public async Task <MediaEncodingProfile> GetEncodingAsync() { int originalWidth = (int)Properties.Width; int originalHeight = (int)Properties.Height; if (IsEdited && _editState is BitmapEditState state && state.Rectangle is Rect rectangle) { originalWidth = (int)rectangle.Width; originalHeight = (int)rectangle.Height; } UpdateWidthHeightBitrateForCompression(_compression); var profile = await MediaEncodingProfile.CreateFromFileAsync(File); if (resultWidth != originalWidth || resultHeight != originalHeight) { profile.Video.Width = (uint)resultWidth; profile.Video.Height = (uint)resultHeight; profile.Video.Bitrate = Math.Min((uint)bitrate, profile.Video.Bitrate); } if (_isMuted) { profile.Audio = null; } return(profile); }
public new static async Task <StorageVideo> CreateAsync(StorageFile file, bool selected) { try { if (!file.IsAvailable) { return(null); } var profile = await MediaEncodingProfile.CreateFromFileAsync(file); if (profile.Video == null) { return(null); } var basic = await file.GetBasicPropertiesAsync(); var video = await file.Properties.GetVideoPropertiesAsync(); if (video.Width > 0 && video.Height > 0) { return(new StorageVideo(file, basic, video, profile)); } return(null); } catch { return(null); } }
private async void SendPhotoExecute(StoragePhoto file) { ObservableCollection <StorageMedia> storages = null; if (file == null) { var picker = new FileOpenPicker(); picker.ViewMode = PickerViewMode.Thumbnail; picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; picker.FileTypeFilter.AddRange(Constants.MediaTypes); var files = await picker.PickMultipleFilesAsync(); if (files != null) { storages = new ObservableCollection <StorageMedia>(files.Select(x => x.Name.EndsWith(".mp4") ? new StorageVideo(x) : (StorageMedia) new StoragePhoto(x))); } } else { storages = new ObservableCollection <StorageMedia> { file }; } if (storages != null && storages.Count > 0) { var dialog = new SendPhotosView { ViewModel = this, Items = storages, SelectedItem = storages[0], IsTTLEnabled = _peer is TLInputPeerUser }; var dialogResult = await dialog.ShowAsync(); TextField.FocusMaybe(FocusState.Keyboard); if (dialogResult == ContentDialogBaseResult.OK) { foreach (var storage in dialog.Items) { if (storage is StoragePhoto photo) { await SendPhotoAsync(storage.File, storage.Caption, storage.TTLSeconds); } else if (storage is StorageVideo video) { MediaEncodingProfile profile = null; if (video.IsMuted) { profile = await MediaEncodingProfile.CreateFromFileAsync(storage.File); profile.Audio = null; } await SendVideoAsync(storage.File, storage.Caption, false, profile); } } } } }
async Task <MediaEncodingProfile> GetEncodingProfileFromFileAsync(StorageFile file) { try { return(await MediaEncodingProfile.CreateFromFileAsync(file)); } catch { } return(null); }
public async Task CS_WP_MC_LumiaCropSquare() { StorageFile source = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Input/Car.mp4")); StorageFile destination = await KnownFolders.VideosLibrary.CreateFileAsync("CS_W_MT_CropSquare.mp4", CreationCollisionOption.ReplaceExisting); // Select the largest centered square area in the input video var encodingProfile = await MediaEncodingProfile.CreateFromFileAsync(source); uint inputWidth = encodingProfile.Video.Width; uint inputHeight = encodingProfile.Video.Height; uint outputLength = Math.Min(inputWidth, inputHeight); Rect cropArea = new Rect( (float)((inputWidth - outputLength) / 2), (float)((inputHeight - outputLength) / 2), (float)outputLength, (float)outputLength ); encodingProfile.Video.Width = outputLength; encodingProfile.Video.Height = outputLength; var definition = new LumiaEffectDefinition(new FilterChainFactory(() => { var filters = new List <IFilter>(); filters.Add(new CropFilter(cropArea)); return(filters); })); definition.InputWidth = inputWidth; definition.InputHeight = inputHeight; definition.OutputWidth = outputLength; definition.OutputHeight = outputLength; var clip = await MediaClip.CreateFromFileAsync(source); clip.VideoEffectDefinitions.Add(definition); var composition = new MediaComposition(); composition.Clips.Add(clip); MediaStreamSource sourceStreamSource = composition.GenerateMediaStreamSource(); using (IRandomAccessStream destinationStream = await destination.OpenAsync(FileAccessMode.ReadWrite)) { var transcoder = new MediaTranscoder(); var transcode = await transcoder.PrepareMediaStreamSourceTranscodeAsync(sourceStreamSource, destinationStream, MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Qvga)); await transcode.TranscodeAsync(); } }
private static async void TranscodeFile(MediaEncodingProfile profile, TimeSpan trimStartTime, TimeSpan trimStopTime, StorageFile srcFile, StorageFile destFile, Action <StorageFile, ulong> callback, Action <double> progressCallback, Action <IAsyncActionWithProgress <double> > faultCallback) { profile = profile ?? await MediaEncodingProfile.CreateFromFileAsync(srcFile); var transcoder = new MediaTranscoder { TrimStartTime = trimStartTime, TrimStopTime = trimStopTime }; var prepareOp = await transcoder.PrepareFileTranscodeAsync(srcFile, destFile, profile); //Telegram.Api.Helpers.Execute.ShowDebugMessage(string.Format("TranscodeFile\nvideo=[{0}x{1} {2}]\naudio=[{3}]\ntrim_start={4} trim_end={5}", profile.Video.Width, profile.Video.Height, profile.Video.Bitrate, profile.Audio != null ? profile.Audio.Bitrate : 0, trimStartTime, trimStopTime)); if (prepareOp.CanTranscode) { var transcodeOp = prepareOp.TranscodeAsync(); transcodeOp.Progress += (result, progress) => { progressCallback.SafeInvoke(progress); }; transcodeOp.Completed += async(o, e) => { var properties = await destFile.GetBasicPropertiesAsync(); var size = properties.Size; TranscodeComplete(o, e, () => callback(destFile, size), faultCallback); }; } else { faultCallback.SafeInvoke(null); switch (prepareOp.FailureReason) { case TranscodeFailureReason.CodecNotFound: Telegram.Api.Helpers.Execute.BeginOnUIThread(() => MessageBox.Show(AppResources.CodecWasNotFound, AppResources.Error, MessageBoxButton.OK)); break; case TranscodeFailureReason.InvalidProfile: Telegram.Api.Helpers.Execute.BeginOnUIThread(() => MessageBox.Show(AppResources.ProfileIsInvalid, AppResources.Error, MessageBoxButton.OK)); break; default: Telegram.Api.Helpers.Execute.BeginOnUIThread(() => MessageBox.Show(AppResources.UnknownFailure, AppResources.Error, MessageBoxButton.OK)); break; } } }
public async Task Record() { if (IsRecording) { throw new InvalidOperationException("Recording already in progress!"); } _memoryBuffer = new InMemoryRandomAccessStream(); _mediaCapture = new MediaCapture(); MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings { StreamingCaptureMode = StreamingCaptureMode.Audio }; await _mediaCapture.InitializeAsync(settings); MediaEncodingProfile recordProfile = new MediaEncodingProfile(); AudioEncodingProperties audioProp = new AudioEncodingProperties(); audioProp.ChannelCount = 1; audioProp.BitsPerSample = 16; audioProp.SampleRate = 8000; audioProp.Bitrate = 16; audioProp.Subtype = MediaEncodingSubtypes.AmrNb; recordProfile.Audio = audioProp; ContainerEncodingProperties containProp = new ContainerEncodingProperties(); containProp.Subtype = MediaEncodingSubtypes.Mpeg4; recordProfile.Container = containProp; recordProfile.Video = null; //await _mediaCapture.StartRecordToStorageFileAsync(recordProfile, fileBuffer); StorageFile amr = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/a.amr")); var pro = await MediaEncodingProfile.CreateFromFileAsync(amr); pro.Container.Subtype = MediaEncodingSubtypes.Mpeg4; var pro2 = MediaEncodingProfile.CreateWma(AudioEncodingQuality.Low); await _mediaCapture.StartRecordToStreamAsync(pro2, _memoryBuffer); IsRecording = true; }
public async void SendPhotoDrop(ObservableCollection <StorageFile> files) { ObservableCollection <StorageMedia> storages = null; if (files != null) { storages = new ObservableCollection <StorageMedia>(files.Select(x => new StoragePhoto(x))); } if (storages != null && storages.Count > 0) { var dialog = new SendPhotosView { ViewModel = this, Items = storages, SelectedItem = storages[0], IsTTLEnabled = _peer is TLInputPeerUser }; var dialogResult = await dialog.ShowAsync(); TextField.FocusMaybe(FocusState.Keyboard); if (dialogResult == ContentDialogBaseResult.OK) { foreach (var storage in dialog.Items) { if (storage is StoragePhoto photo) { await SendPhotoAsync(storage.File, storage.Caption, storage.TTLSeconds); } else if (storage is StorageVideo video) { MediaEncodingProfile profile = null; if (video.IsMuted) { profile = await MediaEncodingProfile.CreateFromFileAsync(storage.File); profile.Audio = null; } await SendVideoAsync(storage.File, storage.Caption, false, profile); } } } } }
public async Task CS_WP_MT_LumiaCropSquare() { StorageFile source = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Input/Car.mp4")); StorageFile destination = await KnownFolders.VideosLibrary.CreateFileAsync("CS_W_MT_CropSquare.mp4", CreationCollisionOption.ReplaceExisting); // Select the largest centered square area in the input video var encodingProfile = await MediaEncodingProfile.CreateFromFileAsync(source); uint inputWidth = encodingProfile.Video.Width; uint inputHeight = encodingProfile.Video.Height; uint outputLength = Math.Min(inputWidth, inputHeight); Rect cropArea = new Rect( (float)((inputWidth - outputLength) / 2), (float)((inputHeight - outputLength) / 2), (float)outputLength, (float)outputLength ); encodingProfile.Video.Width = outputLength; encodingProfile.Video.Height = outputLength; var definition = new LumiaEffectDefinition(new FilterChainFactory(() => { var filters = new List <IFilter>(); filters.Add(new CropFilter(cropArea)); return(filters); })); definition.InputWidth = inputWidth; definition.InputHeight = inputHeight; definition.OutputWidth = outputLength; definition.OutputHeight = outputLength; var transcoder = new MediaTranscoder(); transcoder.AddVideoEffect(definition.ActivatableClassId, true, definition.Properties); PrepareTranscodeResult transcode = await transcoder.PrepareFileTranscodeAsync(source, destination, encodingProfile); await transcode.TranscodeAsync(); }
private async void StartMediaElementPreview_Click(object sender, RoutedEventArgs e) { StartMediaElementPreview.IsEnabled = false; // Cleanup any previous playback MediaElementPreview.Stop(); MediaElementPreview.Source = null; MediaElementPreview.RemoveAllEffects(); StorageFile source = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Car.mp4")); var encodingProfile = await MediaEncodingProfile.CreateFromFileAsync(source); var definition = await CreateEffectDefinitionAsync(encodingProfile.Video); MediaElementPreview.Source = new Uri("ms-appx:///Assets/Car.mp4"); MediaElementPreview.AddVideoEffect(definition.ActivatableClassId, false, definition.Properties); StartMediaElementPreview.IsEnabled = true; }
private async void Transcode_Click(object sender, RoutedEventArgs e) { StartMediaTranscoder.IsEnabled = false; StorageFile source = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Car.mp4")); StorageFile destination = await KnownFolders.VideosLibrary.CreateFileAsync("VideoEffectsTestApp.MediaTranscoder.mp4", CreationCollisionOption.ReplaceExisting); var encodingProfile = await MediaEncodingProfile.CreateFromFileAsync(source); var definition = await CreateEffectDefinitionAsync(encodingProfile.Video); var transcoder = new MediaTranscoder(); transcoder.AddVideoEffect(definition.ActivatableClassId, true, definition.Properties); PrepareTranscodeResult transcode = await transcoder.PrepareFileTranscodeAsync(source, destination, MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Qvga)); await transcode.TranscodeAsync(); StartMediaTranscoder.IsEnabled = true; }
private async void StartMediaCompositionPreview_Click(object sender, RoutedEventArgs e) { StartMediaCompositionPreview.IsEnabled = false; StorageFile source = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Car.mp4")); var encodingProfile = await MediaEncodingProfile.CreateFromFileAsync(source); var definition = await CreateEffectDefinitionAsync(encodingProfile.Video); var clip = await MediaClip.CreateFromFileAsync(source); clip.VideoEffectDefinitions.Add(definition); var composition = new MediaComposition(); composition.Clips.Add(clip); MediaCompositionPreview.SetMediaStreamSource(composition.GenerateMediaStreamSource()); StartMediaCompositionPreview.IsEnabled = true; }
private async void StartMediaCompositionRender_Click(object sender, RoutedEventArgs e) { StartMediaCompositionRender.IsEnabled = false; StorageFile source = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Car.mp4")); StorageFile destination = await KnownFolders.VideosLibrary.CreateFileAsync("VideoEffectsTestApp.MediaComposition.mp4", CreationCollisionOption.ReplaceExisting); var encodingProfile = await MediaEncodingProfile.CreateFromFileAsync(source); var definition = await CreateEffectDefinitionAsync(encodingProfile.Video); var clip = await MediaClip.CreateFromFileAsync(source); clip.VideoEffectDefinitions.Add(definition); var composition = new MediaComposition(); composition.Clips.Add(clip); await composition.RenderToFileAsync(destination); StartMediaCompositionRender.IsEnabled = true; }
private async void Button_Click_1(object sender, RoutedEventArgs e) { //MediaEncodingProfile profile = new MediaEncodingProfile(); //profile.Video = property; //profile.Video.Subtype = MediaEncodingSubtypes.H264; //profile.Video.Height = Source_height; //profile.Video.Width = Source_width; //profile.Video.FrameRate.Numerator = Source_frameRate; //profile.Audio.Subtype = MediaEncodingSubtypes.Aac; //profile.Audio.SampleRate = SampleRate; MediaEncodingProfile profile = await MediaEncodingProfile.CreateFromFileAsync(source); profile.Video.Subtype = MediaEncodingSubtypes.H264; profile.Video.Height = Source_height; profile.Video.Width = Source_width; profile.Video.FrameRate.Numerator = Source_frameRate; profile.Audio.SampleRate = SampleRate; profile.Audio.Subtype = MediaEncodingSubtypes.Aac; MediaTranscoder transcoder = new MediaTranscoder(); //MediaEncodingProfile profile = new MediaEncodingProfile(); //profile.Video.Subtype = MediaEncodingSubtypes.H264; //profile.Video.Height = Source_height; //profile.Video.Width = Source_width; //profile.Video.FrameRate.Numerator = Source_frameRate; //profile.Video.Bitrate = property.Bitrate; //profile.Audio.SampleRate = SampleRate; //profile.Audio.Subtype = MediaEncodingSubtypes.Aac; //MediaTranscoder transcoder = new MediaTranscoder(); PrepareTranscodeResult prepareOp = await transcoder.PrepareFileTranscodeAsync(source, destination, profile); if (prepareOp.CanTranscode) { var transcodeOp = prepareOp.TranscodeAsync(); transcodeOp.Progress += new AsyncActionProgressHandler <double>(TranscodeProgress); transcodeOp.Completed += new AsyncActionWithProgressCompletedHandler <double>(TranscodeComplete); } else { switch (prepareOp.FailureReason) { case TranscodeFailureReason.CodecNotFound: System.Diagnostics.Debug.WriteLine("Codec not found."); break; case TranscodeFailureReason.InvalidProfile: System.Diagnostics.Debug.WriteLine("Invalid profile."); break; default: System.Diagnostics.Debug.WriteLine("Unknown failure."); break; } } }
/// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. /// This parameter is typically used to configure the page.</param> protected override async void OnNavigatedTo(NavigationEventArgs e) { StorageFile source = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Input/Car.mp4")); // Select the largest centered square area in the input video var inputProfile = await MediaEncodingProfile.CreateFromFileAsync(source); uint inputWidth = inputProfile.Video.Width; uint inputHeight = inputProfile.Video.Height; uint outputLength = Math.Min(inputWidth, inputHeight); Rect cropArea = new Rect( (float)((inputWidth - outputLength) / 2), (float)((inputHeight - outputLength) / 2), (float)outputLength, (float)outputLength ); // Create the output encoding profile var outputProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.HD720p); outputProfile.Video.Bitrate = inputProfile.Video.Bitrate; outputProfile.Video.FrameRate.Numerator = inputProfile.Video.FrameRate.Numerator; outputProfile.Video.FrameRate.Denominator = inputProfile.Video.FrameRate.Denominator; outputProfile.Video.Width = outputLength; outputProfile.Video.Height = outputLength; var definition = new LumiaEffectDefinition(new FilterChainFactory(() => { var filters = new List <IFilter>(); filters.Add(new CropFilter(cropArea)); return(filters); })); definition.InputWidth = inputWidth; definition.InputHeight = inputHeight; definition.OutputWidth = outputLength; definition.OutputHeight = outputLength; var clip = await MediaClip.CreateFromFileAsync(source); clip.VideoEffectDefinitions.Add(definition); var composition = new MediaComposition(); composition.Clips.Add(clip); TextLog.Text = "Encoding using MediaComposition"; StorageFile destination1 = await KnownFolders.VideosLibrary.CreateFileAsync("Square_MC.mp4", CreationCollisionOption.ReplaceExisting); await composition.RenderToFileAsync(destination1, MediaTrimmingPreference.Fast, outputProfile); TextLog.Text = "Encoding using MediaTranscoder"; StorageFile destination2 = await KnownFolders.VideosLibrary.CreateFileAsync("Square_MT.mp4", CreationCollisionOption.ReplaceExisting); var transcoder = new MediaTranscoder(); transcoder.AddVideoEffect(definition.ActivatableClassId, true, definition.Properties); var transcode = await transcoder.PrepareFileTranscodeAsync(source, destination2, outputProfile); await transcode.TranscodeAsync(); TextLog.Text = "Starting MediaComposition preview"; PreviewMC.SetMediaStreamSource( composition.GeneratePreviewMediaStreamSource((int)outputLength, (int)outputLength) ); TextLog.Text = "Starting MediaElement preview"; PreviewME.AddVideoEffect(definition.ActivatableClassId, false, definition.Properties); PreviewME.Source = new Uri("ms-appx:///Input/Car.mp4"); PreviewME.Play(); TextLog.Text = "Done"; }
public async Task <MediaEncodingProfile> GetEncodingAsync() { int originalWidth = (int)Properties.Width; int originalHeight = (int)Properties.Height; if (_editState is BitmapEditState state && state.Rectangle is Rect rectangle) { originalWidth = (int)rectangle.Width; originalHeight = (int)rectangle.Height; } int resultWidth = originalWidth; int resultHeight = originalHeight; int bitrate = this.originalBitrate; long videoFramesSize = 0; double videoDuration = 0; var selectedCompression = _compression; var compressionsCount = _maxCompression; if (selectedCompression != compressionsCount - 1) { float maxSize; int targetBitrate; switch (selectedCompression) { case 0: maxSize = 432.0f; targetBitrate = 400000; break; case 1: maxSize = 640.0f; targetBitrate = 900000; break; case 2: maxSize = 848.0f; targetBitrate = 1100000; break; case 3: default: targetBitrate = 1600000; maxSize = 1280.0f; break; } float scale = originalWidth > originalHeight ? maxSize / originalWidth : maxSize / originalHeight; resultWidth = (int)Math.Round(originalWidth * scale / 2) * 2; resultHeight = (int)Math.Round(originalHeight * scale / 2) * 2; if (bitrate != 0) { bitrate = Math.Min(targetBitrate, (int)(originalBitrate / scale)); videoFramesSize = (long)(bitrate / 8 * videoDuration / 1000); } } var profile = await MediaEncodingProfile.CreateFromFileAsync(File); //profile.Video.Width = (uint)resultWidth; //profile.Video.Height = (uint)resultHeight; //profile.Video.Bitrate = (uint)bitrate; if (_isMuted) { profile.Audio = null; } return(profile); }
private async Task TranscodeAsync(UpdateFileGenerationStart update, string[] args) { try { var conversion = JsonConvert.DeserializeObject <VideoConversion>(args[2]); if (conversion.Transcode) // <==> conversion.Mute (currently, see: MessageFactory) { var file = await StorageApplicationPermissions.FutureAccessList.GetFileAsync(args[0]); var temp = await StorageFile.GetFileFromPathAsync(update.DestinationPath); var profile = await MediaEncodingProfile.CreateFromFileAsync(file); if ((profile.Video.Width != conversion.Width || profile.Video.Height != conversion.Height) && conversion.Width > 0 && conversion.Height > 0 && conversion.Bitrate > 0) // All zero for video profile { profile.Video.Width = conversion.Width; //Note: OutputSize tells the video effect how to crop the video, and encoding profile tells the encoder how to encode the video profile.Video.Height = conversion.Height; profile.Video.Bitrate = conversion.Bitrate; } else if (profile.Video.Width == conversion.Width && profile.Video.Height == conversion.Height && Math.Abs(profile.Video.Bitrate - conversion.Bitrate) < 10000) { // Do not transcode if bitrate is very similar await CopyAsync(update, args); return; } else if (profile.Audio == null && conversion.Mute && conversion.TrimStartTime == null && conversion.TrimStopTime == null) { await CopyAsync(update, args); return; } //profile.Video.Width = conversion.Width; //profile.Video.Height = conversion.Height; //profile.Video.Bitrate = conversion.Bitrate; if (conversion.Mute) { profile.Audio = null; } var transcoder = new MediaTranscoder(); if (conversion.TrimStartTime is TimeSpan trimStart) { transcoder.TrimStartTime = trimStart; } if (conversion.TrimStopTime is TimeSpan trimStop) { transcoder.TrimStopTime = trimStop; } if (conversion.Transform) { var transform = new VideoTransformEffectDefinition(); transform.Rotation = conversion.Rotation; transform.OutputSize = conversion.OutputSize; transform.Mirror = conversion.Mirror; transform.CropRectangle = conversion.CropRectangle.IsEmpty() ? Rect.Empty : conversion.CropRectangle; profile.Video.Width = (uint)conversion.OutputSize.Width; profile.Video.Height = (uint)conversion.OutputSize.Height; transcoder.AddVideoEffect(transform.ActivatableClassId, true, transform.Properties); } var prepare = await transcoder.PrepareFileTranscodeAsync(file, temp, profile); if (prepare.CanTranscode) { var progress = prepare.TranscodeAsync(); progress.Progress = (result, delta) => { _protoService.Send(new SetFileGenerationProgress(update.GenerationId, 100, (int)delta)); }; progress.Completed = (result, delta) => { _protoService.Send(new FinishFileGeneration(update.GenerationId, prepare.FailureReason == TranscodeFailureReason.None ? null : new Error(500, prepare.FailureReason.ToString()))); }; } else { _protoService.Send(new FinishFileGeneration(update.GenerationId, new Error(500, prepare.FailureReason.ToString()))); } } else { await CopyAsync(update, args); } } catch (Exception ex) { _protoService.Send(new FinishFileGeneration(update.GenerationId, new Error(500, "FILE_GENERATE_LOCATION_INVALID " + ex.ToString()))); } }
private async Task TranscodeAsync(UpdateFileGenerationStart update) { try { var args = update.Conversion.Substring("transcode#".Length); args = args.Substring(0, args.LastIndexOf('#')); var conversion = JsonConvert.DeserializeObject <VideoConversion>(args); if (conversion.Transcode) { var file = await StorageFile.GetFileFromPathAsync(update.OriginalPath); var temp = await StorageFile.GetFileFromPathAsync(update.DestinationPath); var transcoder = new MediaTranscoder(); var profile = await MediaEncodingProfile.CreateFromFileAsync(file); profile.Video.Width = conversion.Width; profile.Video.Height = conversion.Height; profile.Video.Bitrate = conversion.Bitrate; if (conversion.Mute) { profile.Audio = null; } if (conversion.Transform) { var transform = new VideoTransformEffectDefinition(); transform.Rotation = conversion.Rotation; transform.OutputSize = conversion.OutputSize; transform.Mirror = conversion.Mirror; transform.CropRectangle = conversion.CropRectangle.IsEmpty() ? Rect.Empty : conversion.CropRectangle; transcoder.AddVideoEffect(transform.ActivatableClassId, true, transform.Properties); } var prepare = await transcoder.PrepareFileTranscodeAsync(file, temp, profile); if (prepare.CanTranscode) { var progress = prepare.TranscodeAsync(); progress.Progress = (result, delta) => { _protoService.Send(new SetFileGenerationProgress(update.GenerationId, (int)delta, 100)); }; progress.Completed = (result, delta) => { _protoService.Send(new FinishFileGeneration(update.GenerationId, prepare.FailureReason == TranscodeFailureReason.None ? null : new Error(406, prepare.FailureReason.ToString()))); }; } else { _protoService.Send(new FinishFileGeneration(update.GenerationId, new Error(500, prepare.FailureReason.ToString()))); } } else { await CopyAsync(update); } } catch (Exception ex) { _protoService.Send(new FinishFileGeneration(update.GenerationId, new Error(500, ex.ToString()))); } }
private async Task TranscodeAsync(UpdateFileGenerationStart update, string[] args) { try { var conversion = JsonConvert.DeserializeObject <VideoConversion>(args[2]); if (conversion.Mute) { var file = await StorageApplicationPermissions.FutureAccessList.GetFileAsync(args[0]); var temp = await StorageFile.GetFileFromPathAsync(update.DestinationPath); var profile = await MediaEncodingProfile.CreateFromFileAsync(file); if (profile.Audio == null && conversion.Mute) { await CopyAsync(update, args); return; } //profile.Video.Width = conversion.Width; //profile.Video.Height = conversion.Height; //profile.Video.Bitrate = conversion.Bitrate; if (conversion.Mute) { profile.Audio = null; } var transcoder = new MediaTranscoder(); if (conversion.Transform) { var transform = new VideoTransformEffectDefinition(); transform.Rotation = conversion.Rotation; transform.OutputSize = conversion.OutputSize; transform.Mirror = conversion.Mirror; transform.CropRectangle = conversion.CropRectangle.IsEmpty() ? Rect.Empty : conversion.CropRectangle; transcoder.AddVideoEffect(transform.ActivatableClassId, true, transform.Properties); } var prepare = await transcoder.PrepareFileTranscodeAsync(file, temp, profile); if (prepare.CanTranscode) { var progress = prepare.TranscodeAsync(); progress.Progress = (result, delta) => { _protoService.Send(new SetFileGenerationProgress(update.GenerationId, 100, (int)delta)); }; progress.Completed = (result, delta) => { _protoService.Send(new FinishFileGeneration(update.GenerationId, prepare.FailureReason == TranscodeFailureReason.None ? null : new Error(500, prepare.FailureReason.ToString()))); }; } else { _protoService.Send(new FinishFileGeneration(update.GenerationId, new Error(500, prepare.FailureReason.ToString()))); } } else { await CopyAsync(update, args); } } catch (Exception ex) { _protoService.Send(new FinishFileGeneration(update.GenerationId, new Error(500, "FILE_GENERATE_LOCATION_INVALID " + ex.ToString()))); } }
public static async Task <StorageVideo> CreateAsync(StorageFile file, bool selected) { return(new StorageVideo(file, await file.GetBasicPropertiesAsync(), await file.Properties.GetVideoPropertiesAsync(), await MediaEncodingProfile.CreateFromFileAsync(file)) { IsSelected = selected }); }
private async Task CalculateFrameRateFromFileAsync(IStorageFile file) { MediaEncodingProfile profile = await MediaEncodingProfile.CreateFromFileAsync(file); FrameRate = (double)profile.Video.FrameRate.Numerator / profile.Video.FrameRate.Denominator; }
private async void QueueContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args) { var Deferral = args.GetDeferral(); if (UseSameProfile.IsChecked.GetValueOrDefault()) { MediaEncoding = await MediaEncodingProfile.CreateFromFileAsync(VideoFile); TrimmingPreference = MediaTrimmingPreference.Precise; ExportFileType = VideoFile.FileType; } else { VideoEncodingQuality Quality = default; switch (EncodingQuality.SelectedIndex) { case 0: { Quality = VideoEncodingQuality.Uhd2160p; break; } case 1: { Quality = VideoEncodingQuality.HD1080p; break; } case 2: { Quality = VideoEncodingQuality.HD720p; break; } case 3: { Quality = VideoEncodingQuality.Wvga; break; } } switch (EncodingProfile.SelectedIndex) { case 0: { MediaEncoding = MediaEncodingProfile.CreateMp4(Quality); ExportFileType = ".mp4"; break; } case 1: { MediaEncoding = MediaEncodingProfile.CreateWmv(Quality); ExportFileType = ".wmv"; break; } case 2: { MediaEncoding = MediaEncodingProfile.CreateHevc(Quality); ExportFileType = ".mkv"; break; } } if (TrimmingProfile.SelectedIndex == 0) { TrimmingPreference = MediaTrimmingPreference.Precise; } else { TrimmingPreference = MediaTrimmingPreference.Fast; } } PreviewSource?.Dispose(); MediaPlay.Source = null; Deferral.Complete(); }
async Task <StorageFile> ConvertVideo(StorageFile inputFile, Size?imageSize, Rect?rectSize) { try { var outputFile = await GenerateRandomOutputFile(); if (inputFile != null && outputFile != null) { MediaProfile = await MediaEncodingProfile.CreateFromFileAsync(inputFile); FFmpegMSS = await FFmpegInteropMSS .CreateFromStreamAsync(await inputFile.OpenReadAsync(), Helper.FFmpegConfig); Mss = FFmpegMSS.GetMediaStreamSource(); if (!IsStoryVideo) { if (Mss.Duration.TotalSeconds > 59) { Transcoder.TrimStartTime = StartTime; Transcoder.TrimStopTime = StopTime; } var max = Math.Max(FFmpegMSS.VideoStream.PixelHeight, FFmpegMSS.VideoStream.PixelWidth); if (max > 1920) { max = 1920; } if (imageSize == null) { MediaProfile.Video.Height = (uint)max; MediaProfile.Video.Width = (uint)max; } else { MediaProfile.Video.Height = (uint)imageSize.Value.Height; MediaProfile.Video.Width = (uint)imageSize.Value.Width; } } else { if (Mss.Duration.TotalSeconds > 14.9) { Transcoder.TrimStartTime = StartTime; Transcoder.TrimStopTime = StopTime; } //var max = Math.Max(FFmpegMSS.VideoStream.PixelHeight, FFmpegMSS.VideoStream.PixelWidth); var size = Helpers.AspectRatioHelper.GetAspectRatioX(FFmpegMSS.VideoStream.PixelWidth, FFmpegMSS.VideoStream.PixelHeight); //if (max > 1920) // max = 1920; MediaProfile.Video.Height = (uint)size.Height; MediaProfile.Video.Width = (uint)size.Width; } var transform = new VideoTransformEffectDefinition { Rotation = MediaRotation.None, OutputSize = imageSize.Value, Mirror = MediaMirroringOptions.None, CropRectangle = rectSize == null ? Rect.Empty : rectSize.Value }; Transcoder.AddVideoEffect(transform.ActivatableClassId, true, transform.Properties); var preparedTranscodeResult = await Transcoder .PrepareMediaStreamSourceTranscodeAsync(Mss, await outputFile.OpenAsync(FileAccessMode.ReadWrite), MediaProfile); Transcoder.VideoProcessingAlgorithm = MediaVideoProcessingAlgorithm.Default; if (preparedTranscodeResult.CanTranscode) { var progress = new Progress <double>(ConvertProgress); await preparedTranscodeResult.TranscodeAsync().AsTask(Cts.Token, progress); ConvertComplete(outputFile); return(outputFile); } else { preparedTranscodeResult.FailureReason.ToString().ShowMsg(); } } } catch (Exception ex) { ex.PrintException().ShowMsg("ConvertVideo"); } return(null); }