private HLLocation ProcessConversionExpression(IConversion pExpression) { HLLocation locationSource = ProcessExpression(pExpression.ValueToConvert); HLLocation locationTemporary = HLTemporaryLocation.Create(CreateTemporary(HLDomain.GetOrCreateType(pExpression.TypeAfterConversion))); mCurrentBlock.EmitAssignment(locationTemporary, locationSource); return(locationTemporary); }
public RecipeNutritionSummaryResolver( IDailyIntakeHelper dailyIntakeHelper, IConversion conversion, IOptions <DailyIntakeReference> dailyIntakeRef) { _dailyIntakeHelper = dailyIntakeHelper; _conversion = conversion; _dailyIntakeRef = dailyIntakeRef.Value; }
public async Task Convert(string Inputfile, string OutputFile) { StopWatch watcher = new StopWatch(); IConversion Conversion = await FFmpeg.Conversions.FromSnippet.Convert(Inputfile, OutputFile); await Conversion.Start(); watcher.PrintDur("XABE"); }
public static void randomizeScaleAndAspectRatio(IConversion some) { int x = randomMod(100, 1000); int y = randomMod(100, 1000); Random r = new Random(); string aspectRatio = r.Next(1, 20) + ":" + r.Next(1, 20); some.AddParameter("-vf scale=" + x + ":" + y + ",setdar=" + aspectRatio); // this is just an extra, didnt seem to work in discord ... }
public void CombineTsFiles(string title, long streamId) { CreateCombinedTsFile(); IConversion conversion = FFmpeg.Conversions.New() .AddParameter($"-f concat -safe 0 -i {_partsDirectory.FullName}/combinedTs.txt -c copy {_rootDirectory.FullName}/stream.mp4") .SetOverwriteOutput(true); conversion.Start().Wait(); }
//从视频中提取音频文件 public static async void ExtractAudio(Info info) { IConversion conversion = await FFmpeg.Conversions.FromSnippet.ExtractAudio(info.VideoPath, info.bgmTemp); if (File.Exists(info.bgmTemp)) { System.IO.File.Delete(info.bgmTemp); } IConversionResult result = await conversion.Start(); }
public void SetUp() { _uut = new Conversion(); string track = "ATR423;11111;22222;33333;20180409095330123"; trackliste = new List <string>(); trackliste.Add(track); convertliste = _uut.ConvertTrack(trackliste); }
public void Set <U>(IConversion <T, U> conversion) { if (conversion == null) { throw new ArgumentNullException(nameof(conversion)); } if (Get <U>().Exists) { throw new ArgumentException($"Conversion to {nameof(U)} already set.", nameof(conversion)); } _conversions[typeof(U)] = conversion; }
public static async Task <string> Get10k() // revision this later on. Must make mp4 resize to 10k pixel image { string path = Path.GetTempPath() + "10k10k10k10k10k10k10k10k10k10k10k10k10k10k10k10k10k10k.mp4"; IConversion c = FFmpeg.Conversions.New(); c.SetOverwriteOutput(true); c.AddParameter("-ss 999 -framerate 1 -i C:\\crasherstest\\10k.png -codec copy -pix_fmt yuv420p " + path); await c.Start(); return(path); }
//拆分音频文件 public static async void SplitAudio(Info info) { double start = info.BeginTime; double span = info.EndTime - info.BeginTime; if (File.Exists(info.cutAudio)) { System.IO.File.Delete(info.cutAudio); } IConversion conversion = await FFmpeg.Conversions.FromSnippet.Split(info.bgmTemp, info.cutAudio, TimeSpan.FromSeconds(start), TimeSpan.FromSeconds(span)); IConversionResult result = await conversion.Start(); }
public DietaryProfileService( IConversion conversion, IDailyIntakeHelper dailyIntakeHelper, IOptions <DailyIntakeReference> dailyIntakeRef, IDietaryProfilesRepository dietaryProfilesRepository, IMapper mapper) { _conversion = conversion; _dailyIntakeHelper = dailyIntakeHelper; _dailyIntakeRef = dailyIntakeRef.Value; _dietaryProfilesRepository = dietaryProfilesRepository; _mapper = mapper; }
public static async Task <IConversionResult> tsTest(string path) { string temp = Path.GetTempPath() + Guid.NewGuid().ToString() + ".ts"; IConversion c = await FFmpeg.Conversions.FromSnippet.ToTs(path, temp); c.SetOverwriteOutput(true); await c.Start(); IConversion c2 = await FFmpeg.Conversions.FromSnippet.ToMp4(temp, path); c2.SetOverwriteOutput(true); return(await c2.Start()); }
//https://ffmpeg.xabe.net/docs.html public async Task <IConversionResult> ConverVideoAsync(string videoPath, string outputPath) { if (string.IsNullOrEmpty(videoPath)) { throw new ArgumentException($"'{nameof(videoPath)}' cannot be null or empty", nameof(videoPath)); } if (string.IsNullOrEmpty(outputPath)) { throw new ArgumentException($"'{nameof(outputPath)}' cannot be null or empty", nameof(outputPath)); } string outputName = Path.Combine(outputPath, Path.GetFileNameWithoutExtension(videoPath) + ".mp4"); try { IMediaInfo mediaInfo = FFmpeg.GetMediaInfo(videoPath).Result; IConversion converter = FFmpeg.Conversions.New(); IVideoStream videoStream = mediaInfo.VideoStreams.FirstOrDefault(); if (videoStream == null) { throw new NullReferenceException("Failed to extract video stream from the source file."); } converter.AddStream(videoStream); IAudioStream audioStream = mediaInfo.AudioStreams.FirstOrDefault(ii => !string.IsNullOrEmpty(ii.Language) && ii.Language.ToLower().Equals("jpn")); if (audioStream == null) { //Could not find a Japanese audio stream lets take the default audioStream = mediaInfo.AudioStreams.FirstOrDefault(); if (audioStream == null) { throw new NullReferenceException("Failed to extract audio stream from the source file."); } } audioStream.SetCodec(AudioCodec.aac); converter.AddStream(audioStream); IConversionResult subsResult = await ExtractSubsAsync(videoPath, outputPath, mediaInfo.SubtitleStreams); converter.SetOutputFormat(Format.mp4); converter.SetOutput(outputName); converter.OnProgress += Converter_OnProgress; IConversionResult result = await converter.Start(cancellationTokenSource.Token); return(result); } catch (Exception ex) { throw; } }
public static async Task <IConversionResult> generateBrokenSample(string master, string output, TimeSpan start, TimeSpan duration) { string temp = Path.GetFullPath(output) + "temp-" + Path.GetFileName(output); if (File.Exists(temp)) { File.Delete(temp); } IConversion bad = await FFmpeg.Conversions.FromSnippet.Split(master, temp, start, duration); bad.SetOverwriteOutput(true); bad.SetPixelFormat(randomPixelFormat()); // this does 90% of the crash randomizeScaleAndAspectRatio(bad); await bad.Start(); IMediaInfo meta = await FFmpeg.GetMediaInfo(temp); IVideoStream v = meta.VideoStreams.ToList().FirstOrDefault(); v.SetSize(randomVideoSize()); { var sub = SubtitleGenerator.New(); await sub.AddSubtitle(TimeSpan.FromSeconds(0), meta.Duration, " ̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺ͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩ 𓀐 ̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺ͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩ 𓀐 ̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺ͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩ 𓀐 ̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺ͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩ 𓀐 ̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺ͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩ 𓀐 ̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺̺ͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩͩ 𓀐\n".Repeat(100)); v.AddSubtitles(sub.Filepath); } IAudioStream a = meta.AudioStreams.ToList().FirstOrDefault(); a.Reverse(); // the people who survive will get confused a.ChangeSpeed(0.5); var result = await FFmpeg.Conversions.New() .SetOverwriteOutput(true) .AddStream(v) .AddStream(a) .SetOutput(output) .SetPixelFormat(PixelFormat.yuv444p) .SetVideoSyncMethod(VideoSyncMethod.passthrough) .Start(); File.Delete(temp); return(result); }
//拆分视频文件 public static async void SplitVideo(Info info) { string videoPath = info.VideoPath; double start = info.BeginTime; double span = info.EndTime - info.BeginTime; string output = info.cutVideo; if (File.Exists(output)) { System.IO.File.Delete(output); } IConversion conversion = await FFmpeg.Conversions.FromSnippet.Split(videoPath, output, TimeSpan.FromSeconds(start), TimeSpan.FromSeconds(start + span)); IConversionResult result = await conversion.Start(); }
private void ClipButtonClick(object sender, RoutedEventArgs e) { StatusText = "Initializing..."; Progress = 0; string outFile = $"{OutputDirectory}\\{OutputName}{Path.GetExtension(Source)}"; string src = Source; TimeSpan totalTime = Player.NaturalDuration.TimeSpan; _ = Task.Run(async() => { try { // If the whole video is selected, upload source directly if (startTime.TotalMilliseconds < 1000 && (totalTime - stopTime).TotalMilliseconds < 1000) { UploadClip(src); } else { if (File.Exists(outFile)) { var dialogResult = MessageBox.Show($"{outFile} already exists, do you want to overwrite it?", $"File already exists", MessageBoxButton.YesNo, MessageBoxImage.Warning); if (dialogResult == MessageBoxResult.No) { Dispatcher.Invoke(() => StatusText = "File already exists"); return; } else { File.Delete(outFile); } } IConversion conversion = FFmpeg.Conversions.New() .AddParameter($"-ss {startTime.ToString("hh\\:mm\\:ss")} -t {durationTime.ToString("hh\\:mm\\:ss")} -i \"{src}\" -acodec copy -vcodec copy \"{outFile}\""); conversion.OnProgress += OnConversionProgress; Dispatcher.Invoke(() => StatusText = "Creating clip"); IConversionResult result = await conversion.Start(); UploadClip(outFile); } } catch (Exception exception) { Console.WriteLine(exception.Message); } }); }
public static async Task <IConversionResult> webmBreaker(string path) { string temp = Path.GetTempPath() + Guid.NewGuid().ToString() + ".webm"; IConversion c = await FFmpeg.Conversions.FromSnippet.ToWebM(path, temp); c.SetOverwriteOutput(true); // c.SetPixelFormat(randomPixelFormat()); // randomizeScaleAndAspectRatio(c); c.AddParameter("-vf scale=10000:10000"); await c.Start(); IConversion c2 = await FFmpeg.Conversions.FromSnippet.ToMp4(temp, path); c2.SetOverwriteOutput(true); return(await c2.Start()); }
public async Task <BaseApiResult <List <string> > > GetThumbnails(string videoPath) { if (string.IsNullOrEmpty(videoPath)) { return(BaseApiResult <List <string> > .ErrorState(ErrorType.Failed, "path cannot be null")); } try { //FFmpeg.SetExecutablesPath(AppManager.FFmpegSaveDir); List <string> result = new List <string>(); //最多截图四张截图 for (int i = 1; i < 5; i++) { string name = videoPath.GetHashCode().ToString(); int seconds = i * i + 5; string distPath = Path.GetTempPath() + $"{name}_{seconds}.png"; if (!File.Exists(distPath)) { var mediaInfo = await FFmpeg.GetMediaInfo(videoPath); //秒超过总长度 if (seconds > mediaInfo.Duration.TotalSeconds) { break; } IConversion conversion = await FFmpeg.Conversions.FromSnippet.Snapshot(videoPath, distPath, TimeSpan.FromSeconds(seconds)); _ = await conversion.Start(); } distPath = distPath.Replace(@"\", @"\\"); //result.Add(WebUtility.UrlEncode(distPath)); result.Add(distPath); } return(BaseApiResult <List <string> > .SuccessState(result)); } catch (FFmpegNotFoundException) { return(BaseApiResult <List <string> > .ErrorState(ErrorType.NoFFmpeg)); } catch (Exception ex) { return(BaseApiResult <List <string> > .ExceptionState(ex)); } }
public static async void extractThumbnailAsync(int id) { //thumbnails extracted from video at second 0 //three format of thumbnails generated using ffmpeg string dir = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location).Split("bin")[0]; string videoPath = string.Format("{0}wwwroot\\videos\\{1}.mp4", dir, id.ToString()); string[] thumbnailFormats = new string[] { "160x90", "240x135", "320x180" }; for (int i = 0; i < 3; i++) { string thumbnailPath = string.Format("{0}wwwroot/thumbnails/{1}_{2}.webp", dir, id.ToString(), i.ToString()); IConversion conversion = await FFmpeg.Conversions.FromSnippet.Snapshot(videoPath, thumbnailPath, TimeSpan.FromSeconds(0)); IConversionResult result = await conversion.AddParameter(String.Format("-s {0}", thumbnailFormats[i])).Start(); } }
public static async Task <IConversionResult> gifBreaker(string path) { string temp = Path.GetTempPath() + Guid.NewGuid().ToString() + ".gif"; IConversion c = await FFmpeg.Conversions.FromSnippet.ToGif(path, temp, 0); c.SetOverwriteOutput(true); c.SetPixelFormat(randomPixelFormat()); randomizeScaleAndAspectRatio(c); c.AddParameter($"-ignore_loop 0"); await c.Start(); IConversion c2 = await FFmpeg.Conversions.FromSnippet.ToMp4(temp, path); c2.SetOverwriteOutput(true); return(await c2.Start()); }
public static Unit GetUnit(this IConversion conversion) { if (conversion is IdentityConversion identityConversion) { var unit = Settings.Instance.AllUnits.Single(x => x.Symbol == identityConversion.Symbol); return(unit); } foreach (var unit in Settings.Instance.AllUnits) { if (unit.AllConversions.Any(pc => pc == conversion)) { return(unit); } } throw new ArgumentOutOfRangeException($"Could not find a unit matching symbol {conversion.Symbol} for conversion {conversion.Name}"); }
/// <summary> /// Instancia um novo objecto do tipo /// <see cref="OuterElementFractionConversion{OutElementType, FractionElementType}"/>. /// </summary> /// <param name="outTypeToFractionTypeConversion"> /// O objecto do tipo correspondente aos elementos externos. /// </param> /// <param name="domain">O domínio.</param> /// <exception cref="ArgumentNullException"> /// Se algum dos argumentos for nulo. /// </exception> public OuterElementFractionConversion( IConversion <OutElementType, FractionElementType> outTypeToFractionTypeConversion, IEuclidenDomain <FractionElementType> domain) { if (domain == null) { throw new ArgumentNullException("domain"); } else if (outTypeToFractionTypeConversion == null) { throw new ArgumentNullException("outTypeToFractionTypeConversion"); } else { this.domain = domain; this.outTypeToFractionTypeConversion = outTypeToFractionTypeConversion; } }
public async Task <VideoFrameExtractionResponse> SaveImageFrames(string videoFile, string saveImagesTo, int frameStepMilliseconds, int maxDurationMilliseconds) { var extractedVideoFrames = new List <VideoFrame>(); var videoFileName = Path.GetFileNameWithoutExtension(videoFile); var mediaInfo = await FFmpeg.GetMediaInfo(videoFile); var videoDurationMilliseconds = (int)mediaInfo.VideoStreams.First().Duration.TotalMilliseconds; //let's just assume not null var duration = (videoDurationMilliseconds <= maxDurationMilliseconds) ? videoDurationMilliseconds : maxDurationMilliseconds; for (var i = 0; i < duration; i++) { var fromMilliseconds = (i * frameStepMilliseconds); var fileName = $"{videoFileName}-{fromMilliseconds}"; var filePath = Path.Combine(saveImagesTo, fileName + ".png"); if (fromMilliseconds > duration) { break; } if (File.Exists(filePath)) { extractedVideoFrames.Add(new VideoFrame { Millisecond = fromMilliseconds, FilePath = filePath }); continue; } IConversion conversion = await FFmpeg.Conversions.FromSnippet.Snapshot(videoFile, filePath, TimeSpan.FromMilliseconds(fromMilliseconds)); IConversionResult result = await conversion.Start(); extractedVideoFrames.Add(new VideoFrame { Millisecond = fromMilliseconds, FilePath = filePath }); } return(new VideoFrameExtractionResponse { Success = true, VideoFrames = extractedVideoFrames }); }
IEnumerable<IConversion> Combination(INavigator navigator, IConversion startFeature = null) { var startType = Source; if(startFeature != null) startType = navigator.End(startFeature); foreach(var feature in AllFeatures.Where(feature => navigator.Start(feature) == startType)) { var destination = navigator.End(feature); if(_foundTypes.Contains(destination)) continue; _foundTypes.Add(destination); var newFeature = navigator.Combine(startFeature, feature); if(newFeature == null) continue; yield return newFeature; _newFeatures.Add(newFeature); } }
/// <summary> /// Saves a video from the images in the ImageFolder /// </summary> /// <param name="preset">The Xabe.FFmpeg preset to use (some values will be overwritten)</param> /// <param name="framerate">The desired framerate of the output video</param> /// <param name="outputVideoPath">The path including the file name and extension to the desired output video. e.g C:\dir\output.mp4</param> /// <param name="multithread">Whether to multithread the process</param> public void SaveVideo(IConversion preset, double framerate, bool multithread = true) { if (!Setup.FFmpegExists) { Setup.DownloadFFmpeg(); } string fileType = io.Path.GetExtension(ImagePaths[0]); var conv = preset .SetFrameRate(framerate) .SetOverwriteOutput(true) .SetOutput(OutputVideoPath) .AddParameter("-i \"" + io.Path.Combine(Path, @"image%d" + fileType) + "\"") .AddParameter("-start_number 0") .UseMultiThread(multithread); conv.Start().Wait(); }
public async Task <IActionResult> AddVideos(IFormCollection formdata) { //await FFmpegDownloader.GetLatestVersion(FFmpegVersion.Official); //FFmpeg.SetExecutablesPath(@"D:\Downloads\Сане\ffmpeg-20200501-39fb1e9-win64-static\ffmpeg-20200501-39fb1e9-win64-static\bin"); int i = 0; string GalleryPath = env.WebRootPath + @"\Uploads\Videos"; string dbGalleryPath = @"/Uploads/Videos"; string VideoName = ""; foreach (var file in formdata.Files) { if (file.Length > 0) { var extension = Path.GetExtension(file.FileName); var filename = DateTime.Now.ToString("ddMMHHmmssfff"); var path = Path.Combine(GalleryPath, filename) + extension; var dbPath = dbGalleryPath + "/" + filename + extension; string VideoCaption = formdata["VideoCaption[]"][i]; VideoName = formdata["VideoName[]"][i]; GalleryVideo video = new GalleryVideo(); video.Caption = VideoCaption; video.VideoUrl = dbPath; video.Name = VideoName; using (var stream = new FileStream(path, FileMode.Create)) { file.CopyTo(stream); } i++; string thumbPath = env.WebRootPath + @"\Uploads\Videos\Thumbnails\" + filename + ".jpeg"; string dbThumbPath = @"/Uploads/Videos/ThumbNails/" + filename + ".jpeg"; video.ThumbUrl = dbThumbPath; await db.GalleryVideos.AddAsync(video); IConversion conversion = await FFmpeg.Conversions.FromSnippet.Snapshot(path, thumbPath, TimeSpan.FromSeconds(0)); IConversionResult result = await conversion.Start(); } } await db.SaveChangesAsync(); return(new JsonResult("Видеофайл " + VideoName + " загружен")); }
/// <summary> /// Instancia um novo objecto do tipo /// <see cref="SubsetSumLLLReductionAlgorithm{CoeffType, NearestCoeffFieldType}"/>. /// </summary> /// <param name="vectorFactory">A fábrica responsável pela criação de vectores.</param> /// <param name="scalarProd">O objecto responsável pelos produtos escalares.</param> /// <param name="nearest">O objecto responsável pela determinação dos valores mais próximos.</param> /// <param name="fieldComparer">O comparador de objectos do corpo.</param> /// <param name="converter">O conversor de objectos.</param> /// <param name="nearestField">O objecto responsável pela determinação dos elementos mais próximos.</param> /// <exception cref="ArgumentNullException"> /// Se algum dos argumentos for nulo. /// </exception> public SubsetSumLLLReductionAlgorithm( IMathVectorFactory <NearestCoeffFieldType> vectorFactory, IScalarProductSpace <IMathVector <NearestCoeffFieldType>, NearestCoeffFieldType> scalarProd, INearest <NearestCoeffFieldType, NearestCoeffFieldType> nearest, IComparer <NearestCoeffFieldType> fieldComparer, IConversion <CoeffType, NearestCoeffFieldType> converter, IField <NearestCoeffFieldType> nearestField) { if (nearestField == null) { throw new ArgumentNullException("nearestField"); } else if (converter == null) { throw new ArgumentNullException("converter"); } else if (fieldComparer == null) { throw new ArgumentNullException("fieldComparer"); } else if (nearest == null) { throw new ArgumentNullException("nearest"); } else if (scalarProd == null) { throw new ArgumentNullException("scalarProd"); } else if (vectorFactory == null) { throw new ArgumentNullException("vectorFactory"); } else { this.vectorFactory = vectorFactory; this.scalarProd = scalarProd; this.nearest = nearest; this.fieldComparer = fieldComparer; this.converter = converter; this.nearestField = nearestField; } }
/// <summary> /// Guarda video convertido a mp4 /// </summary> /// <returns>Tarea que espera mientras se convierte el video</returns> private async Task SaveVideo() { try { using (var fs = File.Create(fullPathOriginal)) { file.CopyTo(fs); } FFmpeg.SetExecutablesPath(FFMPEG_PATH); IConversion conversion = await FFmpeg.Conversions.FromSnippet.ToMp4(fullPathOriginal, fullPath); await conversion.Start(); File.Delete(fullPathOriginal); } catch (Exception e) { _logger.LogInformation(e.Message); } }
bool TryConvert(string input, string output) { bool sucess = false; try { string extention = Path.GetExtension(input); if (SupportedExtentions.Contains(extention)) { IConversion conv = Conversion.Convert(input, output); conv.SetAudioBitrate(320000); conv.Start().Wait(); sucess = true; } } catch { } return(sucess); }
private async Task Worker(CancellationToken token) { while (!token.IsCancellationRequested) { IConversion conversion = null; try { _start.WaitOne(); conversion = GetNext(); Interlocked.Increment(ref _number); await conversion.Start(token); OnConverted?.Invoke((int)Interlocked.Read(ref _number), (int)Interlocked.Read(ref _totalItems), conversion); } catch (Exception) { OnException?.Invoke((int)Interlocked.Read(ref _number), (int)Interlocked.Read(ref _totalItems), conversion); } } }
public async Task BurnSubtitlesWithParametersTest() { IMediaInfo inputFile = await FFmpeg.GetMediaInfo(Resources.MkvWithAudio); string outputPath = _storageFixture.GetTempFileName(FileExtensions.Mp4); IConversion conversion = FFmpeg.Conversions.New() .AddStream(inputFile.VideoStreams.First() .AddSubtitles(Resources.SubtitleSrt, VideoSize.Xga, "UTF-8", "Fontsize=20,PrimaryColour=&H00ffff&,MarginV=30")) .SetOutput(outputPath); IConversionResult conversionResult = await conversion.Start(); IMediaInfo mediaInfo = await FFmpeg.GetMediaInfo(outputPath); Assert.Equal(9, mediaInfo.Duration.Seconds); Assert.Equal("h264", mediaInfo.VideoStreams.First().Codec); Assert.False(mediaInfo.AudioStreams.Any()); Assert.Contains($":charenc=UTF-8:force_style='Fontsize=20,PrimaryColour=&H00ffff&,MarginV=30':original_size=1024x768", conversion.Build()); }
/// <summary> /// /// </summary> /// <param name="conversion"></param> public Conversion(IConversion conversion) : base(conversion) { this.checkNumericRange = conversion.CheckNumericRange; this.typeAfterConversion = conversion.TypeAfterConversion; this.valueToConvert = conversion.ValueToConvert; }
/// <summary> /// Returns a shallow copy of the given conversion expression. /// </summary> /// <param name="conversion"></param> public Conversion Copy(IConversion conversion) { Contract.Requires(conversion != null); Contract.Ensures(Contract.Result<Conversion>() != null); return new Conversion(conversion); }
/// <summary> /// Performs some computation with the given conversion expression. /// </summary> /// <param name="conversion"></param> public virtual void Visit(IConversion conversion) { this.Visit((IExpression)conversion); }
//^ ensures this.path.Count == old(this.path.Count); /// <summary> /// Traverses the given conversion expression. /// </summary> /// <param name="conversion"></param> public virtual void Visit(IConversion conversion) { if (this.stopTraversal) return; //^ int oldCount = this.path.Count; this.path.Push(conversion); this.Visit(conversion.ValueToConvert); //^ assume this.path.Count == oldCount+1; //True because all of the virtual methods of this class promise not to decrease this.path.Count. this.path.Pop(); }
/// <summary> /// Performs some computation with the given conversion expression. /// </summary> /// <param name="conversion"></param> public virtual void Visit(IConversion conversion) { }
/// <summary> /// Traverses the children of the conversion expression. /// </summary> public virtual void TraverseChildren(IConversion conversion) { Contract.Requires(conversion != null); this.TraverseChildren((IExpression)conversion); if (this.StopTraversal) return; this.Traverse(conversion.ValueToConvert); if (this.StopTraversal) return; this.Traverse(conversion.TypeAfterConversion); }
/// <summary> /// Visits the specified conversion. /// </summary> /// <param name="conversion">The conversion.</param> public override void Visit(IConversion conversion) { Conversion mutableConversion = new Conversion(conversion); this.resultExpression = this.myCodeCopier.DeepCopy(mutableConversion); }
/// <summary> /// Returns a deep copy of the given conversion expression. /// </summary> /// <param name="conversion"></param> public Conversion Copy(IConversion conversion) { var mutableCopy = this.shallowCopier.Copy(conversion); this.CopyChildren((Expression)mutableCopy); mutableCopy.ValueToConvert = this.Copy(mutableCopy.ValueToConvert); mutableCopy.TypeAfterConversion = this.Copy(mutableCopy.TypeAfterConversion); return mutableCopy; }
/// <summary> /// Generates IL for the specified conversion. /// </summary> /// <param name="conversion">The conversion.</param> public override void TraverseChildren(IConversion conversion) { this.Traverse(conversion.ValueToConvert); //TODO: change IConversion to make it illegal to convert to or from enum types. ITypeReference sourceType = conversion.ValueToConvert.Type; ITypeReference targetType = conversion.Type; // The code model represents the implicit conversion of "null" to a reference type // with an explicit conversion. But that does not need to be present in the IL. // There it can just be implicit. var ctc = conversion.ValueToConvert as ICompileTimeConstant; if (ctc != null && ctc.Value == null && targetType.TypeCode == PrimitiveTypeCode.NotPrimitive && TypeHelper.TypesAreEquivalent(sourceType, this.host.PlatformType.SystemObject)) return; if (sourceType.ResolvedType.IsEnum && !TypeHelper.TypesAreEquivalent(targetType, this.host.PlatformType.SystemObject)) sourceType = sourceType.ResolvedType.UnderlyingType; if (targetType.ResolvedType.IsEnum) targetType = targetType.ResolvedType.UnderlyingType; if (sourceType is Dummy) sourceType = targetType; if (targetType is Dummy) targetType = sourceType; if (TypeHelper.TypesAreEquivalent(sourceType, targetType)) return; if (conversion.CheckNumericRange) this.VisitCheckedConversion(sourceType, targetType); else this.VisitUncheckedConversion(sourceType, targetType); }
public VccCastArrayConversion(IConversion conversion, IExpression size) { this.conversion = conversion; this.size = size; }
public override void TraverseChildren(IConversion conversion) { if (conversion.ValueToConvert is IVectorLength) { this.Traverse(((IVectorLength)conversion.ValueToConvert).Vector); if (conversion.TypeAfterConversion.TypeCode == PrimitiveTypeCode.Int64 || conversion.TypeAfterConversion.TypeCode == PrimitiveTypeCode.UInt64) this.sourceEmitterOutput.Write(".LongLength"); else this.sourceEmitterOutput.Write(".Length"); return; } if (conversion.CheckNumericRange) this.sourceEmitterOutput.Write("checked"); this.sourceEmitterOutput.Write("(("); this.PrintTypeReferenceName(conversion.TypeAfterConversion); this.sourceEmitterOutput.Write(")"); this.Traverse(conversion.ValueToConvert); this.sourceEmitterOutput.Write(")"); }
/// <summary> /// Generates IL for the specified conversion. /// </summary> /// <param name="conversion">The conversion.</param> public override void TraverseChildren(IConversion conversion) { this.Traverse(conversion.ValueToConvert); //TODO: change IConversion to make it illegal to convert to or from enum types. ITypeReference sourceType = conversion.ValueToConvert.Type; if (sourceType.ResolvedType.IsEnum) sourceType = sourceType.ResolvedType.UnderlyingType; ITypeReference targetType = conversion.Type; if (targetType.ResolvedType.IsEnum) targetType = targetType.ResolvedType.UnderlyingType; if (sourceType == Dummy.TypeReference) sourceType = targetType; if (targetType == Dummy.TypeReference) targetType = sourceType; if (TypeHelper.TypesAreEquivalent(sourceType, targetType)) return; if (conversion.CheckNumericRange) this.VisitCheckedConversion(sourceType, targetType); else this.VisitUncheckedConversion(sourceType, targetType); }
/// <summary> /// Rewrites the given conversion expression. /// </summary> /// <param name="conversion"></param> public virtual IExpression Rewrite(IConversion conversion) { return conversion; }
public override void TraverseChildren(IConversion conversion) { MethodEnter(conversion); base.TraverseChildren(conversion); MethodExit(); }
/// <summary> /// Returns a shallow copy of the given conversion expression. /// </summary> /// <param name="conversion"></param> public Conversion Copy(IConversion conversion) { return new Conversion(conversion); }
TypeBase INavigator.End(IConversion feature) => feature.Source;
public void Visit(IConversion conversion) { this.result = this.copier.Copy(conversion); }
/// <summary> /// Traverses the conversion expression. /// </summary> public void Traverse(IConversion conversion) { Contract.Requires(conversion != null); if (this.preorderVisitor != null) this.preorderVisitor.Visit(conversion); if (this.StopTraversal) return; this.TraverseChildren(conversion); if (this.StopTraversal) return; if (this.postorderVisitor != null) this.postorderVisitor.Visit(conversion); }
public override void Visit(IConversion conversion) { if(Process(conversion)){visitor.Visit(conversion);} base.Visit(conversion); }
public void Visit(IConversion conversion) { this.traverser.Traverse(conversion); }
public override void TraverseChildren(IConversion conversion) { var tok = conversion.ValueToConvert.Token(); this.Traverse(conversion.ValueToConvert); var boogieTypeOfValue = this.sink.CciTypeToBoogie(conversion.ValueToConvert.Type); var boogieTypeToBeConvertedTo = this.sink.CciTypeToBoogie(conversion.TypeAfterConversion); if (boogieTypeOfValue == boogieTypeToBeConvertedTo && !TranslationHelper.IsStruct(conversion.ValueToConvert.Type) && !TranslationHelper.IsStruct(conversion.TypeAfterConversion)) { // then this conversion is a nop, just ignore it return; } var nameOfTypeToConvert = TypeHelper.GetTypeName(conversion.ValueToConvert.Type); var nameOfTypeToBeConvertedTo = TypeHelper.GetTypeName(conversion.TypeAfterConversion); var msg = String.Format("Can't convert '{0}' to '{1}'", nameOfTypeToConvert, nameOfTypeToBeConvertedTo); var exp = TranslatedExpressions.Pop(); if (boogieTypeOfValue == this.sink.Heap.UnionType && boogieTypeToBeConvertedTo != this.sink.Heap.RefType) { var e = this.sink.Heap.FromUnion(tok, boogieTypeToBeConvertedTo, exp, false); TranslatedExpressions.Push(e); return; } if (boogieTypeToBeConvertedTo == this.sink.Heap.UnionType) { Bpl.Expr e; if (boogieTypeOfValue == this.sink.Heap.RefType) e = new Bpl.NAryExpr(Bpl.Token.NoToken, new Bpl.FunctionCall(this.sink.Heap.Unbox2Union), new List<Bpl.Expr>(new Bpl.Expr[] {exp})); else e = this.sink.Heap.ToUnion(tok, boogieTypeOfValue, exp, false, StmtTraverser.StmtBuilder); TranslatedExpressions.Push(e); return; } if (boogieTypeToBeConvertedTo == this.sink.Heap.RefType && TranslationHelper.IsStruct(conversion.TypeAfterConversion) && boogieTypeOfValue == this.sink.Heap.RefType) { // REVIEW: This also applies to conversions from one struct type to another! TranslatedExpressions.Push(exp); return; } if (boogieTypeToBeConvertedTo == Bpl.Type.Bool) { Bpl.Expr expr; if (boogieTypeOfValue == Bpl.Type.Int) { expr = Bpl.Expr.Binary(Bpl.BinaryOperator.Opcode.Neq, exp, Bpl.Expr.Literal(0)); } else if (boogieTypeOfValue == this.sink.Heap.RefType) { expr = new Bpl.NAryExpr(Bpl.Token.NoToken, new Bpl.FunctionCall(this.sink.Heap.Unbox2Bool), new List<Bpl.Expr>(new Bpl.Expr[] {exp})); } else if (boogieTypeOfValue == this.sink.Heap.RealType) { expr = new Bpl.NAryExpr(Bpl.Token.NoToken, new Bpl.FunctionCall(this.sink.Heap.Real2Int), new List<Bpl.Expr>(new Bpl.Expr[] {exp})); expr = Bpl.Expr.Binary(Bpl.BinaryOperator.Opcode.Neq, expr, Bpl.Expr.Literal(0)); } else if (boogieTypeOfValue == this.sink.Heap.UnionType) { expr = this.sink.Heap.FromUnion(tok, Bpl.Type.Bool, exp, false); } else { throw new NotImplementedException(msg); } TranslatedExpressions.Push(expr); return; } if (boogieTypeToBeConvertedTo == Bpl.Type.Int) { Bpl.Expr expr; if (boogieTypeOfValue == Bpl.Type.Bool) { expr = new Bpl.NAryExpr(tok, new Bpl.IfThenElse(tok), new List<Bpl.Expr>(new Bpl.Expr[] {exp, Bpl.Expr.Literal(1), Bpl.Expr.Literal(0)})); } else if (boogieTypeOfValue == this.sink.Heap.RefType) { expr = new Bpl.NAryExpr(Bpl.Token.NoToken, new Bpl.FunctionCall(this.sink.Heap.Unbox2Int), new List<Bpl.Expr>(new Bpl.Expr[] {exp})); } else if (boogieTypeOfValue == this.sink.Heap.RealType) { expr = new Bpl.NAryExpr(Bpl.Token.NoToken, new Bpl.FunctionCall(this.sink.Heap.Real2Int), new List<Bpl.Expr>(new Bpl.Expr[] {exp})); } else if (boogieTypeOfValue == this.sink.Heap.UnionType) { expr = this.sink.Heap.FromUnion(Bpl.Token.NoToken, Bpl.Type.Int, exp, false); } else { throw new NotImplementedException(msg); } TranslatedExpressions.Push(expr); return; } if (boogieTypeToBeConvertedTo == this.sink.Heap.RefType) { // var a = BoxFromXXX(exp); Bpl.Variable a = this.sink.CreateFreshLocal(conversion.TypeAfterConversion); Bpl.Procedure boxOperator; if (boogieTypeOfValue == Bpl.Type.Bool) boxOperator = this.sink.Heap.BoxFromBool; else if (boogieTypeOfValue == Bpl.Type.Int) boxOperator = this.sink.Heap.BoxFromInt; else if (boogieTypeOfValue == this.sink.Heap.RealType) boxOperator = this.sink.Heap.BoxFromReal; else if (TranslationHelper.IsStruct(conversion.ValueToConvert.Type)) { // Boxing a struct implicitly makes a copy of the struct var typeOfValue = conversion.ValueToConvert.Type; var proc = this.sink.FindOrCreateProcedureForStructCopy(typeOfValue); var bplLocal = Bpl.Expr.Ident(this.sink.CreateFreshLocal(typeOfValue)); var cmd = new Bpl.CallCmd(tok, proc.Name, new List<Bpl.Expr> { exp, }, new List<Bpl.IdentifierExpr> { bplLocal, }); this.StmtTraverser.StmtBuilder.Add(cmd); TranslatedExpressions.Push(bplLocal); return; } else { if (boogieTypeOfValue != this.sink.Heap.UnionType) throw new NotImplementedException(msg); boxOperator = this.sink.Heap.BoxFromUnion; } var name = boxOperator.Name; this.StmtTraverser.StmtBuilder.Add(new Bpl.CallCmd(Bpl.Token.NoToken, name, new List<Bpl.Expr>(new Bpl.Expr[] {exp}), new List<Bpl.IdentifierExpr>(new Bpl.IdentifierExpr[] {Bpl.Expr.Ident(a)}))); TranslatedExpressions.Push(Bpl.Expr.Ident(a)); return; } if (boogieTypeToBeConvertedTo == this.sink.Heap.RealType) { Bpl.Expr expr; if (boogieTypeOfValue == Bpl.Type.Bool) { expr = new Bpl.NAryExpr(tok, new Bpl.IfThenElse(tok), new List<Bpl.Expr>(new Bpl.Expr[] {exp, Bpl.Expr.Literal(1), Bpl.Expr.Literal(0)})); expr = new Bpl.NAryExpr(Bpl.Token.NoToken, new Bpl.FunctionCall(this.sink.Heap.Int2Real), new List<Bpl.Expr>(new Bpl.Expr[] {expr})); } else if (boogieTypeOfValue == Bpl.Type.Int) { expr = new Bpl.NAryExpr(Bpl.Token.NoToken, new Bpl.FunctionCall(this.sink.Heap.Int2Real), new List<Bpl.Expr>(new Bpl.Expr[] {exp})); } else if (boogieTypeOfValue == this.sink.Heap.RefType) { expr = new Bpl.NAryExpr(Bpl.Token.NoToken, new Bpl.FunctionCall(this.sink.Heap.Unbox2Real), new List<Bpl.Expr>(new Bpl.Expr[] { exp })); } else if (boogieTypeOfValue == this.sink.Heap.UnionType) { expr = this.sink.Heap.FromUnion(tok, this.sink.Heap.RealType, exp, false); } else { throw new NotImplementedException(msg); } TranslatedExpressions.Push(expr); return; } //if (boogieTypeToBeConvertedTo == this.sink.Heap.UnionType) { // Bpl.Function func; // if (boogieTypeOfValue == Bpl.Type.Bool) { // func = this.sink.Heap.Bool2Union; // } // else if (boogieTypeOfValue == Bpl.Type.Int) { // func = this.sink.Heap.Int2Union; // } // else if (boogieTypeOfValue == this.sink.Heap.RefType) { // func = this.sink.Heap.Ref2Union; // } // else if (boogieTypeOfValue == this.sink.Heap.RealType) { // func = this.sink.Heap.Real2Union; // } // else { // throw new NotImplementedException(msg); // } // var boxExpr = new Bpl.NAryExpr(conversion.Token(), new Bpl.FunctionCall(func), new List<Bpl.Expr>(exp)); // TranslatedExpressions.Push(boxExpr); // return; //} }
public void Visit(IConversion conversion) { Contract.Requires(conversion != null); throw new NotImplementedException(); }
private HLLocation ProcessConversionExpression(IConversion pExpression) { HLLocation locationSource = ProcessExpression(pExpression.ValueToConvert); HLLocation locationTemporary = HLTemporaryLocation.Create(CreateTemporary(HLDomain.GetOrCreateType(pExpression.TypeAfterConversion))); mCurrentBlock.EmitAssignment(locationTemporary, locationSource); return locationTemporary; }
public void Visit(IConversion conversion) { throw new NotImplementedException(); }
IConversion INavigator.Combine(IConversion start, IConversion end) => Feature.Combination.CheckedCreate(end, start);
public override void TraverseChildren(IConversion conversion) { base.TraverseChildren(conversion); Conversion/*?*/ conv = conversion as Conversion; if (conv != null) { if (conv.TypeAfterConversion.TypeCode == PrimitiveTypeCode.IntPtr || conv.Type.TypeCode == PrimitiveTypeCode.UIntPtr) { if (conv.ValueToConvert.Type is IPointerTypeReference || conv.ValueToConvert.Type is IManagedPointerTypeReference) { conv.Type = conv.TypeAfterConversion = conv.ValueToConvert.Type; //TODO: hmm. Perhaps this is all wrong. In IL the point of the conversion is to "forget" that the pointer has type conv.ValueToConvert.Type. //so that the verifier will allow the pointer to be abused as a pointer to something else return; } } conv.Type = conversion.TypeAfterConversion; } }
public override void TraverseChildren(IConversion conversion) { if (conversion.ValueToConvert is IVectorLength) { this.Traverse(((IVectorLength)conversion.ValueToConvert).Vector); if (conversion.TypeAfterConversion.TypeCode == PrimitiveTypeCode.Int64 || conversion.TypeAfterConversion.TypeCode == PrimitiveTypeCode.UInt64) this.sourceEmitterOutput.Write(".LongLength"); else this.sourceEmitterOutput.Write(".Length"); return; } var needsParen = LowerPrecedenceThanParentExpression(conversion); var savedCurrentPrecedence = this.currentPrecedence; this.currentPrecedence = this.Precedence(conversion); if (conversion.CheckNumericRange) this.sourceEmitterOutput.Write("checked"); if (needsParen) this.sourceEmitterOutput.Write("("); this.sourceEmitterOutput.Write("("); this.PrintTypeReferenceName(conversion.TypeAfterConversion); this.sourceEmitterOutput.Write(")"); this.Traverse(conversion.ValueToConvert); if (needsParen) this.sourceEmitterOutput.Write(")"); this.currentPrecedence = savedCurrentPrecedence; }
public virtual void onASTElement(IConversion conversion) { }
/// <summary> /// Returns a deep copy of the given conversion expression. /// </summary> /// <param name="conversion"></param> public Conversion Copy(IConversion conversion) { Contract.Requires(conversion != null); Contract.Ensures(Contract.Result<Conversion>() != null); var mutableCopy = this.shallowCopier.Copy(conversion); this.CopyChildren((Expression)mutableCopy); mutableCopy.ValueToConvert = this.Copy(mutableCopy.ValueToConvert); mutableCopy.TypeAfterConversion = this.Copy(mutableCopy.TypeAfterConversion); return mutableCopy; }