static bool encode(Options opt) { DeleteFile(opt.OutputFile); MediaSocket inSocket = CreateInputSocket(opt); MediaSocket outSocket = CreateOutputSocket(opt); // create Transcoder using (Transcoder transcoder = new Transcoder()) { transcoder.AllowDemoMode = true; transcoder.Inputs.Add(inSocket); transcoder.Outputs.Add(outSocket); bool res = transcoder.Open(); PrintStatus("Transcoder open", transcoder.Error); if (!res) { return(false); } res = transcoder.Run(); PrintStatus("Transcoder run", transcoder.Error); if (!res) { return(false); } transcoder.Close(); PrintStatus("Transcoder close", transcoder.Error); } return(true); }
// return error message or null if success public static string ConvertFileWithPreset(string inputFile, string outputFile, string outputPreset, EventHandler <TranscoderContinueEventArgs> onContinue, EventHandler <TranscoderProgressEventArgs> onProgress, EventHandler <TranscoderStatusEventArgs> onStatus ) { using (MediaInfo mediaInfo = new MediaInfo()) { mediaInfo.Inputs[0].File = inputFile; if (!mediaInfo.Open()) { return(FormatErrorMessage(mediaInfo.Error)); } using (Transcoder t = new Transcoder()) { // In order to use the OEM release for testing (without a valid license) the transcoder demo mode must be enabled. t.AllowDemoMode = true; if (onContinue != null) { t.OnContinue += onContinue; } if (onProgress != null) { t.OnProgress += onProgress; } if (onStatus != null) { t.OnStatus += onStatus; } MediaSocket insocket = MediaSocket.FromMediaInfo(mediaInfo); t.Inputs.Add(insocket); MediaSocket outsocket = MediaSocket.FromPreset(outputPreset); if (outsocket == null) { return("Cannot create output preset"); } outsocket.File = outputFile; t.Outputs.Add(outsocket); if (!t.Open()) { return(FormatErrorMessage(t.Error)); } if (!t.Run()) { return(FormatErrorMessage(t.Error)); } t.Close(); } } return(null); // no error }
static bool Encode(Options opt) { DeleteFile(opt.OutputFile); MediaSocket inSocket = new MediaSocket(); inSocket.File = opt.InputFile; MediaSocket outSocket = CreateOutputSocket(opt); // create Transcoder using (Transcoder transcoder = new Transcoder()) { transcoder.AllowDemoMode = true; transcoder.Inputs.Add(inSocket); transcoder.Outputs.Add(outSocket); if (!transcoder.Open()) { PrintError("Transcoder open", transcoder.Error); return(false); } if (!transcoder.Run()) { PrintError("Transcoder run", transcoder.Error); return(false); } transcoder.Close(); } return(true); }
static bool EncodeImageToMpeg2Video(string imageFile, string outputFile, string encodingPreset) { 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 = imageFile; if (!info.Load()) { PrintError("MediaInfo load", info.Error); return(false); } MediaSocket socket = MediaSocket.FromMediaInfo(info); 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); } if (!transcoder.Run()) { PrintError("Transcoder run", transcoder.Error); return(false); } transcoder.Close(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); return(false); } finally { transcoder.Dispose(); } return(true); }
static bool Encode(Options opt) { try { File.Delete(opt.OutputFile); } catch { } using (var transcoder = new Transcoder()) { // Transcoder demo mode must be enabled, // in order to use the OEM release for testing (without a valid license). transcoder.AllowDemoMode = true; // Configure input // The input stream frame rate determines the playback speed var instream = new VideoStreamInfo { StreamType = PrimoSoftware.AVBlocks.StreamType.UncompressedVideo, FrameRate = opt.YuvFps, FrameWidth = opt.YuvWidth, FrameHeight = opt.YuvHeight, ColorFormat = opt.YuvColor.Id, ScanType = ScanType.Progressive }; var inpin = new MediaPin { StreamInfo = instream }; var insocket = new MediaSocket { StreamType = PrimoSoftware.AVBlocks.StreamType.UncompressedVideo, File = opt.YuvFile }; insocket.Pins.Add(inpin); transcoder.Inputs.Add(insocket); // Configure output var outsocket = MediaSocket.FromPreset(opt.OutputPreset.Name); outsocket.File = opt.OutputFile; transcoder.Outputs.Add(outsocket); bool res = transcoder.Open(); PrintError("Open Transcoder", transcoder.Error); if (!res) return false; res = transcoder.Run(); PrintError("Run Transcoder", transcoder.Error); if (!res) return false; transcoder.Close(); } return true; }
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); } }
static bool Encode(Options opt) { DeleteFile(opt.OutputFile); MediaSocket inSocket = new MediaSocket(); inSocket.File = opt.InputFile; MediaSocket outSocket = CreateOutputSocket(opt); bool success = false; // create Transcoder using (Transcoder transcoder = new Transcoder()) { transcoder.AllowDemoMode = true; transcoder.Inputs.Add(inSocket); transcoder.Outputs.Add(outSocket); if (!transcoder.Open()) { PrintError("Transcoder open", transcoder.Error); return(false); } using (FileStream outputFile = File.OpenWrite(opt.OutputFile)) { MediaSample outputSample = new MediaSample(); int outputIndex = -1; while (transcoder.Pull(out outputIndex, outputSample)) { MediaBuffer buffer = outputSample.Buffer; outputFile.Write(buffer.Start, buffer.DataOffset, buffer.DataSize); } ErrorInfo error = transcoder.Error; PrintError("Transcoder pull", error); if ((error.Code == (int)CodecError.EOS) && (error.Facility == ErrorFacility.Codec)) { // ok success = true; } } transcoder.Close(); } return(success); }
static bool DecodeAvcFile(Options opt) { // transcoder will fail if output exists (by design) DeleteFile(opt.OutputFile); var mediaInfo = new PrimoSoftware.AVBlocks.MediaInfo(); mediaInfo.Inputs[0].File = opt.InputFile; if (!mediaInfo.Open()) { PrintError("MediaInfo.Open()", mediaInfo.Error); return(false); } MediaSocket inSocket = MediaSocket.FromMediaInfo(mediaInfo); MediaSocket outSocket = CreateOutputSocket(opt); // create Transcoder using (Transcoder transcoder = new Transcoder()) { transcoder.AllowDemoMode = true; transcoder.Inputs.Add(inSocket); transcoder.Outputs.Add(outSocket); bool res = transcoder.Open(); PrintError("Transcoder open", transcoder.Error); if (!res) { return(false); } res = transcoder.Run(); PrintError("Transcoder run", transcoder.Error); if (!res) { return(false); } transcoder.Close(); PrintError("Transcoder close", transcoder.Error); if (!res) { return(false); } } return(true); }
static int Main(string[] args) { var opt = new Options(); if (!opt.Prepare(args)) { return((int)ExitCodes.OptionsError); } Library.Initialize(); MediaSocket inSocket = CreateInputSocket(opt); MediaSocket outSocket = CreateOutputSocket(opt); int exitCode = (int)ExitCodes.Success; // Set license information. To run AVBlocks in demo mode, comment the next line out // Library.SetLicense("<license-string>"); using (Transcoder transcoder = new Transcoder()) { transcoder.AllowDemoMode = true; transcoder.Inputs.Add(inSocket); transcoder.Outputs.Add(outSocket); DeleteFile(opt.OutputFile); if (transcoder.Open()) { PrintStatus("Transcoder open", transcoder.Error); if (!EncodeH264Stream(opt, transcoder)) { exitCode = (int)ExitCodes.EncodingError; } transcoder.Close(); PrintStatus("Transcoder close", transcoder.Error); } else { PrintStatus("Transcoder open", transcoder.Error); exitCode = (int)ExitCodes.EncodingError; } } Library.Shutdown(); return(exitCode); }
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); }
static bool ApplyOverlay(Options opt) { DeleteFile(opt.OutputFile); // create Transcoder using (Transcoder transcoder = new Transcoder()) { transcoder.AllowDemoMode = true; MediaSocket inputSocket = new MediaSocket(); inputSocket.File = opt.InputFile; transcoder.Inputs.Add(inputSocket); MediaSocket outputSocket = ConfigureOutputSocket(opt); transcoder.Outputs.Add(outputSocket); bool res = transcoder.Open(); if (!res) { PrintError("Transcoder open", transcoder.Error); return(false); } res = transcoder.Run(); if (!res) { PrintError("Transcoder run", transcoder.Error); return(false); } transcoder.Close(); } Console.WriteLine("Output: " + opt.OutputFile); return(true); }
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); }
static bool Encode(Options opt) { try { File.Delete(opt.OutputFile); } catch { } System.IO.Stream inputStream = null; System.IO.Stream outputStream = null; try { inputStream = new System.IO.FileStream(opt.YuvFile, FileMode.Open, FileAccess.Read, FileShare.Read); outputStream = new System.IO.FileStream(opt.OutputFile, FileMode.Create, FileAccess.Write, FileShare.None); 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; // Configure input var instream = new VideoStreamInfo { FrameRate = opt.YuvFps, // the input frame rate determines how fast the video is played FrameWidth = opt.YuvWidth, FrameHeight = opt.YuvHeight, ColorFormat = opt.YuvColor.Id, StreamType = PrimoSoftware.AVBlocks.StreamType.UncompressedVideo, ScanType = ScanType.Progressive }; var inpin = new MediaPin { StreamInfo = instream }; var insocket = new MediaSocket { Stream = inputStream, StreamType = PrimoSoftware.AVBlocks.StreamType.UncompressedVideo }; insocket.Pins.Add(inpin); transcoder.Inputs.Add(insocket); // Configure output var outsocket = MediaSocket.FromPreset(opt.OutputPreset.Name); outsocket.Stream = outputStream; transcoder.Outputs.Add(outsocket); bool res = transcoder.Open(); PrintError("Open Transcoder", transcoder.Error); if (!res) { return(false); } res = transcoder.Run(); PrintError("Run Transcoder", transcoder.Error); if (!res) { return(false); } transcoder.Close(); } } finally { if (inputStream != null) { inputStream.Dispose(); inputStream = null; } if (outputStream != null) { outputStream.Dispose(); outputStream = null; } } return(true); }
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); }
/* * 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); }
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); }
static bool MP4Remux(Options opt) { try { File.Delete(opt.OutputFile); } catch (Exception) { } bool audioStreamDetected = false; bool videoStreamDetected = false; using (var transcoder = new Transcoder()) { // Transcoder demo mode must be enabled, // in order to use the production release for testing (without a valid license). transcoder.AllowDemoMode = true; // configure inputs using (MediaInfo info = new MediaInfo()) { info.Inputs[0].File = opt.InputFile; if (!info.Open()) { PrintError("mediaInfo.Open", info.Error); return(false); } MediaSocket inputSocket = MediaSocket.FromMediaInfo(info); info.Close(); for (int i = 0; i < inputSocket.Pins.Count; i++) { MediaPin pin = inputSocket.Pins[i]; if (pin.StreamInfo.StreamType == StreamType.H264) { if (videoStreamDetected) { pin.Connection = PinConnection.Disabled; } else { videoStreamDetected = true; Console.WriteLine("Muxing video input: {0}", opt.InputFile); } } else if (pin.StreamInfo.StreamType == StreamType.Aac) { if (audioStreamDetected) { pin.Connection = PinConnection.Disabled; } else { audioStreamDetected = true; Console.WriteLine("Muxing audio input: {0}", opt.InputFile); } } else { pin.Connection = PinConnection.Disabled; } } transcoder.Inputs.Add(inputSocket); } // Configure output { MediaSocket socket = new MediaSocket(); socket.File = opt.OutputFile; socket.StreamType = StreamType.Mp4; if (videoStreamDetected) { VideoStreamInfo streamInfo = new VideoStreamInfo(); streamInfo.StreamType = StreamType.H264; streamInfo.StreamSubType = StreamSubType.Avc1; MediaPin pin = new MediaPin(); pin.StreamInfo = streamInfo; socket.Pins.Add(pin); } if (audioStreamDetected) { AudioStreamInfo streamInfo = new AudioStreamInfo(); streamInfo.StreamType = StreamType.Aac; streamInfo.StreamSubType = StreamSubType.AacMp4; MediaPin pin = new MediaPin(); pin.StreamInfo = streamInfo; socket.Pins.Add(pin); } if (opt.FastStart) { socket.Params.Add(Param.Muxer.MP4.FastStart, 1); } transcoder.Outputs.Add(socket); } bool res = transcoder.Open(); PrintError("Open Transcoder", transcoder.Error); if (!res) { return(false); } res = transcoder.Run(); PrintError("Run Transcoder", transcoder.Error); if (!res) { return(false); } transcoder.Close(); } return(true); }
public bool TranscodeSplit(Options opt, string outFile, string preset, double startTime, out double processedTime, out Int64 processedSize, out bool isSplit) { DeleteFile(outFile); processedSize = 0; processedTime = 0; isSplit = false; using (var transcoder = new Transcoder() { AllowDemoMode = true }) { // Input var inSocket = new MediaSocket(); inSocket.File = opt.InputFile; inSocket.TimePosition = startTime; transcoder.Inputs.Add(inSocket); using (var outputStream = new OutputStream(outFile)) { // Output MediaSocket outSocket = MediaSocket.FromPreset(preset); outSocket.Stream = outputStream; transcoder.Outputs.Add(outSocket); outputStream_ = outputStream; transcoder.OnContinue += Transcoder_OnContinue; transcoder.OnProgress += Transcoder_OnProgress; ReportProgress = false; if (opt.SplitTime > 0) { SplitTime = opt.SplitTime; } if (opt.SplitSize > 0) { SplitSize = opt.SplitSize; } if (!transcoder.Open()) { PrintError("Transcoder open", transcoder.Error); return(false); } if (!transcoder.Run()) { PrintError("Transcoder run", transcoder.Error); return(false); } transcoder.Close(); isSplit = isSplit_; processedSize = outputStream.Length; processedTime = processedTime_; } } return(true); }
public void Close() { t.Close(); t.Inputs.Clear(); t.Outputs.Clear(); }
static bool MP4Mux(Options opt) { try { File.Delete(opt.OutputFile); } catch (Exception) { } using (var transcoder = new Transcoder()) { // Transcoder demo mode must be enabled, // in order to use the production release for testing (without a valid license) transcoder.AllowDemoMode = true; MediaSocket outputSocket = new MediaSocket(); outputSocket.File = opt.OutputFile; outputSocket.StreamType = StreamType.Mp4; // audio for (int i = 0; i < (int)opt.AudioFiles.Length; i++) { MediaPin outputPin = new MediaPin(); AudioStreamInfo asi = new AudioStreamInfo(); asi.StreamType = StreamType.Aac; outputPin.StreamInfo = asi; outputSocket.Pins.Add(outputPin); MediaSocket inputSocket = new MediaSocket(); inputSocket.File = opt.AudioFiles[i]; inputSocket.StreamType = StreamType.Mp4; transcoder.Inputs.Add(inputSocket); Console.WriteLine("Muxing audio input: {0}", opt.AudioFiles[i]); } // video for (int i = 0; i < (int)opt.VideoFiles.Length; i++) { MediaPin outputPin = new MediaPin(); VideoStreamInfo vsi = new VideoStreamInfo(); vsi.StreamType = StreamType.H264; outputPin.StreamInfo = vsi; outputSocket.Pins.Add(outputPin); MediaSocket inputSocket = new MediaSocket(); inputSocket.File = opt.VideoFiles[i]; inputSocket.StreamType = StreamType.Mp4; transcoder.Inputs.Add(inputSocket); Console.WriteLine("Muxing video input: {0}", opt.VideoFiles[i]); } transcoder.Outputs.Add(outputSocket); if (!transcoder.Open()) { PrintError("Open Transcoder", transcoder.Error); return(false); } if (!transcoder.Run()) { PrintError("Run Transcoder", transcoder.Error); return(false); } transcoder.Close(); Console.WriteLine("Output file: {0}", opt.OutputFile); return(true); } }
static bool DecodeH264Stream(Options opt) { // Create an input socket from file MediaSocket inSocket = new MediaSocket(); inSocket.File = opt.InputFile; // Create an output socket with one YUV 4:2:0 video pin VideoStreamInfo outStreamInfo = new VideoStreamInfo(); outStreamInfo.StreamType = StreamType.UncompressedVideo; outStreamInfo.ColorFormat = ColorFormat.YUV420; outStreamInfo.ScanType = ScanType.Progressive; MediaPin outPin = new MediaPin(); outPin.StreamInfo = outStreamInfo; MediaSocket outSocket = new MediaSocket(); outSocket.StreamType = StreamType.UncompressedVideo; outSocket.Pins.Add(outPin); // Create Transcoder using (var transcoder = new Transcoder()) { transcoder.AllowDemoMode = true; transcoder.Inputs.Add(inSocket); transcoder.Outputs.Add(outSocket); if (transcoder.Open()) { DeleteFile(opt.OutputFile); int inputIndex; MediaSample yuvFrame = new MediaSample(); int frameCounter = 0; using (System.IO.FileStream outfile = System.IO.File.OpenWrite(opt.OutputFile)) { while (transcoder.Pull(out inputIndex, yuvFrame)) { // Each call to Transcoder::pull returns a raw YUV 4:2:0 frame. outfile.Write(yuvFrame.Buffer.Start, yuvFrame.Buffer.DataOffset, yuvFrame.Buffer.DataSize); ++frameCounter; } PrintError("Transcoder pull", transcoder.Error); Console.WriteLine("Frames decoded: {0}", frameCounter); Console.WriteLine("Output file: {0}", opt.OutputFile); outfile.Close(); } transcoder.Close(); return(true); } PrintError("Transcoder open", transcoder.Error); return(false); } }
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(); } }
static bool ReEncode(Options opt) { if (File.Exists(opt.OutputFile)) { File.Delete(opt.OutputFile); } using (var transcoder = new Transcoder()) { // In order to use the production release for testing (without a valid license), // the transcoder demo mode must be enabled. transcoder.AllowDemoMode = true; using (var mediaInfo = new MediaInfo()) { mediaInfo.Inputs[0].File = opt.InputFile; if (!mediaInfo.Open()) { PrintError("Open MediaInfo", mediaInfo.Error); return(false); } // Add Inputs { var socket = MediaSocket.FromMediaInfo(mediaInfo); transcoder.Inputs.Add(socket); } } // Add Outputs { // Create output socket var socket = new MediaSocket(); var inSocket = transcoder.Inputs[0]; socket.StreamType = inSocket.StreamType; socket.File = opt.OutputFile; // Add pins with ReEncode parameter set to Use.On foreach (var inPin in inSocket.Pins) { StreamInfo si = (StreamInfo)inPin.StreamInfo.Clone(); var pin = new MediaPin(); pin.StreamInfo = (StreamInfo)si.Clone(); if ((MediaType.Video == si.MediaType) && opt.ReEncodeVideo) { pin.Params.Add(Param.ReEncode, Use.On); } if ((MediaType.Audio == si.MediaType) && opt.ReEncodeAudio) { pin.Params.Add(Param.ReEncode, Use.On); } socket.Pins.Add(pin); } transcoder.Outputs.Add(socket); } bool result = transcoder.Open(); PrintError("Open Transcoder", transcoder.Error); if (!result) { return(false); } result = transcoder.Run(); PrintError("Run Transcoder", transcoder.Error); if (!result) { return(false); } transcoder.Close(); } return(true); }
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); }