예제 #1
0
    public MP4Box this [uint index1, ulong index2]
    {
        get
        {
            if (this.arr == null)
            {
                return(null);
            }

            for (int i = 0; i < this.arr.Count; i++)
            {
                MP4Box box = (MP4Box)this.arr[i];
                if ((box.Type == index1) && (index2 >= box.Pos) &&
                    (index2 < (box.Pos + box.Size)))
                {
                    return(box);
                }
                box = box[index1, index2];
                if (box != null)
                {
                    return(box);
                }
            }

            return(null);
        }
    }
예제 #2
0
    public MP4Box this [uint index]
    {
        get
        {
            if (this.arr == null)
            {
                return(null);
            }

            for (int i = 0; i < this.arr.Count; i++)
            {
                MP4Box box = (MP4Box)this.arr[i];
                if (box.Type == index)
                {
                    return(box);
                }
                box = box[index];
                if (box != null)
                {
                    return(box);
                }
            }

            return(null);
        }
    }
예제 #3
0
    public void WriteBytes(MemoryStream ms)
    {
        byte [] tmp;

        tmp = BitConverter.GetBytes(this.shortsize);
        Utility.LeReverse(tmp);
        ms.Write(tmp, 0, tmp.Length);

        tmp = BitConverter.GetBytes(this.type);
        ms.Write(tmp, 0, tmp.Length);

        if (this.shortsize == 1)
        {
            tmp = BitConverter.GetBytes(this.size);
            Utility.LeReverse(tmp);
            ms.Write(tmp, 0, tmp.Length);
        }

        if (this.type == MP4Types.UUID)
        {
            ms.Write(this.uuid, 0, this.uuid.Length);
        }

        try
        {
            this.GetType().InvokeMember("WriteBytes" + this.TypeStr.ToUpper(),
                                        BindingFlags.Default | BindingFlags.Public |
                                        BindingFlags.NonPublic | BindingFlags.Instance |
                                        BindingFlags.InvokeMethod, null, this,
                                        new object[] { ms });
        }
        catch (MissingMethodException)
        {
            if (this.data != null)
            {
                tmp = (byte [])this.data;
                ms.Write(tmp, 0, tmp.Length);
            }
        }

        if (this.children != null)
        {
            for (int i = 0; i < this.children.Count; i++)
            {
                MP4Box box = (MP4Box)this.children[i];
                box.WriteBytes(ms);
            }
        }
    }
예제 #4
0
        //public async void OnErrorReceived(object sender, DataReceivedEventArgs d)
        //{
        //    Console.WriteLine(d.Data);
        //    await webSocket.SendMessageToAllAsync(d.Data);
        //}

        //public async void OnConvertionDone(object sender, EventArgs e)
        //{
        //    Console.WriteLine("Done!");
        //}

        internal MediaConverter(string ffmpegExecutablePath, string mp4boxExecutablePath)
        {
            // Working folders
            //this.tempFolder = tempFolder;
            //this.convertedFolder = convertedFolder;
            //this.compresssedFolder = compressedFolder;

            // Contruct FFMPEG
            this.ffmpeg = new FFMPEG(ffmpegExecutablePath);
            this.ffmpeg.ErrorReceived  += ErrorReceived;
            this.ffmpeg.ConvertionDone += ConvertionDone;

            //Construct MP4BOX
            this.mp4box = new MP4Box(mp4boxExecutablePath);
            this.mp4box.ErrorReceived  += ErrorReceived;
            this.mp4box.ConvertionDone += ConvertionDone;
        }
예제 #5
0
        private void DoMuxResult(EncodeInfo job)
        {
            switch (job.EncodingProfile.OutFormat)
            {
            case OutputType.OutputTs:
            case OutputType.OutputM2Ts:
            case OutputType.OutputAvchd:
            case OutputType.OutputBluRay:
                TsMuxeR tsmuxer = new TsMuxeR();
                tsmuxer.SetJob(job);
                _worker.DoWork += tsmuxer.DoEncode;
                Log.Info("TSMuxer.DoEncode()");
                break;

            case OutputType.OutputMatroska:
            case OutputType.OutputWebM:
                MkvMerge mkvmerge = new MkvMerge();
                mkvmerge.SetJob(job);
                _worker.DoWork += mkvmerge.DoEncode;
                Log.Info("MKVmergeEncoder.DoEncode()");
                break;

            case OutputType.OutputDvd:
                DvdAuthor dvdauthor = new DvdAuthor();
                dvdauthor.SetJob(job);
                _worker.DoWork += dvdauthor.DoEncode;
                Log.Info("DVDAuthor.DoEncode()");
                break;

            case OutputType.OutputMp4:
                MP4Box box = new MP4Box();
                box.SetJob(job);
                _worker.DoWork += box.DoEncode;
                Log.Info("MP4Box.DoEncode()");
                break;
            }
        }
예제 #6
0
        private bool MP4BoxRemux()
        {
            _jobStatus.ErrorMsg           = "";
            _jobStatus.PercentageComplete = 100; //all good to start with
            _jobStatus.ETA = "";

            Util.FileIO.TryFileDelete(RemuxedTempFile);
            string Parameters = " -keep-sys -keep-all";

            //Check for Null FPS (bug with MediaInfo for some .TS files)
            if (_fps <= 0)
            {
                _jobLog.WriteEntry(this, Localise.GetPhrase("Mp4BoxRemuxAVI FPS 0 reported by video file - non compliant video file, skipping adding to parameter"), Log.LogEntryType.Warning);
                Parameters += " -add " + FilePaths.FixSpaces(_originalFile) +
                              " -new " + FilePaths.FixSpaces(RemuxedTempFile);
            }
            else
            {
                Parameters += " -fps " + _fps.ToString(System.Globalization.CultureInfo.InvariantCulture) +
                              " -add " + FilePaths.FixSpaces(_originalFile) +
                              " -new " + FilePaths.FixSpaces(RemuxedTempFile);
            }

            MP4Box mp4Box = new MP4Box(Parameters, _jobStatus, _jobLog);

            mp4Box.Run();
            if (!mp4Box.Success || _jobStatus.PercentageComplete < GlobalDefs.ACCEPTABLE_COMPLETION)
            {
                _jobLog.WriteEntry(this, Localise.GetPhrase("MP4BoxRemux failed"), Log.LogEntryType.Error);
                _jobStatus.ErrorMsg = Localise.GetPhrase("MP4BoxRemux failed");
                return(false);
            }

            _jobLog.WriteEntry(this, Localise.GetPhrase("MP4Box remux moving file"), Log.LogEntryType.Information);
            return(ReplaceTempRemuxed());
        }
예제 #7
0
    public byte [] DownloadSong(Hashtable song, Progress ProgressCallback)
    {
        int      i;
        Rijndael alg;
        string   strDownloadKey = (string)song["downloadKey"];

        if (strDownloadKey == null)
        {
            throw new Exception("Can't download song without downloadKey");
        }

        byte [] encData = Request((string)song["URL"], null, null,
                                  "downloadKey=" + strDownloadKey,
                                  null, ProgressCallback);

        alg         = Rijndael.Create();
        alg.Mode    = CipherMode.CBC;
        alg.Padding = PaddingMode.None;

        MemoryStream cms = new MemoryStream();

        byte [] ftyp = Encoding.ASCII.GetBytes("\0\0\0\0ftypM4A \0\0\0\0");
        cms.Write(ftyp, 0, ftyp.Length);

        byte [] Key = HexStringToBytes((string)song["encryptionKey"]);
        byte [] IV  = new byte[16];
        Buffer.BlockCopy(encData, 0, IV, 0, 16);

        ICryptoTransform ct = alg.CreateDecryptor(Key, IV);
        CryptoStream     cs =
            new CryptoStream(cms, ct, CryptoStreamMode.Write);

        cs.Write(encData, 16, ((encData.Length - 16) / 16) * 16);
        cs.Close();

        byte [] mp4 = cms.ToArray();

        byte [] moov = Encoding.ASCII.GetBytes("moov");

        for (i = 0; i < mp4.Length - 4; i++)
        {
            if (mp4[i + 0] == moov[0] && mp4[i + 1] == moov[1] &&
                mp4[i + 2] == moov[2] && mp4[i + 3] == moov[3])
            {
                byte [] offb = BitConverter.GetBytes((UInt32)(i - 4));
                if (BitConverter.IsLittleEndian)
                {
                    Array.Reverse(offb, 0, 4);
                }
                Buffer.BlockCopy(offb, 0, mp4, 0, offb.Length);
                break;
            }
        }

        MP4Root root = new MP4Root();

        try
        {
            root.Parse(new MemoryStream(mp4));
        }
        catch (InvalidBoxSizeException e)
        {
        }

        MP4Box mp4a = root[MP4Types.MP4A];

        if (mp4a != null)
        {
            MP4Box sinf = mp4a[MP4Types.SINF];
            if (sinf != null)
            {
                mp4a.Size -= sinf.Size;
                sinf.Free();
            }
        }

        return(root.Bytes);
    }
예제 #8
0
 public InvalidBoxSizeException(MP4Box box) :
     base(String.Format("Box {0} has invalid size {1}",
                        box.TypeStr, box.Size))
 {
     this.box = box;
 }
예제 #9
0
        public static void GetAppVersions(string encPath = "", string javaPath = "")
        {
            if (String.IsNullOrEmpty(encPath))
            {
                encPath = AppSettings.ToolsPath;
            }
            if (String.IsNullOrEmpty(javaPath))
            {
                javaPath = AppSettings.JavaInstallPath;
            }

            X264 x264Enc = new X264();

            AppSettings.Lastx264Ver = x264Enc.GetVersionInfo(encPath, false);

            if (Environment.Is64BitOperatingSystem)
            {
                AppSettings.Lastx26464Ver = x264Enc.GetVersionInfo(encPath, true);
            }

            FfMpeg ffmpeg = new FfMpeg();

            AppSettings.LastffmpegVer = ffmpeg.GetVersionInfo(encPath, false);

            if (Environment.Is64BitOperatingSystem)
            {
                AppSettings.Lastffmpeg64Ver = ffmpeg.GetVersionInfo(encPath, true);
            }

            Eac3To eac3To = new Eac3To();

            AppSettings.Lasteac3ToVer = eac3To.GetVersionInfo(encPath);

            LsDvd lsdvd = new LsDvd();

            AppSettings.LastlsdvdVer = lsdvd.GetVersionInfo(encPath);

            MkvMerge mkvMerge = new MkvMerge();

            AppSettings.LastMKVMergeVer = mkvMerge.GetVersionInfo(encPath);

            MPlayer mplayer = new MPlayer();

            AppSettings.LastMplayerVer = mplayer.GetVersionInfo(encPath);

            TsMuxeR tsmuxer = new TsMuxeR();

            AppSettings.LastTSMuxerVer = tsmuxer.GetVersionInfo(encPath);

            MJpeg mjpeg = new MJpeg();

            AppSettings.LastMJPEGToolsVer = mjpeg.GetVersionInfo(encPath);

            DvdAuthor dvdauthor = new DvdAuthor();

            AppSettings.LastDVDAuthorVer = dvdauthor.GetVersionInfo(encPath);

            MP4Box mp4Box = new MP4Box();

            AppSettings.LastMp4BoxVer = mp4Box.GetVersionInfo(encPath);

            HcEnc hcenc = new HcEnc();

            AppSettings.LastHcEncVer = hcenc.GetVersionInfo(encPath);

            OggEnc ogg = new OggEnc();

            AppSettings.LastOggEncVer = ogg.GetVersionInfo(encPath, false);

            if (AppSettings.UseOptimizedEncoders)
            {
                AppSettings.LastOggEncLancerVer = ogg.GetVersionInfo(encPath, true);
            }

            NeroAACEnc aac = new NeroAACEnc();

            AppSettings.LastNeroAacEncVer = aac.GetVersionInfo(encPath);

            Lame lame = new Lame();

            AppSettings.LastLameVer = lame.GetVersionInfo(encPath);

            VpxEnc vpxEnc = new VpxEnc();

            AppSettings.LastVpxEncVer = vpxEnc.GetVersionInfo(encPath);

            XvidEnc xvidEnc = new XvidEnc();
            string  myVer   = xvidEnc.GetVersionInfo(encPath);

            if (!String.IsNullOrEmpty(javaPath))
            {
                BdSup2SubTool bdSup2Sub = new BdSup2SubTool();
                AppSettings.LastBDSup2SubVer = bdSup2Sub.GetVersionInfo(encPath, javaPath);
            }

            #region Get AviSynth Version

            IGraphBuilder graphBuilder = (IGraphBuilder) new FilterGraph();

            string avsFile = AviSynthGenerator.GenerateTestFile();

            int result = graphBuilder.RenderFile(avsFile, null);

            Log.DebugFormat("RenderFile Result: {0}", result);

            if (result < 0)
            {
                Log.Debug("AviSynth is not installed");
            }
            else
            {
                FileVersionInfo ver    = FileVersionInfo.GetVersionInfo(Path.Combine(Environment.SystemDirectory, "avisynth.dll"));
                string          appVer = String.Format("{0:g}.{1:g}.{2:g}.{3:g}", ver.FileMajorPart, ver.FileMinorPart,
                                                       ver.FileBuildPart, ver.FilePrivatePart);
                Log.DebugFormat("Avisynth version {0:s} installed", appVer);
                AppSettings.LastAviSynthVer = appVer;
            }

            File.Delete(avsFile);
            #endregion

            GetAviSynthPluginsVer();
            GetUpdaterVersion();

            AppSettings.UpdateVersions = false;
            AppSettings.SaveSettings();
        }
예제 #10
0
        /// <summary>
        /// Extracts subtitles from a video file into a SRT format (with same name) and cleans it up.
        /// It will overwrite any existing SRT files
        /// If there are multiple subtitles it extracts them into multiple files with incremental names.
        /// </summary>
        /// <param name="sourceFile">Path to video file</param>
        /// <param name="offset">Offset of the subtitles during extraction</param>
        /// <param name="overWrite">True to overwrite existing SRT files, false to create new ones with incremental names</param>
        /// <param name="languageExtractList">List of 3 digit language codes to extract (blank to extract all, unnamed languages will always be extracted)</param>
        /// <returns>True if successful</returns>
        public bool ExtractSubtitles(string sourceFile, string workingPath, int startTrim, int endTrim, double offset, bool overWrite, List <string> languageExtractList)
        {
            _jobLog.WriteEntry(this, ("Extracting Subtitles from " + sourceFile + " into SRT file"), Log.LogEntryType.Information);
            _jobLog.WriteEntry(this, "Source File : " + sourceFile, Log.LogEntryType.Debug);
            _jobLog.WriteEntry(this, "Working Path " + workingPath, Log.LogEntryType.Debug);
            _jobLog.WriteEntry(this, "Start Trim : " + startTrim.ToString(CultureInfo.InvariantCulture), Log.LogEntryType.Debug);
            _jobLog.WriteEntry(this, "Stop Trim : " + endTrim.ToString(CultureInfo.InvariantCulture), Log.LogEntryType.Debug);
            _jobLog.WriteEntry(this, "Offset : " + offset.ToString(CultureInfo.InvariantCulture), Log.LogEntryType.Debug);

            if (String.IsNullOrEmpty(sourceFile))
            {
                return(true); // nothing to do
            }
            if (!File.Exists(sourceFile))
            {
                _jobLog.WriteEntry(this, ("File does not exist " + sourceFile), Log.LogEntryType.Warning);
                return(true); //nothing to process
            }

            FFmpegMediaInfo mediaInfo = new FFmpegMediaInfo(sourceFile, _jobStatus, _jobLog);

            if (!mediaInfo.Success || mediaInfo.ParseError)
            {
                _jobLog.WriteEntry(this, ("Error reading subtitle info from file"), Log.LogEntryType.Error);
                return(false);
            }

            _jobLog.WriteEntry(this, "Found " + mediaInfo.SubtitleTracks.ToString() + " Subtitle tracks, extract only the first matching track", Log.LogEntryType.Debug);

            bool extractedSubtitle = false;

            for (int i = 0; i < mediaInfo.SubtitleTracks; i++)
            {
                if (extractedSubtitle) // Only extract and use one subtitle (sometimes chapter tracks are misidentified as subtitle tracks)
                {
                    continue;
                }

                // Build the command line
                string parameters    = "";
                string outputSRTFile = ""; // Using Serviio subtitle filename format (filename.srt or filename_language.srt or filename_uniquenumber.srt)

                // Check for language comparison if required
                if (languageExtractList != null)
                {
                    if (languageExtractList.Count > 0) // If list is empty, we extract all
                    {
                        _jobLog.WriteEntry(this, "Subtitle language extraction list -> " + String.Join(",", languageExtractList.ToArray()), Log.LogEntryType.Debug);

                        if (!String.IsNullOrWhiteSpace(mediaInfo.MediaInfo.SubtitleInfo[i].Language))        // check if we have a language defined for this track
                        {
                            if (!languageExtractList.Contains(mediaInfo.MediaInfo.SubtitleInfo[i].Language)) // This language is not in the list of extraction
                            {
                                _jobLog.WriteEntry(this, "Skipping subtitle extraction since subtitle language >" + mediaInfo.MediaInfo.SubtitleInfo[i].Language + "< is NOT in the subtitle language list", Log.LogEntryType.Warning);
                                continue; // Skip this subtitle track
                            }
                        }
                        else
                        {
                            _jobLog.WriteEntry(this, "Extracting subtitle since there is no language defined for track", Log.LogEntryType.Debug);
                        }
                    }
                }

                // Check for existing SRT files
                if (overWrite)
                {
                    outputSRTFile = Path.Combine(workingPath, Path.GetFileNameWithoutExtension(sourceFile)) + (i > 0 ? (String.IsNullOrWhiteSpace(mediaInfo.MediaInfo.SubtitleInfo[i].Language) ? "_" + i.ToString() : "_" + mediaInfo.MediaInfo.SubtitleInfo[i].Language) : "") + ".srt"; // First file user default name, then try to name with language first, if not give a unique number
                    parameters   += " -y";
                }
                else // Create a unique SRT file name
                {
                    int existingSRTCount = 0;
                    outputSRTFile = Path.Combine(workingPath, Path.GetFileNameWithoutExtension(sourceFile)) + ".srt"; // Try default name
                    while (File.Exists(outputSRTFile))
                    {
                        _jobLog.WriteEntry(this, "Subtitle file " + outputSRTFile + " exists, creating a new unique SRT filename", Log.LogEntryType.Debug);
                        outputSRTFile = Path.Combine(workingPath, Path.GetFileNameWithoutExtension(sourceFile)) + (String.IsNullOrWhiteSpace(mediaInfo.MediaInfo.SubtitleInfo[i].Language) ? "_" + existingSRTCount.ToString() : "_" + mediaInfo.MediaInfo.SubtitleInfo[i].Language + (existingSRTCount > 0 ? existingSRTCount.ToString() : "")) + ".srt"; // Create a unique SRT filename, try with language first, if not give a unique identifier, avoid a loop
                        existingSRTCount++;
                    }
                }

                // Build ffmpeg command line
                parameters += " -i " + FilePaths.FixSpaces(sourceFile);
                parameters += " -an -vn";
                parameters += " -map 0:" + mediaInfo.MediaInfo.SubtitleInfo[i].Stream.ToString(); // Subtitle steam no
                parameters += " -scodec copy -copyinkf -f srt " + FilePaths.FixSpaces(outputSRTFile);

                // Now extract it
                _jobLog.WriteEntry(this, "Extracting Subtitle " + (i + 1).ToString() + " with language >" + mediaInfo.MediaInfo.SubtitleInfo[i].Language + "< to " + outputSRTFile, Log.LogEntryType.Debug);
                FFmpeg ffmpeg = new FFmpeg(parameters, _jobStatus, _jobLog);
                ffmpeg.Run();
                if (!ffmpeg.Success)
                {
                    FileIO.TryFileDelete(outputSRTFile); // Delete partial file

                    // Backup, try using MP4Box instead to extract it
                    _jobLog.WriteEntry(this, ("FFMPEG failed to extract subtitles into SRT file, retrying using MP4Box"), Log.LogEntryType.Warning);
                    parameters = "-srt " + (mediaInfo.MediaInfo.SubtitleInfo[i].Stream + 1).ToString() + " " + FilePaths.FixSpaces(sourceFile);
                    // MP4Box create an output file called <input>_<track>_text.srt
                    // Check if the output srt exists and then rename it if it does
                    string tempSrtOutput = FilePaths.GetFullPathWithoutExtension(sourceFile) + "_" + (mediaInfo.MediaInfo.SubtitleInfo[i].Stream + 1).ToString() + "_text.srt";
                    bool   tempSrtExists = false;
                    if (File.Exists(tempSrtOutput)) // Save the output srt filename if it exists
                    {
                        try
                        {
                            FileIO.MoveAndInheritPermissions(tempSrtOutput, tempSrtOutput + ".tmp");
                        }
                        catch (Exception e)
                        {
                            _jobLog.WriteEntry(this, ("Error extracting subtitles into SRT file.\r\n" + e.ToString()), Log.LogEntryType.Error);
                            return(false);
                        }
                        tempSrtExists = true;
                    }

                    // Extract the subtitle
                    MP4Box mp4Box = new MP4Box(parameters, _jobStatus, _jobLog);
                    mp4Box.Run();
                    if (!mp4Box.Success)
                    {
                        _jobLog.WriteEntry(this, ("Error extracting subtitles into SRT file"), Log.LogEntryType.Error);
                        FileIO.TryFileDelete(tempSrtOutput); // Delete partial file
                        if (tempSrtExists)
                        {
                            RestoreSavedSrt(tempSrtOutput);
                        }
                        return(false);
                    }

                    if (FileIO.FileSize(tempSrtOutput) <= 0) // MP4Box always return success even if nothing is extracted, so check if has been extracted
                    {
                        _jobLog.WriteEntry(this, "No or empty Subtitle file " + tempSrtOutput + " extracted by MP4Box, skipping", Log.LogEntryType.Debug);
                        FileIO.TryFileDelete(tempSrtOutput); // Delete empty file
                    }
                    else
                    {
                        // Rename the temp output SRT to the expected name
                        try
                        {
                            FileIO.MoveAndInheritPermissions(tempSrtOutput, outputSRTFile);
                        }
                        catch (Exception e)
                        {
                            _jobLog.WriteEntry(this, ("Error extracting subtitles into SRT file.\r\n" + e.ToString()), Log.LogEntryType.Error);
                            FileIO.TryFileDelete(tempSrtOutput); // Delete partial file
                            if (tempSrtExists)
                            {
                                RestoreSavedSrt(tempSrtOutput);
                            }
                            return(false);
                        }
                    }

                    // Restore temp SRT file if it exists
                    if (tempSrtExists)
                    {
                        RestoreSavedSrt(tempSrtOutput);
                    }
                }

                if (FileIO.FileSize(outputSRTFile) <= 0) // Check for empty files
                {
                    _jobLog.WriteEntry(this, "Empty Subtitle file " + outputSRTFile + " extracted, deleting it", Log.LogEntryType.Warning);
                    FileIO.TryFileDelete(outputSRTFile); // Delete empty file
                }
                else
                {
                    // Trim the SRT file if required
                    if (startTrim > 0 || endTrim > 0)
                    {
                        // Get the length of the video, needed to calculate end point
                        float Duration = 0;
                        Duration = VideoParams.VideoDuration(sourceFile);
                        if (Duration <= 0)
                        {
                            FFmpegMediaInfo ffmpegStreamInfo = new FFmpegMediaInfo(sourceFile, _jobStatus, _jobLog);
                            if (ffmpegStreamInfo.Success && !ffmpegStreamInfo.ParseError)
                            {
                                // Converted file should contain only 1 audio stream
                                Duration = ffmpegStreamInfo.MediaInfo.VideoInfo.Duration;
                                _jobLog.WriteEntry(this, ("Video duration") + " : " + Duration.ToString(CultureInfo.InvariantCulture), Log.LogEntryType.Information);

                                if (Duration == 0)
                                {
                                    _jobLog.WriteEntry(this, ("Video duration 0"), Log.LogEntryType.Error);
                                    return(false);
                                }
                            }
                            else
                            {
                                _jobLog.WriteEntry(this, ("Cannot read video duration"), Log.LogEntryType.Error);
                                return(false);
                            }
                        }

                        // Trim the subtitle
                        if (!TrimSubtitle(outputSRTFile, workingPath, startTrim, endTrim, Duration, 0))
                        {
                            _jobLog.WriteEntry(this, ("Error trimming SRT file"), Log.LogEntryType.Error);
                            return(false);
                        }
                    }

                    // Clean it up and offset the SRT if required
                    if (!SRTValidateAndClean(outputSRTFile, offset))
                    {
                        _jobLog.WriteEntry(this, ("Cannot clean and set offset for SRT file"), Log.LogEntryType.Error);
                        return(false);
                    }

                    // Check for empty file
                    if (Util.FileIO.FileSize(outputSRTFile) <= 0)
                    {
                        FileIO.TryFileDelete(outputSRTFile); // Delete the empty file
                        _jobLog.WriteEntry(this, ("No valid SRT file found"), Log.LogEntryType.Warning);
                        continue;                            // check for the next subtitle track
                    }

                    _extractedSRTFile = outputSRTFile; // Save it
                    _jobLog.WriteEntry(this, "Extracted Subtitle file " + outputSRTFile + ", size [KB] " + (FileIO.FileSize(outputSRTFile) / 1024).ToString("N", CultureInfo.InvariantCulture), Log.LogEntryType.Debug);
                    extractedSubtitle = true;          // We have success
                }
            }

            return(true);
        }
예제 #11
0
        private bool MP4BoxRemuxAvi()
        {
            _jobStatus.ErrorMsg           = "";
            _jobStatus.PercentageComplete = 100; //all good to start with
            _jobStatus.ETA = "";

            string fileNameBase   = Path.Combine(_workingPath, Path.GetFileNameWithoutExtension(_originalFile));
            string audioStream    = fileNameBase + "_audio.raw";
            string newAudioStream = fileNameBase + "_audio.aac";
            string videoStream    = fileNameBase + "_video.h264";

            Util.FileIO.TryFileDelete(RemuxedTempFile);

            // Video
            string Parameters = " -keep-sys -aviraw video -out " + FilePaths.FixSpaces(videoStream) + " " + FilePaths.FixSpaces(_originalFile);

            _jobStatus.CurrentAction = Localise.GetPhrase("Remuxing to") + " " + _remuxTo.ToLower() + " " + Localise.GetPhrase("Part") + " 1";

            MP4Box mp4Box = new MP4Box(Parameters, _jobStatus, _jobLog);

            mp4Box.Run();
            if (!mp4Box.Success || _jobStatus.PercentageComplete < GlobalDefs.ACCEPTABLE_COMPLETION) // check for completion of job
            {
                _jobStatus.ErrorMsg = "MP4Box Remux Video AVI failed";
                _jobLog.WriteEntry(this, _jobStatus.ErrorMsg + " at " + _jobStatus.PercentageComplete.ToString(System.Globalization.CultureInfo.InvariantCulture), Log.LogEntryType.Error);
                return(false);
            }

            // Audio
            Parameters = " -keep-all -keep-sys -aviraw audio -out " + FilePaths.FixSpaces(audioStream) + " " + FilePaths.FixSpaces(_originalFile);

            _jobStatus.CurrentAction = Localise.GetPhrase("Remuxing to") + " " + _remuxTo.ToLower() + " " + Localise.GetPhrase("Part") + " 2";

            mp4Box = new MP4Box(Parameters, _jobStatus, _jobLog);
            mp4Box.Run();
            if (!mp4Box.Success || _jobStatus.PercentageComplete < GlobalDefs.ACCEPTABLE_COMPLETION) //check for completion of job
            {
                _jobStatus.ErrorMsg = "MP4Box Remux Audio AVI failed";
                _jobLog.WriteEntry(this, _jobStatus.ErrorMsg + " at " + _jobStatus.PercentageComplete.ToString(System.Globalization.CultureInfo.InvariantCulture), Log.LogEntryType.Error);
                return(false);
            }

            // Check if streams are extracted
            if ((File.Exists(audioStream)) && (File.Exists(videoStream)))
            {
                _jobLog.WriteEntry(this, Localise.GetPhrase("MP4Box remux avi moving file"), Log.LogEntryType.Information);
                try
                {
                    Util.FileIO.TryFileDelete(newAudioStream);
                    FileIO.MoveAndInheritPermissions(audioStream, newAudioStream);
                }
                catch (Exception e)
                {
                    _jobLog.WriteEntry(this, Localise.GetPhrase("Unable to move remuxed stream") + " " + audioStream + " to " + newAudioStream + "\r\nError : " + e.ToString(), Log.LogEntryType.Error);
                    _jobStatus.PercentageComplete = 0;
                    _jobStatus.ErrorMsg           = "Unable to move muxed stream";
                    return(false);
                }

                string mergeParameters = " -keep-sys -keep-all";

                //Check for Null FPS (bug with MediaInfo for some .TS files)
                if (_fps <= 0)
                {
                    _jobLog.WriteEntry(this, Localise.GetPhrase("Mp4BoxRemuxAVI FPS 0 reported by video file - non compliant video file, skipping adding to parameter"), Log.LogEntryType.Warning);
                    mergeParameters += " -add " + FilePaths.FixSpaces(videoStream) +
                                       " -add " + FilePaths.FixSpaces(newAudioStream) +
                                       " -new " + FilePaths.FixSpaces(RemuxedTempFile);
                }
                else
                {
                    mergeParameters += " -fps " + _fps.ToString(System.Globalization.CultureInfo.InvariantCulture) +
                                       " -add " + FilePaths.FixSpaces(videoStream) +
                                       " -add " + FilePaths.FixSpaces(newAudioStream) +
                                       " -new " + FilePaths.FixSpaces(RemuxedTempFile);
                }


                _jobStatus.CurrentAction = Localise.GetPhrase("Remuxing to") + " " + _remuxTo.ToLower() + " " + Localise.GetPhrase("Part") + " 3";

                mp4Box = new MP4Box(mergeParameters, _jobStatus, _jobLog);
                mp4Box.Run();
                if (!mp4Box.Success || _jobStatus.PercentageComplete < GlobalDefs.ACCEPTABLE_COMPLETION) // check for completion
                {
                    _jobStatus.ErrorMsg = "Mp4Box Remux Merger AVI with FPS conversion failed";
                    _jobLog.WriteEntry(this, _jobStatus.ErrorMsg, Log.LogEntryType.Error);
                    return(false);
                }

                Util.FileIO.TryFileDelete(videoStream);
                Util.FileIO.TryFileDelete(newAudioStream);

                _jobLog.WriteEntry(this, Localise.GetPhrase("MP4Box remux AVI trying to move remuxed file"), Log.LogEntryType.Information);
                return(ReplaceTempRemuxed());
            }
            else
            {
                _jobLog.WriteEntry(this, Localise.GetPhrase("MP4Box Remux AVI of") + " " + _originalFile + " " + Localise.GetPhrase("failed.  Extracted video and audio streams not found."), Log.LogEntryType.Error);
                _jobStatus.PercentageComplete = 0;
                _jobStatus.ErrorMsg           = "Remux failed, extracted video streams not found";
                return(false);
            }
        }
예제 #12
0
 public InvalidBoxSizeException( MP4Box box )
     : base(String.Format( "Box {0} has invalid size {1}",
                          box.TypeStr, box.Size ))
 {
     this.box = box;
 }