Skip to content

Instantly share code, notes, and snippets.

@conholdate-docs-gists
Created October 14, 2022 06:46
Show Gist options
  • Save conholdate-docs-gists/69233f5726123f96641082806be8565a to your computer and use it in GitHub Desktop.
Save conholdate-docs-gists/69233f5726123f96641082806be8565a to your computer and use it in GitHub Desktop.
// Load the source AVI file
VideoLoadOptions loadOptions = new VideoLoadOptions();
loadOptions.SetVideoConnector(new VideoConnector());
using (Converter converter = new Converter("sample.avi", () => loadOptions))
{
// Set the convert options for MP4 format
VideoConvertOptions options = new VideoConvertOptions {
Format = VideoFileType.Mp4
};
// Convert to MP4 format
converter.Convert("converted.mp4", options);
}
public class VideoConnector : IVideoConnector
{
private readonly Dictionary<VideoFileType, Action<FFMpegArgumentOptions>> _optionsMap = new();
public VideoConnector()
{
_optionsMap.Add(VideoFileType.Avi, SetAviConvertOptions);
_optionsMap.Add(VideoFileType.Flv, SetFlvConvertOptions);
_optionsMap.Add(VideoFileType.Mkv, SetMkvConvertOptions);
_optionsMap.Add(VideoFileType.Mp4, SetMp4ConvertOptions);
_optionsMap.Add(VideoFileType.Wmv, SetWmvConvertOptions);
_optionsMap.Add(VideoFileType.Mov, SetMovConvertOptions);
_optionsMap.Add(VideoFileType.Webm, SetWebmConvertOptions);
}
public Stream ConvertVideo(Stream sourceStream, VideoConvertOptions convertOptions)
{
var resultStream = new MemoryStream();
var arguments = FFMpegArguments
.FromPipeInput(new StreamPipeSource(sourceStream))
.OutputToPipe(new StreamPipeSink(resultStream), options =>
{
if (_optionsMap.ContainsKey(convertOptions.Format))
{
_optionsMap[convertOptions.Format].Invoke(options);
}
else
{
throw new InvalidOperationException(
$"Conversion to {convertOptions.Format.Extension} is not supported at the moment");
}
});
arguments.ProcessSynchronously();
return resultStream;
}
private void SetAviConvertOptions(FFMpegArgumentOptions options)
{
options.ForceFormat("avi");
}
private void SetFlvConvertOptions(FFMpegArgumentOptions options)
{
options.ForceFormat("flv");
}
private void SetMkvConvertOptions(FFMpegArgumentOptions options)
{
options.ForceFormat("matroska");
}
private void SetMp4ConvertOptions(FFMpegArgumentOptions options)
{
options.ForceFormat("mp4");
options.WithCustomArgument("-movflags empty_moov");
}
private void SetWmvConvertOptions(FFMpegArgumentOptions options)
{
options.ForceFormat("asf");
}
private void SetMovConvertOptions(FFMpegArgumentOptions options)
{
options.ForceFormat("mov");
options.WithCustomArgument("-movflags empty_moov");
}
private void SetWebmConvertOptions(FFMpegArgumentOptions options)
{
options.ForceFormat("webm");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment