예제 #1
0
        async Task <StorageUploadItem> ConvertVideoAsync(StorageUploadItem uploadItem)
        {
            try
            {
                var MediaProfile = MediaEncodingProfile.CreateMp4(uploadItem.VideoEncodingQuality);
                var outputFile   = await GenerateRandomOutputFile();

                if (uploadItem != null && outputFile != null)
                {
                    var inputFile = uploadItem.VideoToUpload;

                    //MediaProfile = await MediaEncodingProfile.CreateFromFileAsync(inputFile);
                    Transcoder.TrimStartTime = uploadItem.StartTime;
                    Transcoder.TrimStopTime  = uploadItem.EndTime;

                    MediaProfile.Video.Height = (uint)uploadItem.Size.Height;
                    MediaProfile.Video.Width  = (uint)uploadItem.Size.Width;


                    var transform = new VideoTransformEffectDefinition
                    {
                        Rotation      = MediaRotation.None,
                        OutputSize    = uploadItem.Size,
                        Mirror        = MediaMirroringOptions.None,
                        CropRectangle = uploadItem.Rect
                    };

                    Transcoder.AddVideoEffect(transform.ActivatableClassId, true, transform.Properties);

                    var preparedTranscodeResult = await Transcoder
                                                  .PrepareFileTranscodeAsync(inputFile,
                                                                             outputFile,
                                                                             //.PrepareMediaStreamSourceTranscodeAsync(Mss,
                                                                             //await outputFile.OpenAsync(FileAccessMode.ReadWrite),
                                                                             MediaProfile);

                    if (preparedTranscodeResult.CanTranscode)
                    {
                        var progress = new Progress <double>(ConvertProgress);
                        await preparedTranscodeResult.TranscodeAsync().AsTask(new CancellationTokenSource().Token, progress);

                        ConvertComplete(outputFile);
                        uploadItem.VideoToUpload = outputFile;
                        return(uploadItem);
                    }
                    else
                    {
                        preparedTranscodeResult.FailureReason.ToString().ShowMsg();
                    }
                }
            }
            catch (Exception ex) { ex.PrintException().ShowMsg("ConvertVideo"); }
            return(uploadItem);
        }
        private void AddTranscoderEffect()
        {
            // <SnippetTranscodingAddEffect>
            MediaTranscoder transcoder = new MediaTranscoder();

            transcoder.AddVideoEffect(
                "Windows.Media.VideoEffects.VideoStabilization");
            // </SnippetTranscodingAddEffect>

            // <SnippetTranscodingRemoveEffect>
            transcoder.ClearEffects();
            // </SnippetTranscodingRemoveEffect>
        }
예제 #3
0
        private async void TranscodeWithEffect()
        {
            var openPicker = new Windows.Storage.Pickers.FileOpenPicker();

            openPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.VideosLibrary;
            openPicker.FileTypeFilter.Add(".wmv");
            openPicker.FileTypeFilter.Add(".mp4");

            StorageFile sourceFile = await openPicker.PickSingleFileAsync();

            var savePicker = new Windows.Storage.Pickers.FileSavePicker();

            savePicker.SuggestedStartLocation =
                Windows.Storage.Pickers.PickerLocationId.VideosLibrary;

            savePicker.DefaultFileExtension = ".mp4";
            savePicker.SuggestedFileName    = "New Video";

            savePicker.FileTypeChoices.Add("MPEG4", new string[] { ".mp4" });

            StorageFile destinationFile = await savePicker.PickSaveFileAsync();


            MediaEncodingProfile mediaEncodingProfile =
                MediaEncodingProfile.CreateMp4(VideoEncodingQuality.HD720p);

            //<SnippetTrancodeWithEffect>
            MediaTranscoder transcoder = new MediaTranscoder();

            // Using the in-box video stabilization effect works
            //VideoStabilizationEffectDefinition videoEffect = new VideoStabilizationEffectDefinition();
            //transcoder.AddVideoEffect(videoEffect.ActivatableClassId);

            // My custom effect throws an exception
            var customEffectDefinition = new VideoEffectDefinition("VideoEffectComponent.ExampleVideoEffect", new PropertySet()
            {
                { "FadeValue", .25 }
            });

            transcoder.AddVideoEffect(customEffectDefinition.ActivatableClassId);

            PrepareTranscodeResult prepareOp = await
                                               transcoder.PrepareFileTranscodeAsync(sourceFile, destinationFile, mediaEncodingProfile);

            if (prepareOp.CanTranscode)
            {
                var transcodeOp = prepareOp.TranscodeAsync();
            }
            //</SnippetTrancodeWithEffect>
        }
예제 #4
0
        public async Task CS_W_MT_Basic(EffectType effectType)
        {
            StorageFile source = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Input/Car.mp4"));

            StorageFile destination = await CreateDestinationFileAync("CS_W_MT_Basic_" + effectType + ".mp4");

            var definition = await Utils.CreateEffectDefinitionAsync(effectType);

            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();
        }
예제 #5
0
        public async Task CS_W_MT_LumiaCropSquare(String inputFileName, String outputFileName)
        {
            StorageFile source = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Input/" + inputFileName));

            StorageFile destination = await CreateDestinationFileAync(outputFileName);

            // Select the largest centered square area in the input video
            var encodingProfile = await TranscodingProfile.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();
        }
예제 #6
0
        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;
        }
예제 #7
0
        /// <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";
        }
예제 #8
0
        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);
        }
예제 #9
0
        public async Task SendVideoAsync(StorageFile file, string caption, bool round, VideoTransformEffectDefinition transform = null, MediaEncodingProfile profile = null)
        {
            if (_peer == null)
            {
                return;
            }

            var fileLocation = new TLFileLocation
            {
                VolumeId = TLLong.Random(),
                LocalId = TLInt.Random(),
                Secret = TLLong.Random(),
                DCId = 0
            };

            var fileName = string.Format("{0}_{1}_{2}.mp4", fileLocation.VolumeId, fileLocation.LocalId, fileLocation.Secret);
            var fileCache = await FileUtils.CreateTempFileAsync(fileName);

            await file.CopyAndReplaceAsync(fileCache);

            var basicProps = await fileCache.GetBasicPropertiesAsync();
            var videoProps = await fileCache.Properties.GetVideoPropertiesAsync();
            var thumbnailBase = await FileUtils.GetFileThumbnailAsync(file);
            var thumbnail = thumbnailBase as TLPhotoSize;
            if (thumbnail == null)
            {
                return;
            }

            var desiredName = string.Format("{0}_{1}_{2}.jpg", thumbnail.Location.VolumeId, thumbnail.Location.LocalId, thumbnail.Location.Secret);

            var date = TLUtils.DateToUniversalTimeTLInt(ProtoService.ClientTicksDelta, DateTime.Now);

            var videoWidth = (int)videoProps.Width;
            var videoHeight = (int)videoProps.Height;

            if (profile != null)
            {
                videoWidth = (int)profile.Video.Width;
                videoHeight = (int)profile.Video.Height;
            }

            var document = new TLDocument
            {
                Id = 0,
                AccessHash = 0,
                Date = date,
                Size = (int)basicProps.Size,
                MimeType = fileCache.ContentType,
                Thumb = thumbnail,
                Attributes = new TLVector<TLDocumentAttributeBase>
                {
                    new TLDocumentAttributeFilename
                    {
                        FileName = file.Name
                    },
                    new TLDocumentAttributeVideo
                    {
                        Duration = (int)videoProps.Duration.TotalSeconds,
                        W = videoWidth,
                        H = videoHeight,
                        IsRoundMessage = round
                    }
                }
            };

            var media = new TLMessageMediaDocument
            {
                Document = document,
                Caption = caption
            };

            var message = TLUtils.GetMessage(SettingsHelper.UserId, _peer.ToPeer(), TLMessageState.Sending, true, true, date, string.Empty, media, TLLong.Random(), null);

            if (Reply != null)
            {
                message.HasReplyToMsgId = true;
                message.ReplyToMsgId = Reply.Id;
                message.Reply = Reply;
                Reply = null;
            }

            var previousMessage = InsertSendingMessage(message);
            CacheService.SyncSendingMessage(message, previousMessage, async (m) =>
            {
                if (transform != null && profile != null)
                {
                    await fileCache.RenameAsync(fileName + ".temp.mp4");
                    var fileResult = await FileUtils.CreateTempFileAsync(fileName);

                    var transcoder = new MediaTranscoder();
                    transcoder.AddVideoEffect(transform.ActivatableClassId, true, transform.Properties);

                    var prepare = await transcoder.PrepareFileTranscodeAsync(fileCache, fileResult, profile);
                    await prepare.TranscodeAsync().AsTask(Upload(media.Document as TLDocument, progress => new TLSendMessageUploadDocumentAction { Progress = progress }, 0, 200.0));

                    //await fileCache.DeleteAsync();
                    fileCache = fileResult;

                    thumbnailBase = await FileUtils.GetFileThumbnailAsync(fileCache);
                    thumbnail = thumbnailBase as TLPhotoSize;

                    desiredName = string.Format("{0}_{1}_{2}.jpg", thumbnail.Location.VolumeId, thumbnail.Location.LocalId, thumbnail.Location.Secret);
                    document.Thumb = thumbnail;
                }

                var fileId = TLLong.Random();
                var upload = await _uploadVideoManager.UploadFileAsync(fileId, fileCache.Name, false).AsTask(Upload(media.Document as TLDocument, progress => new TLSendMessageUploadDocumentAction { Progress = progress }, 0.5, 2.0));
                if (upload != null)
                {
                    var thumbFileId = TLLong.Random();
                    var thumbUpload = await _uploadDocumentManager.UploadFileAsync(thumbFileId, desiredName);
                    if (thumbUpload != null)
                    {
                        var inputMedia = new TLInputMediaUploadedThumbDocument
                        {
                            File = upload.ToInputFile(),
                            Thumb = thumbUpload.ToInputFile(),
                            MimeType = document.MimeType,
                            Caption = media.Caption,
                            Attributes = document.Attributes
                        };

                        var result = await ProtoService.SendMediaAsync(_peer, inputMedia, message);
                    }
                    //if (result.IsSucceeded)
                    //{
                    //    var update = result.Result as TLUpdates;
                    //    if (update != null)
                    //    {
                    //        var newMessage = update.Updates.OfType<TLUpdateNewMessage>().FirstOrDefault();
                    //        if (newMessage != null)
                    //        {
                    //            var newM = newMessage.Message as TLMessage;
                    //            if (newM != null)
                    //            {
                    //                message.Media = newM.Media;
                    //                message.RaisePropertyChanged(() => message.Media);
                    //            }
                    //        }
                    //    }
                    //}
                }
            });
        }
예제 #10
0
        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())));
            }
        }
예제 #11
0
        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())));
            }
        }
예제 #12
0
        async Task <StorageUploadItem> ConvertVideoAsync(StorageUploadItem uploadItem)
        {
            try
            {
                var mediaProfile = MediaEncodingProfile.CreateMp4(uploadItem.VideoEncodingQuality);
                var outputFile   = await GenerateRandomOutputFile();

                if (uploadItem != null && outputFile != null)
                {
                    var inputFile = uploadItem.VideoToUpload;

                    var fileProfile = await GetEncodingProfileFromFileAsync(inputFile);

                    if (fileProfile != null)
                    {
                        mediaProfile.Video.Bitrate = fileProfile.Video.Bitrate;
                        if (mediaProfile.Audio != null)
                        {
                            mediaProfile.Audio.Bitrate       = fileProfile.Audio.Bitrate;
                            mediaProfile.Audio.BitsPerSample = fileProfile.Audio.BitsPerSample;
                            mediaProfile.Audio.ChannelCount  = fileProfile.Audio.ChannelCount;
                            mediaProfile.Audio.SampleRate    = fileProfile.Audio.SampleRate;
                        }
                        "Media profile copied from original video".PrintDebug();
                    }
                    //MediaProfile = await MediaEncodingProfile.CreateFromFileAsync(inputFile);
                    Transcoder.TrimStartTime = uploadItem.StartTime;
                    Transcoder.TrimStopTime  = uploadItem.EndTime;

                    mediaProfile.Video.Height = (uint)uploadItem.Size.Height;
                    mediaProfile.Video.Width  = (uint)uploadItem.Size.Width;


                    var transform = new VideoTransformEffectDefinition
                    {
                        Rotation      = MediaRotation.None,
                        OutputSize    = uploadItem.Size,
                        Mirror        = MediaMirroringOptions.None,
                        CropRectangle = uploadItem.Rect
                    };

                    Transcoder.AddVideoEffect(transform.ActivatableClassId, true, transform.Properties);

                    var preparedTranscodeResult = await Transcoder
                                                  .PrepareFileTranscodeAsync(inputFile,
                                                                             outputFile,
                                                                             mediaProfile);

                    if (preparedTranscodeResult.CanTranscode)
                    {
                        var progress = new Progress <double>(ConvertProgress);
                        await preparedTranscodeResult.TranscodeAsync().AsTask(new CancellationTokenSource().Token, progress);

                        ConvertComplete(outputFile);
                        uploadItem.VideoToUpload = outputFile;
                        return(uploadItem);
                    }
                    else
                    {
                        preparedTranscodeResult.FailureReason.ToString().ShowMsg();
                    }
                }
            }
            catch (Exception ex) { ex.PrintException().ShowMsg("ConvertVideo"); }
            return(uploadItem);
        }
예제 #13
0
        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())));
            }
        }
예제 #14
0
        async Task <StorageFile> ConvertVideo(StorageFile inputFile, Size?imageSize, Rect?rectSize)
        {
            try
            {
                var outputFile = await GenerateRandomOutputFile();

                if (inputFile != null && outputFile != null)
                {
                    var    mediaProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto);
                    int    height = 0, width = 0;
                    double duration = 0;
                    if (DeviceUtil.IsMobile)
                    {
                        var videoInfo = await inputFile.GetVideoInfoAsync();

                        height   = (int)videoInfo.Height;
                        width    = (int)videoInfo.Width;
                        duration = videoInfo.Duration.TotalSeconds;
                    }
                    else
                    {
                        FFmpegMSS = await FFmpegInteropMSS
                                    .CreateFromStreamAsync(await inputFile.OpenReadAsync(), Helper.FFmpegConfig);

                        Mss      = FFmpegMSS.GetMediaStreamSource();
                        height   = FFmpegMSS.VideoStream.PixelHeight;
                        width    = FFmpegMSS.VideoStream.PixelWidth;
                        duration = Mss.Duration.TotalSeconds;
                    }

                    var fileProfile = await Uploads.VideoConverterX.GetEncodingProfileFromFileAsync(inputFile);

                    if (fileProfile != null)
                    {
                        mediaProfile.Video.Bitrate = fileProfile.Video.Bitrate;
                        if (mediaProfile.Audio != null)
                        {
                            mediaProfile.Audio.Bitrate       = fileProfile.Audio.Bitrate;
                            mediaProfile.Audio.BitsPerSample = fileProfile.Audio.BitsPerSample;
                            mediaProfile.Audio.ChannelCount  = fileProfile.Audio.ChannelCount;
                            mediaProfile.Audio.SampleRate    = fileProfile.Audio.SampleRate;
                        }
                        "Media profile copied from original video".PrintDebug();
                    }
                    if (!IsStoryVideo)
                    {
                        if (duration > 59)
                        {
                            Transcoder.TrimStartTime = StartTime;
                            Transcoder.TrimStopTime  = StopTime;
                        }


                        var max = Math.Max(height, width);
                        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 (duration > 14.9)
                        {
                            Transcoder.TrimStartTime = StartTime;
                            Transcoder.TrimStopTime  = StopTime;
                        }
                        var size = Helpers.AspectRatioHelper.GetAspectRatioX(width, height);
                        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);

                    PrepareTranscodeResult preparedTranscodeResult;
                    if (DeviceUtil.IsMobile)
                    {
                        preparedTranscodeResult = await Transcoder.PrepareFileTranscodeAsync(inputFile, outputFile, mediaProfile);
                    }
                    else
                    {
                        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);
        }