public async Task StartAsync(VideoConverterArgs Args, IProgress <int> Progress) { if (!FFmpegService.FFmpegExists) { throw new FFmpegNotFoundException(); } var argsBuilder = new FFmpegArgsBuilder(); argsBuilder.AddInputFile(Args.InputFile); const string filter = "\"[0:v] split [a][b];[a] palettegen [p];[b][p] paletteuse\""; argsBuilder.AddOutputFile(Args.FileName) .AddArg("filter_complex", filter) .SetFrameRate(Args.FrameRate); var process = FFmpegService.StartFFmpeg(argsBuilder.GetArgs(), Args.FileName, out var log); log.ProgressChanged += Progress.Report; await Task.Run(() => process.WaitForExit()); if (process.ExitCode != 0) { throw new FFmpegException(process.ExitCode); } Progress.Report(100); }
public void ShowFFmpegUnavailable() { Application.Current.Dispatcher.Invoke(() => { var dialog = new ModernDialog { Title = "FFmpeg Unavailable", Content = "FFmpeg was not found on your system.\n\nSelect FFmpeg Folder if you alrady have FFmpeg on your system, else Download FFmpeg." }; // Yes -> Select FFmpeg Folder dialog.YesButton.Content = LanguageManager.Instance.SelectFFmpegFolder; dialog.YesButton.Click += (S, E) => FFmpegService.SelectFFmpegFolder(); // No -> Download FFmpeg dialog.NoButton.Content = "Download FFmpeg"; dialog.NoButton.Click += (S, E) => FFmpegService.FFmpegDownloader?.Invoke(); dialog.CancelButton.Content = "Cancel"; dialog.Buttons = new[] { dialog.YesButton, dialog.NoButton, dialog.CancelButton }; _audioPlayer.Play(SoundKind.Error); dialog.ShowDialog(); }); }
public void ShowFFmpegUnavailable() { Application.Current.Dispatcher.Invoke(() => { var dialog = new ModernDialog { Title = "FFmpeg를 이용할 수 없음", Content = "FFmpeg를 찾을 수 없습니다.\n\nFFmpeg가 있는 폴더를 지정하거나, FFmpeg를 다운로드 받아주세요." }; // Yes -> Select FFmpeg Folder dialog.YesButton.Content = LanguageManager.Instance.SelectFFmpegFolder; dialog.YesButton.Click += (S, E) => FFmpegService.SelectFFmpegFolder(); // No -> Download FFmpeg dialog.NoButton.Content = "FFmpeg 다운로드"; dialog.NoButton.Click += (S, E) => FFmpegService.FFmpegDownloader?.Invoke(); dialog.CancelButton.Content = "취소"; dialog.Buttons = new[] { dialog.YesButton, dialog.NoButton, dialog.CancelButton }; _audioPlayer.Play(SoundKind.Error); dialog.ShowDialog(); }); }
public async Task StartAsync(VideoConverterArgs Args, IProgress <int> Progress) { if (!FFmpegService.FFmpegExists) { throw new FFmpegNotFoundException(); } var argsBuilder = new FFmpegArgsBuilder(); argsBuilder.AddInputFile(Args.InputFile); var output = argsBuilder.AddOutputFile(Args.FileName) .SetFrameRate(Args.FrameRate); _videoCodec.Apply(ServiceProvider.Get <FFmpegSettings>(), Args, output); //if (Args.AudioProvider != null) { _videoCodec.AudioArgsProvider(Args.AudioQuality, output); } var process = FFmpegService.StartFFmpeg(argsBuilder.GetArgs(), Args.FileName, out var log); log.ProgressChanged += Progress.Report; await Task.Run(() => process.WaitForExit()); if (process.ExitCode != 0) { throw new FFmpegException(process.ExitCode); } Progress.Report(100); }
private bool CheckForAudio(string path) { FFmpegService ffmpeg = new FFmpegService(); var qa = ffmpeg.QueryAudio(path); return(qa.IsAudio); }
/// <inheritdoc /> public void Dispose() { _ffMpegWriter.Dispose(); var argsBuilder = new FFmpegArgsBuilder(); argsBuilder.AddInputFile(_tempFileName); var output = argsBuilder.AddOutputFile(_args.FileName) .AddArg(_args.VideoArgsProvider(_args.VideoQuality)) .SetFrameRate(_args.FrameRate); if (_args.AudioProvider != null) { output.AddArg(_args.AudioArgsProvider(_args.AudioQuality)); } output.AddArg(_args.OutputArgs); var process = FFmpegService.StartFFmpeg(argsBuilder.GetArgs(), _args.FileName); process.WaitForExit(); File.Delete(_tempFileName); }
/// <summary> /// 开始执行工作流时触发 /// </summary> /// <param name="obj">对象</param> private void BeginRun(RunManager obj) { //流程运行开始…… SharedObject.Instance.Output(SharedObject.enOutputType.Trace, ResxIF.GetString("TheProcessStarted")); //不应该更新状态为START,不然和用户自己设置的标识冲突了 //Task.Run(async()=> { // await ControlServerService.UpdateRunStatus(obj.m_packageItem.Name, obj.m_packageItem.Version, ControlServerService.enProcessStatus.Start); //}); if (FFmpegService != null) { FFmpegService.StopCaptureScreen(); FFmpegService = null; } if (ViewModelLocator.Instance.UserPreferences.IsEnableScreenRecorder) { //屏幕录像开始…… SharedObject.Instance.Output(SharedObject.enOutputType.Trace, ResxIF.GetString("ScreenRecordingStarted")); var screenRecorderFilePath = App.LocalRPAStudioDir + @"\ScreenRecorder\" + obj.m_packageItem.Name + @"(" + DateTime.Now.ToString(ResxIF.GetString("YYYYMMDD")) + ").mp4"; FFmpegService = new FFmpegService(screenRecorderFilePath, ViewModelLocator.Instance.UserPreferences.FPS, ViewModelLocator.Instance.UserPreferences.Quality);//默认存到%localappdata%下RPASTUDIO下的ScreenRecorder目录下 Task.Run(() => { FFmpegService.StartCaptureScreen(); }); //等待屏幕录像ffmpeg进程启动 int wait_count = 0; while (!FFmpegService.IsRunning()) { wait_count++; Thread.Sleep(300); if (wait_count == 10) { break; } } } Common.RunInUI(() => { m_view.Hide(); obj.m_packageItem.IsRunning = true; IsWorkflowRunning = true; WorkflowRunningName = obj.m_packageItem.Name; WorkflowRunningToolTip = obj.m_packageItem.ToolTip; WorkflowRunningStatus = ResxIF.GetString("RunningText"); //正在运行 }); }
public static void Extract(Disc disc, string path, string fileBase) { var dsr = new DiscSectorReader(disc); bool confirmed = false; var tracks = disc.Session1.Tracks; foreach (var track in tracks) { if (!track.IsAudio) { continue; } int trackLength = track.NextTrack.LBA - track.LBA; var waveData = new byte[trackLength * 2352]; int startLba = track.LBA; for (int sector = 0; sector < trackLength; sector++) { dsr.ReadLBA_2352(startLba + sector, waveData, sector * 2352); } string mp3Path = $"{Path.Combine(path, fileBase)} - Track {track.Number:D2}.mp3"; if (File.Exists(mp3Path)) { if (!confirmed) { var dr = MessageBox.Show("This file already exists. Do you want extraction to proceed overwriting files, or cancel the entire operation immediately?", "File already exists", MessageBoxButtons.OKCancel); if (dr == DialogResult.Cancel) { return; } confirmed = true; } File.Delete(mp3Path); } string tempfile = Path.GetTempFileName(); try { File.WriteAllBytes(tempfile, waveData); var ffmpeg = new FFmpegService(); ffmpeg.Run("-f", "s16le", "-ar", "44100", "-ac", "2", "-i", tempfile, "-f", "mp3", "-ab", "192k", mp3Path); } finally { File.Delete(tempfile); } } }
/// <summary> /// Creates a new instance of <see cref="FFmpegWriter"/>. /// </summary> public FFmpegWriter(FFmpegVideoWriterArgs Args) { var settings = ServiceProvider.Get <FFmpegSettings>(); _videoBuffer = new byte[Args.ImageProvider.Width * Args.ImageProvider.Height * 4]; frameCount = 0; _keyVector = Args.keyVector; _keyVector.CreateKeyOutputFile(); Console.WriteLine($"Video Buffer Allocated: {_videoBuffer.Length}"); var audioPipeName = GetPipeName(); var videoPipeName = GetPipeName(); var videoInArgs = $"-thread_queue_size 512 -use_wallclock_as_timestamps 1 -f rawvideo -pix_fmt rgb32 -video_size {Args.ImageProvider.Width}x{Args.ImageProvider.Height} -i {PipePrefix}{videoPipeName}"; var videoOutArgs = $"{Args.VideoArgsProvider(Args.VideoQuality)} -r {Args.FrameRate}"; if (settings.Resize) { var width = settings.ResizeWidth; var height = settings.ResizeHeight; if (width % 2 == 1) { ++width; } if (height % 2 == 1) { ++height; } videoOutArgs += $" -vf scale={width}:{height}"; } string audioInArgs = "", audioOutArgs = ""; if (Args.AudioProvider != null) { audioInArgs = $"-thread_queue_size 512 -f s16le -acodec pcm_s16le -ar {Args.Frequency} -ac {Args.Channels} -i {PipePrefix}{audioPipeName}"; audioOutArgs = Args.AudioArgsProvider(Args.AudioQuality); // UpdatePeriod * Frequency * (Bytes per Second) * Channels * 2 var audioBufferSize = (int)((1000.0 / Args.FrameRate) * 44.1 * 2 * 2 * 2); _audioPipe = new NamedPipeServerStream(audioPipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 0, audioBufferSize); } _ffmpegIn = new NamedPipeServerStream(videoPipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 0, _videoBuffer.Length); _ffmpegProcess = FFmpegService.StartFFmpeg($"{videoInArgs} {audioInArgs} {videoOutArgs} {audioOutArgs} {Args.OutputArgs} \"{Args.FileName}\"", Args.FileName); }
private void FinalAnalysis() { //some quick checks: if (OUT_CompiledCueFiles.Count == 0) { Error("Cue file doesn't specify any input files!"); } //we can't reliably analyze the length of files here, because we might have to be decoding to get lengths (VBR mp3s) //REMINDER: we could actually scan the mp3 frames in software //So, it's not really worth the trouble. We'll cope with lengths later //we could check the format of the wav file here, though //score the cost of loading the file bool needsCodec = false; OUT_LoadTime = 0; foreach (var cfi in OUT_CompiledCueFiles) { if (cfi == null) { continue; } if (cfi.Type == CompiledCueFileType.DecodeAudio) { needsCodec = true; OUT_LoadTime = Math.Max(OUT_LoadTime, 10); } if (cfi.Type == CompiledCueFileType.SeekAudio) { needsCodec = true; } if (cfi.Type == CompiledCueFileType.ECM) { OUT_LoadTime = Math.Max(OUT_LoadTime, 1); } } //check whether processing was available if (needsCodec) { FFmpegService ffmpeg = new FFmpegService(); if (!ffmpeg.QueryServiceAvailable()) { Warn("Decoding service will be required for further processing, but is not available"); } } }
void GenerateGif(string PaletteFile) { var argsBuilder = new FFmpegArgsBuilder(); argsBuilder.AddInputFile(_tempFileName); argsBuilder.AddInputFile(PaletteFile); argsBuilder.AddOutputFile(_args.FileName) .AddArg("lavfi", "paletteuse") .SetFrameRate(_args.FrameRate); var process = FFmpegService.StartFFmpeg(argsBuilder.GetArgs(), _args.FileName); process.WaitForExit(); }
private void BeginRun(RunManager obj) { SharedObject.Instance.Output(SharedObject.enOutputType.Trace, "流程运行开始……", null); if (this.FFmpegService != null) { this.FFmpegService.StopCaptureScreen(); this.FFmpegService = null; } if (ViewModelLocator.Instance.UserPreferences.IsEnableScreenRecorder) { SharedObject.Instance.Output(SharedObject.enOutputType.Trace, "屏幕录像开始……", null); var screenCaptureSavePath = Path.Combine( App.LocalRPAStudioDir, "ScreenRecorder", obj.m_packageItem.Name, "(", DateTime.Now.ToString("yyyy年MM月dd日HH时mm分ss秒"), ").mp4" ); FFmpegService = new FFmpegService(screenCaptureSavePath, ViewModelLocator.Instance.UserPreferences.FPS, ViewModelLocator.Instance.UserPreferences.Quality); Task.Run(FFmpegService.StartCaptureScreen); // 三秒 int num = 0; while (!FFmpegService.IsRunning()) { num++; Thread.Sleep(300); if (num == 10) { break; } } } Common.RunInUI(() => { ViewModelLocator.Instance.Main.m_view.Hide(); obj.m_packageItem.IsRunning = true; IsWorkflowRunning = true; WorkflowRunningName = obj.m_packageItem.Name; WorkflowRunningToolTip = obj.m_packageItem.ToolTip; WorkflowRunningStatus = "正在运行"; }); }
public FFmpegAudioWriter(string FileName, int AudioQuality, FFmpegAudioArgsProvider AudioArgsProvider, int Frequency = 44100, int Channels = 2) { var argsBuilder = new FFmpegArgsBuilder(); argsBuilder.AddStdIn() .SetFormat("s16le") .SetAudioCodec("pcm_s16le") .SetAudioFrequency(Frequency) .SetAudioChannels(Channels) .DisableVideo(); argsBuilder.AddOutputFile(FileName) .AddArg(AudioArgsProvider(AudioQuality)); _ffmpegProcess = FFmpegService.StartFFmpeg(argsBuilder.GetArgs(), FileName); _ffmpegIn = _ffmpegProcess.StandardInput.BaseStream; }
/// <summary> /// Creates a new instance of <see cref="FFmpegWriter"/>. /// </summary> public FFmpegWriter(FFmpegVideoWriterArgs Args) { var settings = ServiceProvider.Get <Settings>(); _videoBuffer = new byte[Args.ImageProvider.Width * Args.ImageProvider.Height * 4]; var audioPipeName = GetPipeName(); var videoPipeName = GetPipeName(); var videoInArgs = $"-framerate {Args.FrameRate} -f rawvideo -pix_fmt rgb32 -video_size {Args.ImageProvider.Width}x{Args.ImageProvider.Height} -i {PipePrefix}{videoPipeName}"; var videoOutArgs = $"{Args.VideoArgsProvider(Args.VideoQuality)} -r {Args.FrameRate}"; if (settings.FFmpeg.Resize) { var width = settings.FFmpeg.ResizeWidth; var height = settings.FFmpeg.ResizeHeight; if (width % 2 == 1) { ++width; } if (height % 2 == 1) { ++height; } videoOutArgs += $" -vf scale={width}:{height}"; } string audioInArgs = "", audioOutArgs = ""; if (Args.AudioProvider != null) { audioInArgs = $"-f s16le -acodec pcm_s16le -ar {Args.Frequency} -ac {Args.Channels} -i {PipePrefix}{audioPipeName}"; audioOutArgs = Args.AudioArgsProvider(Args.AudioQuality); _audioPipe = new NamedPipeServerStream(audioPipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 10000, 10000); } _ffmpegIn = new NamedPipeServerStream(videoPipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 10000, 10000); _ffmpegProcess = FFmpegService.StartFFmpeg($"{videoInArgs} {audioInArgs} {videoOutArgs} {audioOutArgs} {Args.OutputArgs} \"{Args.FileName}\"", Args.FileName); }
/// <inheritdoc /> public void Dispose() { _ffMpegWriter.Dispose(); var videoInArgs = $"-i \"{_tempFileName}\""; var videoOutArgs = $"{_args.VideoArgsProvider(_args.VideoQuality)} -r {_args.FrameRate}"; var audioOutArgs = ""; if (_args.AudioProvider != null) { audioOutArgs = _args.AudioArgsProvider(_args.AudioQuality); } var process = FFmpegService.StartFFmpeg($"{videoInArgs} {videoOutArgs} {audioOutArgs} {_args.OutputArgs} \"{_args.FileName}\"", _args.FileName); process.WaitForExit(); File.Delete(_tempFileName); }
string GeneratePalette() { var argsBuilder = new FFmpegArgsBuilder(); argsBuilder.AddInputFile(_tempFileName); var tempFile = Path.GetTempFileName(); var paletteFile = Path.ChangeExtension(tempFile, "png"); File.Move(tempFile, paletteFile); argsBuilder.AddOutputFile(paletteFile) .AddArg("-vf palettegen") .SetFrameRate(_args.FrameRate) .AddArg("-y"); var process = FFmpegService.StartFFmpeg(argsBuilder.GetArgs(), paletteFile); process.WaitForExit(); return paletteFile; }
private void EndRun(RunManager obj) { SharedObject.Instance.Output(SharedObject.enOutputType.Trace, ResxIF.GetString("EndProcessRun")); //流程运行结束 Task.Run(async() => { if (obj.HasException) { await ControlServerService.UpdateRunStatus(obj.m_packageItem.Name, obj.m_packageItem.Version, ControlServerService.enProcessStatus.Exception); } else { await ControlServerService.UpdateRunStatus(obj.m_packageItem.Name, obj.m_packageItem.Version, ControlServerService.enProcessStatus.Stop); } }); if (ViewModelLocator.Instance.UserPreferences.IsEnableScreenRecorder) { SharedObject.Instance.Output(SharedObject.enOutputType.Trace, ResxIF.GetString("EndScreenRecording")); //屏幕录像结束 FFmpegService.StopCaptureScreen(); FFmpegService = null; } Common.RunInUI(() => { m_view.Show(); m_view.Activate(); obj.m_packageItem.IsRunning = false; //由于有可能列表已经刷新,所以需要重置IsRunning状态,为了方便,全部重置 foreach (var pkg in PackageItems) { pkg.IsRunning = false; } IsWorkflowRunning = false; WorkflowRunningName = ""; WorkflowRunningStatus = ""; }); }
/// <inheritdoc /> public void Dispose() { _ffMpegWriter.Dispose(); var argsBuilder = new FFmpegArgsBuilder(); argsBuilder.AddInputFile(_tempFileName); var output = argsBuilder.AddOutputFile(_args.FileName) .SetFrameRate(_args.FrameRate); _args.VideoCodec.Apply(ServiceProvider.Get <FFmpegSettings>(), _args, output); if (_args.AudioProvider != null) { _args.VideoCodec.AudioArgsProvider(_args.AudioQuality, output); } var process = FFmpegService.StartFFmpeg(argsBuilder.GetArgs(), _args.FileName, out _); process.WaitForExit(); File.Delete(_tempFileName); }
public FFmpegAudioWriter(string FileName, int AudioQuality, FFmpegAudioArgsProvider AudioArgsProvider, int Frequency = 44100, int Channels = 2) { if (!FFmpegService.FFmpegExists) { throw new FFmpegNotFoundException(); } var argsBuilder = new FFmpegArgsBuilder(); argsBuilder.AddStdIn() .SetFormat("s16le") .SetAudioCodec("pcm_s16le") .SetAudioFrequency(Frequency) .SetAudioChannels(Channels) .DisableVideo(); var output = argsBuilder.AddOutputFile(FileName); AudioArgsProvider(AudioQuality, output); _ffmpegProcess = FFmpegService.StartFFmpeg(argsBuilder.GetArgs(), FileName, out _); _ffmpegIn = _ffmpegProcess.StandardInput.BaseStream; }
public static void Extract(Disc disc, string path, string fileBase, Func <bool?> getOverwritePolicy) { var dsr = new DiscSectorReader(disc); var shouldHalt = false; bool?overwriteExisting = null; // true = overwrite, false = skip existing, null = unset var tracks = disc.Session1.Tracks; Parallel.ForEach(tracks, track => { if (shouldHalt) { return; } if (!track.IsAudio) { return; } if (track.NextTrack == null) { return; } int trackLength = track.NextTrack.LBA - track.LBA; var waveData = new byte[trackLength * 2352]; int startLba = track.LBA; lock (disc) for (int sector = 0; sector < trackLength; sector++) { dsr.ReadLBA_2352(startLba + sector, waveData, sector * 2352); } string mp3Path = $"{Path.Combine(path, fileBase)} - Track {track.Number:D2}.mp3"; if (File.Exists(mp3Path)) { overwriteExisting ??= getOverwritePolicy(); switch (overwriteExisting) { case true: // "Yes" -- overwrite File.Delete(mp3Path); break; case false: // "No" -- skip return; case null: // "Cancel" -- halt shouldHalt = true; return; } } string tempfile = Path.GetTempFileName(); try { File.WriteAllBytes(tempfile, waveData); FFmpegService.Run("-f", "s16le", "-ar", "44100", "-ac", "2", "-i", tempfile, "-f", "mp3", "-ab", "192k", mp3Path); } finally { File.Delete(tempfile); } }); }
private void Download() { //the temp file is owned by this thread var fn = TempFileManager.GetTempFilename("ffmpeg_download", ".7z", false); try { using (var evt = new ManualResetEvent(false)) { using (var client = new System.Net.WebClient()) { System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12; client.DownloadFileAsync(new Uri(FFmpegService.Url), fn); client.DownloadProgressChanged += (object sender, System.Net.DownloadProgressChangedEventArgs e) => { pct = e.ProgressPercentage; }; client.DownloadFileCompleted += (object sender, System.ComponentModel.AsyncCompletedEventArgs e) => { //we don't really need a status. we'll just try to unzip it when it's done evt.Set(); }; for (; ;) { if (evt.WaitOne(10)) { break; } //if the gui thread ordered an exit, cancel the download and wait for it to acknowledge if (exiting) { client.CancelAsync(); evt.WaitOne(); break; } } } } //throw new Exception("test of download failure"); //if we were ordered to exit, bail without wasting any more time if (exiting) { return; } //try acquiring file using (var hf = new HawkFile(fn)) { using (var exe = hf.BindFirstOf(".exe")) { var data = exe.ReadAllBytes(); //last chance. exiting, don't dump the new ffmpeg file if (exiting) { return; } File.WriteAllBytes(FFmpegService.FFmpegPath, data); } } //make sure it worked if (!FFmpegService.QueryServiceAvailable()) { throw new Exception("download failed"); } succeeded = true; } catch { failed = true; } finally { try { File.Delete(fn); } catch { } } }
private void Download() { //the temp file is owned by this thread var fn = TempFileManager.GetTempFilename("ffmpeg_download", ".7z", false); try { using (var evt = new ManualResetEvent(false)) { using (var client = new System.Net.WebClient()) { System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12; client.DownloadFileAsync(new Uri(FFmpegService.Url), fn); client.DownloadProgressChanged += (object sender, System.Net.DownloadProgressChangedEventArgs e) => { pct = e.ProgressPercentage; }; client.DownloadFileCompleted += (object sender, System.ComponentModel.AsyncCompletedEventArgs e) => { //we don't really need a status. we'll just try to unzip it when it's done evt.Set(); }; for (; ;) { if (evt.WaitOne(10)) { break; } //if the gui thread ordered an exit, cancel the download and wait for it to acknowledge if (exiting) { client.CancelAsync(); evt.WaitOne(); break; } } } } //throw new Exception("test of download failure"); //if we were ordered to exit, bail without wasting any more time if (exiting) { return; } //try acquiring file using (var hf = new HawkFile(fn)) { using (var exe = OSTailoredCode.IsUnixHost ? hf.BindArchiveMember("ffmpeg") : hf.BindFirstOf(".exe")) { var data = exe !.ReadAllBytes(); //last chance. exiting, don't dump the new ffmpeg file if (exiting) { return; } DirectoryInfo parentDir = new(Path.GetDirectoryName(FFmpegService.FFmpegPath) !); if (!parentDir.Exists) { parentDir.Create(); } File.WriteAllBytes(FFmpegService.FFmpegPath, data); if (OSTailoredCode.IsUnixHost) { OSTailoredCode.ConstructSubshell("chmod", $"+x {FFmpegService.FFmpegPath}", checkStdout: false).Start(); Thread.Sleep(50); // Linux I/O flush idk } } } //make sure it worked if (!FFmpegService.QueryServiceAvailable()) { throw new Exception("download failed"); } succeeded = true; } catch { failed = true; } finally { try { File.Delete(fn); } catch { } } }
private bool CheckForAudio(string path) => FFmpegService.QueryAudio(path).IsAudio;
private static void DownloadFile(HttpContext context) { var flushed = false; try { var id = context.Request[FilesLinkUtility.FileId]; var doc = context.Request[FilesLinkUtility.DocShareKey] ?? ""; using (var fileDao = Global.DaoFactory.GetFileDao()) { File file; var readLink = FileShareLink.Check(doc, true, fileDao, out file); if (!readLink && file == null) { fileDao.InvalidateCache(id); int version; file = int.TryParse(context.Request[FilesLinkUtility.Version], out version) && version > 0 ? fileDao.GetFile(id, version) : fileDao.GetFile(id); } if (file == null) { context.Response.StatusCode = (int)HttpStatusCode.NotFound; return; } if (!readLink && !Global.GetFilesSecurity().CanRead(file)) { context.Response.StatusCode = (int)HttpStatusCode.Forbidden; return; } if (!string.IsNullOrEmpty(file.Error)) { throw new Exception(file.Error); } if (!fileDao.IsExistOnStorage(file)) { Global.Logger.ErrorFormat("Download file error. File is not exist on storage. File id: {0}.", file.ID); context.Response.StatusCode = (int)HttpStatusCode.NotFound; return; } FileMarker.RemoveMarkAsNew(file); context.Response.Clear(); context.Response.ClearHeaders(); context.Response.Charset = "utf-8"; FilesMessageService.Send(file, context.Request, MessageAction.FileDownloaded, file.Title); if (string.Equals(context.Request.Headers["If-None-Match"], GetEtag(file))) { //Its cached. Reply 304 context.Response.StatusCode = (int)HttpStatusCode.NotModified; context.Response.Cache.SetETag(GetEtag(file)); } else { context.Response.CacheControl = "public"; context.Response.Cache.SetETag(GetEtag(file)); context.Response.Cache.SetCacheability(HttpCacheability.Public); Stream fileStream = null; try { var title = file.Title; if (file.ContentLength <= SetupInfo.AvailableFileSize) { var ext = FileUtility.GetFileExtension(file.Title); var outType = (context.Request[FilesLinkUtility.OutType] ?? "").Trim(); if (!string.IsNullOrEmpty(outType) && FileUtility.ExtsConvertible.Keys.Contains(ext) && FileUtility.ExtsConvertible[ext].Contains(outType)) { ext = outType; } long offset = 0; long length; if (!file.ProviderEntry && string.Equals(context.Request["convpreview"], "true", StringComparison.InvariantCultureIgnoreCase) && FFmpegService.IsConvertable(ext)) { const string mp4Name = "content.mp4"; var mp4Path = FileDao.GetUniqFilePath(file, mp4Name); var store = Global.GetStore(); if (!store.IsFile(mp4Path)) { fileStream = fileDao.GetFileStream(file); Global.Logger.InfoFormat("Converting {0} (fileId: {1}) to mp4", file.Title, file.ID); var stream = FFmpegService.Convert(fileStream, ext); store.Save(string.Empty, mp4Path, stream, mp4Name); } var fullLength = store.GetFileSize(string.Empty, mp4Path); length = ProcessRangeHeader(context, fullLength, ref offset); fileStream = store.GetReadStream(string.Empty, mp4Path, (int)offset); title = FileUtility.ReplaceFileExtension(title, ".mp4"); } else { if (!FileConverter.EnableConvert(file, ext)) { if (!readLink && fileDao.IsSupportedPreSignedUri(file)) { context.Response.Redirect(fileDao.GetPreSignedUri(file, TimeSpan.FromHours(1)).ToString(), true); return; } fileStream = fileDao.GetFileStream(file); // getStream to fix file.ContentLength if (fileStream.CanSeek) { var fullLength = file.ContentLength; length = ProcessRangeHeader(context, fullLength, ref offset); fileStream.Seek(offset, SeekOrigin.Begin); } else { length = file.ContentLength; } } else { title = FileUtility.ReplaceFileExtension(title, ext); fileStream = FileConverter.Exec(file, ext); length = fileStream.Length; } } SendStreamByChunks(context, length, title, fileStream, ref flushed); } else { if (!readLink && fileDao.IsSupportedPreSignedUri(file)) { context.Response.Redirect(fileDao.GetPreSignedUri(file, TimeSpan.FromHours(1)).ToString(), true); return; } fileStream = fileDao.GetFileStream(file); // getStream to fix file.ContentLength long offset = 0; var length = file.ContentLength; if (fileStream.CanSeek) { length = ProcessRangeHeader(context, file.ContentLength, ref offset); fileStream.Seek(offset, SeekOrigin.Begin); } SendStreamByChunks(context, length, title, fileStream, ref flushed); } } catch (ThreadAbortException tae) { Global.Logger.Error("DownloadFile", tae); } catch (HttpException e) { Global.Logger.Error("DownloadFile", e); throw new HttpException((int)HttpStatusCode.BadRequest, e.Message); } finally { if (fileStream != null) { fileStream.Close(); fileStream.Dispose(); } } try { context.Response.Flush(); context.Response.SuppressContent = true; context.ApplicationInstance.CompleteRequest(); flushed = true; } catch (HttpException ex) { Global.Logger.Error("DownloadFile", ex); } } } } catch (ThreadAbortException tae) { Global.Logger.Error("DownloadFile", tae); } catch (Exception ex) { // Get stack trace for the exception with source file information var st = new StackTrace(ex, true); // Get the top stack frame var frame = st.GetFrame(0); // Get the line number from the stack frame var line = frame.GetFileLineNumber(); Global.Logger.ErrorFormat("Url: {0} {1} IsClientConnected:{2}, line number:{3} frame:{4}", context.Request.Url, ex, context.Response.IsClientConnected, line, frame); if (!flushed && context.Response.IsClientConnected) { context.Response.StatusCode = 400; context.Response.Write(HttpUtility.HtmlEncode(ex.Message)); } } }
/// <summary> /// Creates a new instance of <see cref="FFmpegWriter"/>. /// </summary> public FFmpegWriter(FFmpegVideoWriterArgs Args) { var settings = ServiceProvider.Get <FFmpegSettings>(); _videoBuffer = new byte[Args.ImageProvider.Width * Args.ImageProvider.Height * 4]; Console.WriteLine($"Video Buffer Allocated: {_videoBuffer.Length}"); var videoPipeName = GetPipeName(); var argsBuilder = new FFmpegArgsBuilder(); argsBuilder.AddInputPipe(videoPipeName) .AddArg("-thread_queue_size 512") .AddArg($"-framerate {Args.FrameRate}") .SetFormat("rawvideo") .AddArg("-pix_fmt rgb32") .SetVideoSize(Args.ImageProvider.Width, Args.ImageProvider.Height); var output = argsBuilder.AddOutputFile(Args.FileName) .AddArg(Args.VideoArgsProvider(Args.VideoQuality)) .SetFrameRate(Args.FrameRate); if (settings.Resize) { var width = settings.ResizeWidth; var height = settings.ResizeHeight; if (width % 2 == 1) { ++width; } if (height % 2 == 1) { ++height; } output.AddArg($"-vf scale={width}:{height}"); } if (Args.AudioProvider != null) { var audioPipeName = GetPipeName(); argsBuilder.AddInputPipe(audioPipeName) .AddArg("-thread_queue_size 512") .SetFormat("s16le") .SetAudioCodec("pcm_s16le") .SetAudioFrequency(Args.Frequency) .SetAudioChannels(Args.Channels); output.AddArg(Args.AudioArgsProvider(Args.AudioQuality)); // UpdatePeriod * Frequency * (Bytes per Second) * Channels * 2 var audioBufferSize = (int)((1000.0 / Args.FrameRate) * 44.1 * 2 * 2 * 2); _audioPipe = new NamedPipeServerStream(audioPipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 0, audioBufferSize); } _ffmpegIn = new NamedPipeServerStream(videoPipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 0, _videoBuffer.Length); output.AddArg(Args.OutputArgs); _ffmpegProcess = FFmpegService.StartFFmpeg(argsBuilder.GetArgs(), Args.FileName); }
public FFmpegAudioWriter(string FileName, int AudioQuality, FFmpegAudioArgsProvider AudioArgsProvider, int Frequency = 44100, int Channels = 2) { _ffmpegProcess = FFmpegService.StartFFmpeg($"-f s16le -acodec pcm_s16le -ar {Frequency} -ac {Channels} -i - -vn {AudioArgsProvider(AudioQuality)} \"{FileName}\"", FileName); _ffmpegIn = _ffmpegProcess.StandardInput.BaseStream; }
/// <summary> /// Creates a new instance of <see cref="FFmpegWriter"/>. /// </summary> public FFmpegWriter(FFmpegVideoWriterArgs Args) { var settings = ServiceProvider.Get <FFmpegSettings>(); VideoInputArgs = Args; var crf = (51 * (100 - VideoInputArgs.VideoQuality)) / 99; outputFolderName = Args.FileName.Substring(0, VideoInputArgs.FileName.Length - 4); additionalVideoInputArgsPre = " -r " + Args.FrameRate + " -start_number 1 -i \""; additionalVideoInputArgsPost = "_%d.png\" -s " + Args.ImageProvider.Width + "*" + Args.ImageProvider.Height + " -vcodec libx264 -crf " + crf + " -pix_fmt " + settings.X264.PixelFormat + " -preset " + settings.X264.Preset; if (settings.Resize) { additionalVideoInputArgsPost += " -vf scale=" + settings.ResizeWidth + ":" + settings.ResizeHeight; } if (File.Exists(capturePropertiesPath)) { foreach (string row in File.ReadAllLines(capturePropertiesPath)) { string[] rowValues = row.Split('='); if (!row.StartsWith("#") && rowValues.Length == 2) { if (rowValues[0].Trim() == "PIPE_TIMEOUT_IN_SECONDS") { try { waitTimeForPipeConnection = int.Parse(rowValues[1].Trim()) * 1000; if (waitTimeForPipeConnection != 30000) { WriteLog("Wait Timeout: " + waitTimeForPipeConnection); } } catch (Exception) { } } } } } if (settings.RawBackup) { framesToBeWritten = new Queue <byte[]>(); (new Thread(ThreadForAppendFrames)).Start(); } _videoBuffer = new byte[Args.ImageProvider.Width * Args.ImageProvider.Height * 4]; Console.WriteLine($"Video Buffer Allocated: {_videoBuffer.Length}"); var videoPipeName = GetPipeName(); var argsBuilder = new FFmpegArgsBuilder(); argsBuilder.AddInputPipe(videoPipeName) .AddArg("-thread_queue_size 512") .AddArg($"-framerate {Args.FrameRate}") .SetFormat("rawvideo") .AddArg("-pix_fmt rgb32") .SetVideoSize(Args.ImageProvider.Width, Args.ImageProvider.Height); var output = argsBuilder.AddOutputFile(Args.FileName) .AddArg(Args.VideoArgsProvider(Args.VideoQuality)) .SetFrameRate(Args.FrameRate); if (settings.Resize) { var width = settings.ResizeWidth; var height = settings.ResizeHeight; if (width % 2 == 1) { ++width; } if (height % 2 == 1) { ++height; } output.AddArg($"-vf scale={width}:{height}"); } if (Args.AudioProvider != null) { var audioPipeName = GetPipeName(); argsBuilder.AddInputPipe(audioPipeName) .AddArg("-thread_queue_size 512") .SetFormat("s16le") .SetAudioCodec("pcm_s16le") .SetAudioFrequency(Args.Frequency) .SetAudioChannels(Args.Channels); output.AddArg(Args.AudioArgsProvider(Args.AudioQuality)); // UpdatePeriod * Frequency * (Bytes per Second) * Channels * 2 var audioBufferSize = (int)((1000.0 / Args.FrameRate) * 44.1 * 2 * 2 * 2); _audioPipe = new NamedPipeServerStream(audioPipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 0, audioBufferSize); } _ffmpegIn = new NamedPipeServerStream(videoPipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 0, _videoBuffer.Length); output.AddArg(Args.OutputArgs); _ffmpegProcess = FFmpegService.StartFFmpeg(argsBuilder.GetArgs(), Args.FileName); }
/// <summary> /// Creates a new instance of <see cref="FFmpegWriter"/>. /// </summary> public FFmpegWriter(FFmpegVideoWriterArgs Args) { if (!FFmpegService.FFmpegExists) { throw new FFmpegNotFoundException(); } var nv12 = Args.ImageProvider.DummyFrame is INV12Frame; var settings = ServiceProvider.Get <FFmpegSettings>(); var w = Args.ImageProvider.Width; var h = Args.ImageProvider.Height; _videoBuffer = new byte[(int)(w * h * (nv12 ? 1.5 : 4))]; Console.WriteLine($"Video Buffer Allocated: {_videoBuffer.Length}"); var videoPipeName = GetPipeName(); var argsBuilder = new FFmpegArgsBuilder(); argsBuilder.AddInputPipe(videoPipeName) .AddArg("thread_queue_size", 512) .AddArg("framerate", Args.FrameRate) .SetFormat("rawvideo") .AddArg("pix_fmt", nv12 ? "nv12" : "rgb32") .SetVideoSize(w, h); var output = argsBuilder.AddOutputFile(Args.FileName) .SetFrameRate(Args.FrameRate); Args.VideoCodec.Apply(settings, Args, output); if (settings.Resize) { var width = settings.ResizeWidth; var height = settings.ResizeHeight; if (width % 2 == 1) { ++width; } if (height % 2 == 1) { ++height; } output.AddArg("vf", $"scale={width}:{height}"); } if (Args.AudioProvider != null) { var audioPipeName = GetPipeName(); argsBuilder.AddInputPipe(audioPipeName) .AddArg("thread_queue_size", 512) .SetFormat("s16le") .SetAudioCodec("pcm_s16le") .SetAudioFrequency(Args.Frequency) .SetAudioChannels(Args.Channels); Args.VideoCodec.AudioArgsProvider(Args.AudioQuality, output); // UpdatePeriod * Frequency * (Bytes per Second) * Channels * 2 var audioBufferSize = (int)((1000.0 / Args.FrameRate) * 44.1 * 2 * 2 * 2); _audioPipe = new NamedPipeServerStream(audioPipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 0, audioBufferSize); } _ffmpegIn = new NamedPipeServerStream(videoPipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 0, _videoBuffer.Length); _ffmpegProcess = FFmpegService.StartFFmpeg(argsBuilder.GetArgs(), Args.FileName, out _); }
private void MountBlobs() { IBlob file_blob = null; BlobInfos = new List <BlobInfo>(); foreach (var ccf in IN_CompileJob.OUT_CompiledCueFiles) { var bi = new BlobInfo(); BlobInfos.Add(bi); switch (ccf.Type) { case CompiledCueFileType.BIN: case CompiledCueFileType.Unknown: { //raw files: var blob = new Disc.Blob_RawFile { PhysicalPath = ccf.FullPath }; OUT_Disc.DisposableResources.Add(file_blob = blob); bi.Length = blob.Length; break; } case CompiledCueFileType.ECM: { var blob = new Disc.Blob_ECM(); OUT_Disc.DisposableResources.Add(file_blob = blob); blob.Load(ccf.FullPath); bi.Length = blob.Length; break; } case CompiledCueFileType.WAVE: { var blob = new Disc.Blob_WaveFile(); OUT_Disc.DisposableResources.Add(file_blob = blob); blob.Load(ccf.FullPath); bi.Length = blob.Length; break; } case CompiledCueFileType.DecodeAudio: { FFmpegService ffmpeg = new FFmpegService(); if (!ffmpeg.QueryServiceAvailable()) { throw new DiscReferenceException(ccf.FullPath, "No decoding service was available (make sure ffmpeg.exe is available. Even though this may be a wav, ffmpeg is used to load oddly formatted wave files. If you object to this, please send us a note and we'll see what we can do. It shouldn't be too hard.)"); } AudioDecoder dec = new AudioDecoder(); byte[] buf = dec.AcquireWaveData(ccf.FullPath); var blob = new Disc.Blob_WaveFile(); OUT_Disc.DisposableResources.Add(file_blob = blob); blob.Load(new MemoryStream(buf)); bi.Length = buf.Length; break; } default: throw new InvalidOperationException(); } //switch(file type) //wrap all the blobs with zero padding bi.Blob = new Disc.Blob_ZeroPadAdapter(file_blob, bi.Length); } }