예제 #1
0
        static bool EncodeH264Stream(Options opt, Transcoder transcoder)
        {
            bool success = false;

            try
            {
                using (var file = System.IO.File.OpenRead(opt.InputFile))
                {
                    int videoBufferSize = MediaSample.VideoBufferSizeInBytes(opt.Width, opt.Height, opt.Color.Id);

                    if (videoBufferSize <= 0)
                    {
                        return(false);
                    }

                    MediaSample mediaSample = new MediaSample();
                    MediaBuffer mediaBuffer = new MediaBuffer(videoBufferSize);
                    mediaSample.Buffer = mediaBuffer;

                    int readBytes;

                    while (true)
                    {
                        mediaBuffer.SetData(0, videoBufferSize);
                        readBytes = file.Read(mediaBuffer.Start, 0, mediaBuffer.DataSize);
                        if (readBytes == videoBufferSize)
                        {
                            mediaBuffer.SetData(0, readBytes);

                            if (!transcoder.Push(0, mediaSample))
                            {
                                PrintStatus("Transcoder push", transcoder.Error);
                                success = false;
                                break;
                            }

                            success = true;
                        }
                        else
                        {
                            if (!transcoder.Flush())
                            {
                                success = false;
                            }

                            PrintStatus("Transcoder flush", transcoder.Error);

                            break;
                        }
                    }
                }
            }
            catch (System.IO.DirectoryNotFoundException dnfe)
            {
                Console.WriteLine(dnfe);
                success = false;
            }

            return(success);
        }
예제 #2
0
        static bool Transcode(Options opt)
        {
            using (Transcoder transcoder = new Transcoder())
            {
                transcoder.AllowDemoMode = true;

                MediaSocket inSocket  = CreateInputSocket(opt);
                MediaSocket outSocket = CreateOutputSocket(opt);

                transcoder.Inputs.Add(inSocket);
                transcoder.Outputs.Add(outSocket);

                DeleteFile(opt.OutputFile);

                if (!transcoder.Open())
                {
                    PrintStatus("Transcoder open", transcoder.Error);
                    return(false);
                }

                for (int fileCount = 0; ; fileCount++)
                {
                    string pattern  = "au_{0:0000}.h264";
                    string fileName = string.Format(pattern, fileCount);
                    string filePath = Path.Combine(opt.InputDir, fileName);

                    if (!File.Exists(filePath))
                    {
                        fileName = string.Format(pattern, fileCount - 1);
                        Console.WriteLine("Decoded " + fileCount + " files." + "(last decoded file: " + fileName + ")");
                        break;
                    }

                    var sample = new MediaSample();
                    sample.Buffer = new MediaBuffer(File.ReadAllBytes(filePath));

                    if (!transcoder.Push(0, sample))
                    {
                        PrintStatus("Transcoder push", transcoder.Error);
                        return(false);
                    }
                }

                if (!transcoder.Flush())
                {
                    PrintStatus("Transcoder flush", transcoder.Error);
                    return(false);
                }

                Console.WriteLine("Output file: " + opt.OutputFile);

                transcoder.Close();

                return(true);
            }
        }
예제 #3
0
        static bool transcodeAUs(Options opt)
        {
            using (var transcoder = new Transcoder())
            {
                transcoder.AllowDemoMode = true;

                string imgFile = BuildImgPath(opt, 0);

                if (!setTranscode(transcoder, imgFile, opt))
                {
                    return(false);
                }

                for (int i = 0; ; i++)
                {
                    if (i > 0)
                    {
                        imgFile = BuildImgPath(opt, i);
                    }

                    if (!File.Exists(imgFile))
                    {
                        break;
                    }

                    var sample = new MediaSample();
                    sample.Buffer = new MediaBuffer(File.ReadAllBytes(imgFile));

                    if (!transcoder.Push(0, sample))
                    {
                        PrintError("Transcoder push", transcoder.Error);
                        return(false);
                    }
                }

                if (!transcoder.Flush())
                {
                    PrintError("Transcoder flush", transcoder.Error);
                    return(false);
                }

                Console.WriteLine("Output file: " + opt.OutputFile);

                transcoder.Close();
            }

            return(true);
        }
예제 #4
0
        static bool DecodeJpeg(string inputFile, string outputFile)
        {
            int frameWidth, frameHeight;

            if (!GetFrameSize(inputFile, out frameWidth, out frameHeight))
            {
                return(false);
            }

            Console.WriteLine("Input frame size: {0}x{1}", frameWidth, frameHeight);

            // read input bytes
            byte[] inputData;
            try
            {
                inputData = System.IO.File.ReadAllBytes(inputFile);
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.ToString());
                return(false);
            }

            DeleteFile(outputFile);

            MediaSocket inSocket  = createInputSocket(frameWidth, frameHeight);
            MediaSocket outSocket = createOutputSocket(outputFile, frameWidth, frameHeight);

            // create Transcoder
            using (Transcoder transcoder = new Transcoder())
            {
                transcoder.AllowDemoMode = true;
                transcoder.Inputs.Add(inSocket);
                transcoder.Outputs.Add(outSocket);

                bool res = transcoder.Open();
                PrintError("Open Transcoder", transcoder.Error);
                if (!res)
                {
                    return(false);
                }

                MediaBuffer buffer = new MediaBuffer();
                buffer.Attach(inputData, true);

                MediaSample sample = new MediaSample();
                sample.Buffer = buffer;

                res = transcoder.Push(0, sample);

                PrintError("Push Transcoder", transcoder.Error);
                if (!res)
                {
                    return(false);
                }

                transcoder.Flush();
                transcoder.Close();
            }

            return(true);
        }
예제 #5
0
        /*
         * uncompressed audio and video input
         */
        public static bool Run(MediaSocket vinput, string vfile, MediaSocket ainput, string afile, MediaSocket output)
        {
            bool res;

            TrackState vtrack = new TrackState();
            TrackState atrack = new TrackState();

            using (UncompressedAVSplitter vsplit = new UncompressedAVSplitter())
                using (UncompressedAVSplitter asplit = new UncompressedAVSplitter())
                    using (var transcoder = new Transcoder()
                    {
                        AllowDemoMode = true
                    })
                    {
                        try
                        {
                            if (vinput != null)
                            {
                                Console.WriteLine("video input file: \"{0}\"", vfile);
                                vsplit.Init(vinput, vfile);
                                Console.WriteLine("OK");
                            }

                            if (ainput != null)
                            {
                                Console.WriteLine("audio input file: \"{0}\"", afile);
                                asplit.Init(ainput, afile);
                                Console.WriteLine("OK");
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                            return(false);
                        }

                        // setup transcoder
                        int trackIndex = 0; // start index

                        if (vinput != null)
                        {
                            transcoder.Inputs.Add(vinput);
                            vtrack.Index = trackIndex++;
                        }

                        if (ainput != null)
                        {
                            transcoder.Inputs.Add(ainput);
                            atrack.Index = trackIndex++;
                        }

                        transcoder.Outputs.Add(output);

                        res = transcoder.Open();
                        PrintError("transcoder open", transcoder.Error);
                        if (!res)
                        {
                            return(false);
                        }

                        // transcoding loop
                        for (;;)
                        {
                            if (vtrack.Index != TrackState.Disabled && vtrack.Frame == null)
                            {
                                vtrack.Frame = vsplit.GetFrame();
                            }

                            if (atrack.Index != TrackState.Disabled && atrack.Frame == null)
                            {
                                atrack.Frame = asplit.GetFrame();
                            }

                            TrackState track = SelectMuxTrack(vtrack, atrack);

                            if (track == null)
                            {
                                break;
                            }

                            // log
                            if (track.Frame != null)
                            {
                                if (track.Frame.StartTime - track.Progress >= 1.0)
                                {
                                    track.Progress = track.Frame.StartTime;
                                    Console.WriteLine("track {0} frame #{1} pts:{2}", track.Index, track.FrameCount, track.Frame.StartTime);
                                }
                            }
                            else
                            {
                                Console.WriteLine("track {0} eos", track.Index);
                            }

                            if (track.Frame != null)
                            {
                                res = transcoder.Push(track.Index, track.Frame);
                                if (!res)
                                {
                                    PrintError("transcoder push frame", transcoder.Error);
                                    return(false);
                                }
                                track.Frame = null; // clear the muxed frame in order to read to the next one
                                track.FrameCount++;
                            }
                            else
                            {
                                res = transcoder.Push(track.Index, null);
                                if (!res)
                                {
                                    PrintError("transcoder push eos", transcoder.Error);
                                    return(false);
                                }
                                track.Index = TrackState.Disabled; // disable track
                            }
                        }

                        res = transcoder.Flush();
                        if (!res)
                        {
                            PrintError("transcoder flush", transcoder.Error);
                            return(false);
                        }
                        transcoder.Close();
                    }

            return(true);
        }
예제 #6
0
        static void EncodeDirectShowInput(string inputFile, string outputFile, string preset)
        {
            if (File.Exists(outputFile))
            {
                File.Delete(outputFile);
            }

            DSGraph    dsGraph    = new DSGraph();
            Transcoder transcoder = new Transcoder();

            // In order to use the OEM release for testing (without a valid license) the transcoder demo mode must be enabled.
            transcoder.AllowDemoMode = true;

            try
            {
                Console.WriteLine("Initializing DirectShow graph.");

                /*
                 *  If the source is a DirectShow filter instead of a file then:
                 * 1) Create an instance of the source filter
                 * 2) Configure source filter
                 * 3) Call dsGraph.Init(sourceFilter);
                 *
                 * For example dsGraph.Init(inputFile) can be replaced with the following code:
                 *
                 *   1) Create an instance of the source filter
                 *
                 *      // FileSourceAsync filter
                 *      IBaseFilter sourceFilter = Util.CreateFilter(new Guid("e436ebb5-524f-11ce-9f53-0020af0ba770"));
                 *
                 *      // or WM ASF Reader filter
                 *      IBaseFilter sourceFilter = Util.CreateFilter(new Guid("187463A0-5BB7-11D3-ACBE-0080C75E246E"));
                 *
                 *   2) Configure source filter
                 *      IFileSourceFilter fileSourceFilter = sourceFilter as IFileSourceFilter;
                 *      fileSourceFilter.Load(inputFile, null);
                 *
                 *   3)
                 *      dsGraph.Init(sourceFilter);
                 */

                dsGraph.Init(inputFile);

                if (dsGraph.videoGrabber != null)
                {
                    ConfigureVideoInput(dsGraph, transcoder);
                }

                if (dsGraph.audioGrabber != null)
                {
                    ConfigureAudioInput(dsGraph, transcoder);
                }

                if ((dsGraph.videoGrabber == null) && (dsGraph.audioGrabber == null))
                {
                    Console.WriteLine("No audio or video can be read from the DirectShow graph.");
                    return;
                }

                // Configure output
                {
                    MediaSocket outSocket = MediaSocket.FromPreset(preset);
                    outSocket.File = outputFile;
                    transcoder.Outputs.Add(outSocket);
                }

                bool res = transcoder.Open();

                PrintError("Open Transcoder", transcoder.Error);
                if (!res)
                {
                    return;
                }

                //DBG
                //var rot = new DsROTEntry(dsGraph.graph);

                Console.WriteLine("Running DirectShow graph.");
                int hr = dsGraph.mediaControl.Run();
                DsError.ThrowExceptionForHR(hr);

                while (true)
                {
                    FilterState fs;
                    dsGraph.mediaControl.GetState(-1, out fs);

                    if (fs != FilterState.Running)
                    {
                        break;
                    }

                    EventCode ev;
                    dsGraph.mediaEvent.WaitForCompletion(1000, out ev);

                    if (EventCode.Complete == ev)
                    {
                        break;
                    }
                }

                Console.WriteLine("DirectShow graph is stopped.");

                if ((dsGraph.videoGrabberCB != null) && (dsGraph.videoGrabberCB.TranscoderError != null))
                {
                    PrintError("Transcoder Error", transcoder.Error);
                }

                if ((dsGraph.audioGrabberCB != null) && (dsGraph.audioGrabberCB.TranscoderError != null))
                {
                    PrintError("Transcoder Error", transcoder.Error);
                }

                Console.WriteLine("Closing transcoder.");

                if (!transcoder.Flush())
                {
                    PrintError("Flush Transcoder", transcoder.Error);
                }

                transcoder.Close();
            }
            finally
            {
                dsGraph.Reset();
                transcoder.Dispose();
            }
        }
예제 #7
0
        static bool Encode(Options opt)
        {
            string       outFilename    = "cube." + opt.FileExtension;
            const int    imageCount     = 250;
            const double inputFrameRate = 25.0;

            using (var transcoder = new Transcoder())
            {
                // In order to use the OEM release for testing (without a valid license),
                // the transcoder demo mode must be enabled.
                transcoder.AllowDemoMode = true;

                try
                {
                    bool result;

                    try
                    {
                        File.Delete(outFilename);
                    }catch {}

                    // Configure Input
                    {
                        using (MediaInfo medInfo = new MediaInfo())
                        {
                            medInfo.Inputs[0].File = GetImagePath(0);

                            result = medInfo.Open();
                            PrintError("Open MediaInfo", medInfo.Error);
                            if (!result)
                            {
                                return(false);
                            }

                            VideoStreamInfo vidInfo = (VideoStreamInfo)medInfo.Outputs[0].Pins[0].StreamInfo.Clone();
                            vidInfo.FrameRate = inputFrameRate;

                            MediaPin pin = new MediaPin();
                            pin.StreamInfo = vidInfo;

                            MediaSocket socket = new MediaSocket();
                            socket.Pins.Add(pin);

                            transcoder.Inputs.Add(socket);
                        }
                    }

                    // Configure Output
                    {
                        MediaSocket socket = MediaSocket.FromPreset(opt.PresetID);
                        socket.File = outFilename;

                        transcoder.Outputs.Add(socket);
                    }

                    // Encode Images
                    result = transcoder.Open();
                    PrintError("Open Transcoder", transcoder.Error);
                    if (!result)
                    {
                        return(false);
                    }

                    for (int i = 0; i < imageCount; i++)
                    {
                        string imagePath = GetImagePath(i);

                        MediaBuffer mediaBuffer = new MediaBuffer(File.ReadAllBytes(imagePath));

                        MediaSample mediaSample = new MediaSample();
                        mediaSample.StartTime = i / inputFrameRate;
                        mediaSample.Buffer    = mediaBuffer;

                        if (!transcoder.Push(0, mediaSample))
                        {
                            PrintError("Push Transcoder", transcoder.Error);
                            return(false);
                        }
                    }

                    result = transcoder.Flush();
                    PrintError("Flush Transcoder", transcoder.Error);
                    if (!result)
                    {
                        return(false);
                    }

                    transcoder.Close();
                    Console.WriteLine("Output video: \"{0}\"", outFilename);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    return(false);
                }
            }

            return(true);
        }
예제 #8
0
        static bool SplitFile(string inputFile)
        {
            string       outputFileExt     = ".mpg";
            string       encodingPreset    = Preset.Video.DVD.NTSC_4x3_PCM;
            const double splitPartDuration = 10;     // seconds

            int audioStreamIndex = -1;
            int videoStreamIndex = -1;

            int audioFrameSize  = 0;
            int audioSampleRate = 0;

            using (var transcoder1 = new Transcoder())
            {
                // In order to use the OEM release for testing (without a valid license) the transcoder demo mode must be enabled.
                transcoder1.AllowDemoMode = true;

                using (var inputInfo = new MediaInfo())
                {
                    inputInfo.Inputs[0].File = inputFile;
                    if (!inputInfo.Open())
                    {
                        PrintError("Open MediaInfo", inputInfo.Error);
                        return(false);
                    }

                    // Configure transcoder1 input and output
                    var inputSocket = MediaSocket.FromMediaInfo(inputInfo);
                    transcoder1.Inputs.Add(inputSocket);

                    for (int i = 0; i < inputSocket.Pins.Count; i++)
                    {
                        StreamInfo inputStreamInfo = inputSocket.Pins[i].StreamInfo;

                        if ((inputStreamInfo.MediaType == MediaType.Video) && videoStreamIndex < 0)
                        {
                            var streamInfo = new VideoStreamInfo();

                            VideoStreamInfo inputVideoStreamInfo = inputStreamInfo as VideoStreamInfo;

                            streamInfo.ColorFormat = ColorFormat.YUV420;
                            streamInfo.StreamType  = StreamType.UncompressedVideo;
                            streamInfo.ScanType    = inputVideoStreamInfo.ScanType;

                            streamInfo.FrameWidth         = inputVideoStreamInfo.FrameWidth;
                            streamInfo.FrameHeight        = inputVideoStreamInfo.FrameHeight;
                            streamInfo.DisplayRatioWidth  = inputVideoStreamInfo.DisplayRatioWidth;
                            streamInfo.DisplayRatioHeight = inputVideoStreamInfo.DisplayRatioHeight;

                            var outputPin = new MediaPin();
                            outputPin.StreamInfo = streamInfo;

                            var outputSocket = new MediaSocket();
                            outputSocket.Pins.Add(outputPin);
                            outputSocket.StreamType = streamInfo.StreamType;

                            videoStreamIndex = transcoder1.Outputs.Count;
                            transcoder1.Outputs.Add(outputSocket);
                        }

                        if ((inputStreamInfo.MediaType == MediaType.Audio) && audioStreamIndex < 0)
                        {
                            var streamInfo = new AudioStreamInfo();

                            AudioStreamInfo inputAudioStreamInfo = inputStreamInfo as AudioStreamInfo;

                            streamInfo.StreamType = StreamType.LPCM;

                            streamInfo.PcmFlags      = inputAudioStreamInfo.PcmFlags;
                            streamInfo.Channels      = inputAudioStreamInfo.Channels;
                            streamInfo.SampleRate    = inputAudioStreamInfo.SampleRate;
                            streamInfo.BitsPerSample = inputAudioStreamInfo.BitsPerSample;

                            var outputPin = new MediaPin();
                            outputPin.StreamInfo = streamInfo;

                            var outputSocket = new MediaSocket();
                            outputSocket.Pins.Add(outputPin);
                            outputSocket.StreamType = streamInfo.StreamType;

                            audioStreamIndex = transcoder1.Outputs.Count;
                            transcoder1.Outputs.Add(outputSocket);

                            audioFrameSize  = inputAudioStreamInfo.Channels * inputAudioStreamInfo.BitsPerSample / 8;
                            audioSampleRate = inputAudioStreamInfo.SampleRate;
                        }
                    }
                }

                bool res = transcoder1.Open();
                PrintError("Open Transcoder1", transcoder1.Error);
                if (!res)
                {
                    return(false);
                }

                var sample = new MediaSample();
                int outputIndex;

                int        splitPartNum  = 0;
                double     splitTime     = splitPartDuration;
                double     partStartTime = 0;
                Transcoder transcoder2   = null;

                List <SplitRecord> splitStats = new List <SplitRecord>();

                List <MediaSample> audioSamplesQueue = new List <MediaSample>();

                try
                {
                    for (; ;)
                    {
                        if ((audioSamplesQueue.Count > 0) && (audioSamplesQueue[0].StartTime < splitTime))
                        {
                            outputIndex = audioStreamIndex;
                            sample      = audioSamplesQueue[0];
                            audioSamplesQueue.RemoveAt(0);
                        }
                        else
                        {
                            if (!transcoder1.Pull(out outputIndex, sample))
                            {
                                break;
                            }

                            if ((outputIndex != audioStreamIndex) &&
                                (outputIndex != videoStreamIndex))
                            {
                                continue;
                            }
                        }

                        if (outputIndex == audioStreamIndex)
                        {
                            double sampleDuration = (double)(sample.Buffer.DataSize) / (double)(audioFrameSize * audioSampleRate);
                            if (sample.StartTime >= splitTime)
                            {
                                audioSamplesQueue.Add(sample);
                                sample = new MediaSample();
                                continue;
                            }
                            else if ((sample.StartTime + sampleDuration) > splitTime)
                            {
                                double sample1Duration   = splitTime - sample.StartTime;
                                int    sample1BufferSize = (int)(sample1Duration * audioSampleRate) * audioFrameSize;

                                if (sample1BufferSize < sample.Buffer.DataSize)
                                {
                                    int buffer2Size = sample.Buffer.DataSize - sample1BufferSize;
                                    var buffer2     = new MediaBuffer(new byte[buffer2Size]);
                                    buffer2.SetData(0, buffer2Size);

                                    Array.Copy(sample.Buffer.Start, sample1BufferSize, buffer2.Start, 0, buffer2Size);

                                    var sample2 = new MediaSample();
                                    sample2.StartTime = sample.StartTime + sample1Duration;
                                    sample2.Buffer    = buffer2;

                                    if (sample1BufferSize > 0)
                                    {
                                        sample.Buffer.SetData(sample.Buffer.DataOffset, sample1BufferSize);
                                    }
                                    else
                                    {
                                        sample.Buffer.SetData(0, 0);
                                    }

                                    audioSamplesQueue.Add(sample2);
                                }
                            }
                        }


                        if ((transcoder2 == null) ||
                            ((sample.StartTime + 0.0001 >= splitTime) && (outputIndex == videoStreamIndex)))
                        {
                            if (transcoder2 != null)
                            {
                                transcoder2.Flush();
                                transcoder2.Close();
                                transcoder2.Dispose();
                            }

                            SplitRecord splitStat = new SplitRecord();
                            splitStat.StartTime       = splitTime;
                            splitStat.StartTimeActual = sample.StartTime;

                            splitPartNum += 1;
                            splitTime     = splitPartNum * splitPartDuration;
                            partStartTime = sample.StartTime;

                            transcoder2 = new Transcoder();
                            transcoder2.AllowDemoMode = true;

                            // Configure transcoder2 input and output
                            {
                                for (int i = 0; i < transcoder1.Outputs.Count; i++)
                                {
                                    var streamInfo = transcoder1.Outputs[i].Pins[0].StreamInfo.Clone() as StreamInfo;
                                    var pin        = new MediaPin();
                                    pin.StreamInfo = streamInfo;

                                    var socket = new MediaSocket();
                                    socket.Pins.Add(pin);
                                    socket.StreamType = streamInfo.StreamType;

                                    transcoder2.Inputs.Add(socket);
                                }

                                var outputSocket = MediaSocket.FromPreset(encodingPreset);

                                string fileName = GenerateOutputFileName(inputFile, splitPartNum) + outputFileExt;
                                string filePath = Path.Combine(GetExeDir(), fileName);

                                try
                                {
                                    File.Delete(filePath);
                                }
                                catch { }

                                outputSocket.File = filePath;
                                transcoder2.Outputs.Add(outputSocket);

                                splitStat.FileName = fileName;
                            }

                            if (splitStats.Count > 0)
                            {
                                SplitRecord lastRecord = splitStats[splitStats.Count - 1];
                                lastRecord.EndTime       = splitStat.StartTime;
                                lastRecord.EndTimeActual = splitStat.StartTimeActual;
                            }

                            splitStats.Add(splitStat);

                            res = transcoder2.Open();
                            PrintError("Open Transcoder2", transcoder2.Error);
                            if (!res)
                            {
                                return(false);
                            }
                        }

                        if ((splitStats.Count > 0))
                        {
                            SplitRecord lastRecord = splitStats[splitStats.Count - 1];
                            lastRecord.EndTime       = sample.StartTime;
                            lastRecord.EndTimeActual = lastRecord.EndTime;
                        }

                        if (sample.StartTime >= 0)
                        {
                            sample.StartTime = sample.StartTime - partStartTime;
                        }

                        res = transcoder2.Push(outputIndex, sample);
                        if (!res)
                        {
                            PrintError("Push Transcoder2", transcoder2.Error);
                            return(false);
                        }
                    }
                }
                finally
                {
                    if (transcoder2 != null)
                    {
                        transcoder2.Flush();
                        transcoder2.Close();
                        transcoder2.Dispose();
                        transcoder2 = null;
                    }
                }

                if ((transcoder1.Error.Facility != ErrorFacility.Codec) ||
                    (transcoder1.Error.Code != (int)CodecError.EOS))
                {
                    PrintError("Pull Transcoder1", transcoder1.Error);
                    return(false);
                }

                transcoder1.Close();

                // print split stats
                Console.WriteLine();
                foreach (var record in splitStats)
                {
                    Console.WriteLine("{0} start: {1} end: {2} act. start: {3} act. end: {4}", record.FileName,
                                      FormatTime(record.StartTime), FormatTime(record.EndTime), FormatTime(record.StartTimeActual), FormatTime(record.EndTimeActual));
                }
                Console.WriteLine();
            }

            return(true);
        }
 private bool Drain()
 {
     return(EncodeAndMux(_audioEncoder, null, _audioMuxIndex) &&
            EncodeAndMux(_videoEncoder, null, _videoMuxIndex) &&
            _mux.Flush());
 }
예제 #10
0
        static bool EncodeImagesToMpeg2Video(string imagesFolder, string outputFile, int imagesCount, int videoFramesPerImage, int step, string encodingPreset)
        {
            double frameRate = -1;

            switch (encodingPreset)
            {
            case Preset.Video.DVD.PAL_4x3_MP2:
            case Preset.Video.DVD.PAL_16x9_MP2:
                frameRate = 25.0;
                break;

            case Preset.Video.DVD.NTSC_4x3_MP2:
            case Preset.Video.DVD.NTSC_16x9_MP2:
                frameRate = 30000.0 / 1001;     // 29.97
                break;

            default:
                return(false);
            }

            Transcoder transcoder = new Transcoder();

            // In order to use the OEM release for testing (without a valid license) the transcoder demo mode must be enabled.
            transcoder.AllowDemoMode = true;

            try
            {
                File.Delete(outputFile);

                // Configure Input
                {
                    MediaInfo info = new MediaInfo();
                    info.InputFile = GetImagePath(imagesFolder, 0);
                    if (!info.Load())
                    {
                        PrintError("MediaInfo load", info.Error);
                        return(false);
                    }

                    MediaPin        pin   = new MediaPin();
                    VideoStreamInfo vInfo = (VideoStreamInfo)info.Streams[0];
                    vInfo.FrameRate = frameRate;
                    pin.StreamInfo  = vInfo;

                    MediaSocket socket = new MediaSocket();
                    socket.Pins.Add(pin);

                    transcoder.Inputs.Add(socket);
                }

                // Configure Output
                {
                    MediaSocket socket = MediaSocket.FromPreset(encodingPreset);
                    socket.File = outputFile;
                    transcoder.Outputs.Add(socket);
                }

                // Encode Images
                if (!transcoder.Open())
                {
                    PrintError("Transcoder open", transcoder.Error);
                    return(false);
                }

                int totalVideoFrames = imagesCount * videoFramesPerImage;

                for (int i = 0; i < totalVideoFrames; i++)
                {
                    string      imagePath   = GetImagePath(imagesFolder, i / videoFramesPerImage * step);
                    MediaBuffer mediaBuffer = new MediaBuffer(File.ReadAllBytes(imagePath));
                    MediaSample mediaSample = new MediaSample();
                    mediaSample.Buffer = mediaBuffer;

                    mediaSample.StartTime = i / frameRate;

                    if (!transcoder.Push(0, mediaSample))
                    {
                        PrintError("Transcoder write", transcoder.Error);
                        return(false);
                    }
                }

                if (!transcoder.Flush())
                {
                    PrintError("Transcoder flush", transcoder.Error);
                    return(false);
                }

                transcoder.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return(false);
            }
            finally
            {
                transcoder.Dispose();
            }

            return(true);
        }