public async Task CS_WP_MC_PreviewTranscode(EffectType effectType)
        {
            StorageFile source = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Input/Car.mp4"));

            StorageFile destination = await KnownFolders.VideosLibrary.CreateFileAsync("CS_WP_MC_PreviewTranscode_" + effectType + ".mp4", CreationCollisionOption.ReplaceExisting);

            var definition = await Utils.CreateEffectDefinitionAsync(effectType);

            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();
            }
        }
Example #2
0
        private async Task SetTranscoder(StorageFile source, StorageFile destination, MediaEncodingProfile mediaEncodingProfile, CancellationToken cancellationToken)
        {
            MediaTranscoder mediaTranscoder = new MediaTranscoder();

            mediaTranscoder.AlwaysReencode = true;

            CancelTask(cancellationToken);

            PrepareTranscodeResult prepareTranscodeResult = await mediaTranscoder.PrepareFileTranscodeAsync(source, destination, mediaEncodingProfile);

            IAsyncActionWithProgress <double> progress = prepareTranscodeResult.TranscodeAsync();

            progress.Progress = new AsyncActionProgressHandler <double>(async(progressInfo, info) =>
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    progressInfo.Cancel();
                }
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(() =>
                {
                    ReportProgress(Stage7, Stage6ProgressBar, TextProgress6, info);
                    if (info == 100)
                    {
                        Save.Content = "Convert/Save";
                    }
                }));
            });
            CancelTask(cancellationToken);
        }
Example #3
0
        /*
         * Method for converting the MP4 to MP3
         * Writes to the destination file
         */
        private async Task ToAudioAsync(StorageFile source, StorageFile destination, MediaEncodingProfile profile)
        {
            var transcoder = new MediaTranscoder();
            var prepareOp  = await transcoder.PrepareFileTranscodeAsync(source, destination, profile);  // Prepare the file for conversion

            if (prepareOp.CanTranscode)
            {
                var transcodeOp = prepareOp.TranscodeAsync();   // Conversion

                // Progress handler
                transcodeOp.Progress += TranscodeProgress;
                // Completion handler
                transcodeOp.Completed += 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;
                }
            }
        }
    public ConvertToMp3Manager(StorageFile sourceAudio, StorageFile destinationAudio, AudioFormat AudioType = AudioFormat.MP3, AudioEncodingQuality audioEncodingQuality = AudioEncodingQuality.High)
    {
        if (sourceAudio == null || destinationAudio == null)
        {
            throw new ArgumentNullException("sourceAudio and destinationAudio cannot be null");
        }
        switch (AudioType)
        {
        case AudioFormat.AAC:
        case AudioFormat.M4A:
            profile = MediaEncodingProfile.CreateM4a(audioEncodingQuality);
            break;

        case AudioFormat.MP3:
            profile = MediaEncodingProfile.CreateMp3(audioEncodingQuality);
            break;

        case AudioFormat.WMA:
            profile = MediaEncodingProfile.CreateWma(audioEncodingQuality);
            break;
        }
        this.SourceAudio      = sourceAudio;
        this.DestinationAudio = destinationAudio;
        this.AudioFormat      = AudioType;
        this.AudioQuality     = audioEncodingQuality;
        this.TransCoder       = new MediaTranscoder();
    }
Example #5
0
        private void CreateMediaObjects()
        {
            // Create our encoding profile based on the size of the item
            // TODO: This only really makes sense for monitors, we need
            //       to change this to make sense in all cases.
            int width  = _captureItem.Size.Width;
            int height = _captureItem.Size.Height;

            // Describe our input: uncompressed BGRA8 buffers comming in at the monitor's refresh rate
            // TODO: We pick 60Hz here because it applies to most monitors. However this should be
            //       more robust.
            var videoProperties = VideoEncodingProperties.CreateUncompressed(MediaEncodingSubtypes.Bgra8, (uint)width, (uint)height);

            _videoDescriptor = new VideoStreamDescriptor(videoProperties);
            _videoDescriptor.EncodingProperties.FrameRate.Numerator   = c_frameRateN;
            _videoDescriptor.EncodingProperties.FrameRate.Denominator = c_frameRateD;
            _videoDescriptor.EncodingProperties.Bitrate = (uint)(c_frameRateN * c_frameRateD * width * height * 4);

            // Create our MediaStreamSource
            _mediaStreamSource                  = new MediaStreamSource(_videoDescriptor);
            _mediaStreamSource.BufferTime       = TimeSpan.FromSeconds(0);
            _mediaStreamSource.Starting        += OnMediaStreamSourceStarting;
            _mediaStreamSource.SampleRequested += OnMediaStreamSourceSampleRequested;

            // Create our device manager
            _mediaGraphicsDevice = MediaGraphicsDevice.CreateFromMediaStreamSource(_mediaStreamSource);
            _mediaGraphicsDevice.RenderingDevice = _device;

            // Create our transcoder
            _transcoder = new MediaTranscoder();
            _transcoder.HardwareAccelerationEnabled = true;
        }
Example #6
0
        public async static Task <StorageFile> FromStorageFile(StorageFile source)
        {
            MediaTranscoder         transcoder = new MediaTranscoder();
            MediaEncodingProfile    profile    = MediaEncodingProfile.CreateWav(AudioEncodingQuality.Medium);
            CancellationTokenSource cts        = new CancellationTokenSource();

            string      fileName = String.Format("TempFile_{0}.wav", Guid.NewGuid());
            StorageFile output   = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(fileName);

            if (source == null || output == null)
            {
                return(null);
            }
            try
            {
                var preparedTranscodeResult = await transcoder.PrepareFileTranscodeAsync(source, output, profile);

                if (preparedTranscodeResult.CanTranscode)
                {
                    var progress = new Progress <double>((percent) => { });
                    await preparedTranscodeResult.TranscodeAsync().AsTask(cts.Token, progress);
                }
                return(output);
            }
            catch
            {
                return(null);
            }
        }
Example #7
0
 public VideoConverterX()
 {
     Transcoder = new MediaTranscoder();
     //Cts = new CancellationTokenSource();
     //Mss = null;
     //FFmpegMSS = null;
 }
Example #8
0
        //MediaStreamSource MssTest;
        //FFmpegInteropMSS FFmpegMSSTest;

        public VideoConverter()
        {
            Transcoder = new MediaTranscoder();
            Cts        = new CancellationTokenSource();
            //Mss = null;
            //FFmpegMSS = null;
            MediaProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto);
        }
Example #9
0
        private static MediaTranscoder GetTranscoder()
        {
            var transcoder = new MediaTranscoder {
                HardwareAccelerationEnabled = true
            };

            return(transcoder);
        }
        //</SnippetRun>

        //<SnippetTranscodeFileAsync>
        private async Task TranscodeFileAsync()
        {
            transcoder = new MediaTranscoder();

            try
            {
                var settings = ApplicationData.Current.LocalSettings;

                settings.Values["TranscodingStatus"] = "Started";

                var inputFileName  = ApplicationData.Current.LocalSettings.Values["InputFileName"] as string;
                var outputFileName = ApplicationData.Current.LocalSettings.Values["OutputFileName"] as string;

                if (inputFileName == null || outputFileName == null)
                {
                    return;
                }


                // retrieve the transcoding information
                var inputFile = await Windows.Storage.StorageFile.GetFileFromPathAsync(inputFileName);

                var outputFile = await Windows.Storage.StorageFile.GetFileFromPathAsync(outputFileName);

                // create video encoding profile
                MediaEncodingProfile encodingProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.HD720p);

                Debug.WriteLine("PrepareFileTranscodeAsync");
                settings.Values["TranscodingStatus"] = "Preparing to transcode ";
                PrepareTranscodeResult preparedTranscodeResult = await transcoder.PrepareFileTranscodeAsync(
                    inputFile,
                    outputFile,
                    encodingProfile);

                if (preparedTranscodeResult.CanTranscode)
                {
                    var startTime = TimeSpan.FromMilliseconds(DateTime.Now.Millisecond);
                    Debug.WriteLine("Starting transcoding @" + startTime);

                    var progress = new Progress <double>(TranscodeProgress);
                    settings.Values["TranscodingStatus"]  = "Transcoding ";
                    settings.Values["ProcessingFileName"] = inputFileName;
                    await preparedTranscodeResult.TranscodeAsync().AsTask(cancelTokenSource.Token, progress);
                }
                else
                {
                    Debug.WriteLine("Source content could not be transcoded.");
                    Debug.WriteLine("Transcode status: " + preparedTranscodeResult.FailureReason.ToString());
                    var endTime = TimeSpan.FromMilliseconds(DateTime.Now.Millisecond);
                    Debug.WriteLine("End time = " + endTime);
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine("Exception type: {0}", e.ToString());
                throw;
            }
        }
Example #11
0
        public async void PickMedia()
        {
            var openPicker = new Windows.Storage.Pickers.FileOpenPicker();

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

            StorageFile source = await openPicker.PickSingleFileAsync();

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

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

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

            savePicker.FileTypeChoices.Add("MPEG3", new string[] { ".mp3" });

            StorageFile destination = await savePicker.PickSaveFileAsync();

            MediaEncodingProfile profile =
                MediaEncodingProfile.CreateMp3(AudioEncodingQuality.High);

            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;
                }
            }
        }
Example #12
0
        public async Task <IAsyncActionWithProgress <double> > StartTranscodeMedia(StorageFile inputFile, StorageFile outFile, MediaEncodingProfile profile)
        {
            MediaTranscoder        transcoder = new MediaTranscoder();
            PrepareTranscodeResult prepareOp  = await transcoder.PrepareFileTranscodeAsync(inputFile, outFile, profile);

            if (prepareOp.CanTranscode)
            {
                var transcodeOp = prepareOp.TranscodeAsync();

                transcodeOp.Progress += new AsyncActionProgressHandler <double>((asyncInfo, e) =>
                {
                    ProcessingProgressChanged?.Invoke(this, e);
                });
                transcodeOp.Completed += new AsyncActionWithProgressCompletedHandler <double>((asyncInfo, status) =>
                {
                    asyncInfo.GetResults();
                    switch (status)
                    {
                    case AsyncStatus.Canceled:
                        ProcessingCanceled?.Invoke(this, new EventArgs());
                        break;

                    case AsyncStatus.Completed:
                        ProcessingCompleted?.Invoke(this, new EventArgs());
                        break;

                    case AsyncStatus.Started:
                        break;

                    case AsyncStatus.Error:
                    default:
                        ProcessingError?.Invoke(this, "转码失败");
                        break;
                    }
                });
                return(transcodeOp);
            }
            else
            {
                switch (prepareOp.FailureReason)
                {
                case TranscodeFailureReason.CodecNotFound:
                    ProcessingError?.Invoke(this, "转码失败:找不到编解码器");
                    break;

                case TranscodeFailureReason.InvalidProfile:
                    ProcessingError?.Invoke(this, "转码失败:配置文件无效");
                    break;

                default:
                    ProcessingError?.Invoke(this, "转码失败:未知错误");
                    break;
                }
                return(null);
            }
        }
Example #13
0
        public async Task CS_D_MediaStreamSource_EncodeAudio()
        {
            //
            // Create a PCM audio source
            //

            var generator = new AudioSampleGenerator();

            var source = new MediaStreamSource(
                new AudioStreamDescriptor(
                    generator.EncodingProperties
                    )
                );

            source.CanSeek = false;
            source.MusicProperties.Title = "CS_D_MediaStreamSource_EncodeAudio";

            source.SampleRequested += (MediaStreamSource sender, MediaStreamSourceSampleRequestedEventArgs args) =>
            {
                Console.WriteLine("SampleRequested Time: {0}", generator.Time);

                // Generate 5s of data
                if (generator.Time.TotalSeconds < 5)
                {
                    args.Request.Sample = generator.GenerateSample();
                }
            };

            //
            // Open destination M4A file
            //

            var musicFolder = await StorageFolder.GetFolderFromPathAsync(Environment.GetFolderPath(Environment.SpecialFolder.MyMusic));

            var folder = await musicFolder.CreateFolderAsync("MediaCaptureReaderTests", CreationCollisionOption.OpenIfExists);

            var file = await folder.CreateFileAsync("CS_D_MediaStreamSource_EncodeAudio.m4a", CreationCollisionOption.ReplaceExisting);

            Console.WriteLine("Output file: " + file.Path);

            using (var destination = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                //
                // Encode PCM to M4A
                //

                var transcoder = new MediaTranscoder();
                var result     = await transcoder.PrepareMediaStreamSourceTranscodeAsync(
                    source,
                    destination,
                    MediaEncodingProfile.CreateM4a(AudioEncodingQuality.Medium)
                    );

                await result.TranscodeAsync();
            }
        }
        public async Task InitStartTranscoder()
        {
            if (parent != null)
            {
                parent.StartWritingOutput("Initialize Transcoder", 1);
            }


            tempFile = await GetTempOutputFile();

            if (parent != null)
            {
                parent.StartWritingOutputExtended("Temporary Output : " + tempFile.Path, 0);
            }

            IRandomAccessStream destStream = await tempFile.OpenAsync(FileAccessMode.ReadWrite);

            int width  = 320;
            int height = 200;

            if (gcitem != null)
            {
                width  = gcitem.Size.Width;
                height = gcitem.Size.Height;
            }

            frameCounter = 0;
            Timestamp    = TimeSpan.Zero;

            VideoEncodingProperties videoSourceProperties = VideoEncodingProperties.CreateUncompressed(MediaEncodingSubtypes.Rgb32, (uint)width, (uint)height);
            VideoStreamDescriptor   videoSourceDescriptor = new VideoStreamDescriptor(videoSourceProperties);

            MediaStreamSource mediaStreamSource = new MediaStreamSource(videoSourceDescriptor);

            mediaStreamSource.BufferTime       = TimeSpan.FromSeconds(0);
            mediaStreamSource.Starting        += OnMSSStarting;
            mediaStreamSource.SampleRequested += OnMSSSampleRequested;
            mediaStreamSource.SampleRendered  += OnMSSSampleRendered;
            //mediaStreamSource.CanSeek = false;

            MediaTranscoder mediaTranscoder = new MediaTranscoder();

            mediaTranscoder.HardwareAccelerationEnabled = true;

            ////////////////////
            //Start Transcoding
            MediaEncodingProfile   destProfile        = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.HD720p);
            PrepareTranscodeResult transcodeOperation = await mediaTranscoder.PrepareMediaStreamSourceTranscodeAsync(mediaStreamSource, destStream, destProfile);

            //await transcode.TranscodeAsync();
            var rendering = transcodeOperation.TranscodeAsync();

            rendering.Progress  += progressHandler;
            rendering.Completed += completedHandler;
        }
        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();
            }
        }
Example #16
0
        private async Task <APIResponse> GetSong(APIRequest request)
        {
            var song         = MediaDatabase.GetSong(request.Segment);
            var responseData = song.HasValue ? new Dictionary <string, object>()
            {
                { "song", song }
            } : null;

            //handle transcode request
            if (song != null && request.Params != null && request.Params.ContainsKey("transcode"))
            {
                string          sourceFilePath     = MediaDatabase.GetSongPath(request.Segment);
                string          transcodedFilePath = null;
                TranscodeFormat format             = TranscodeFormat.Undefined;;

                if (request.Params.ContainsKey("transcode"))
                {
                    if (Enum.TryParse <TranscodeFormat>(request.Params["transcode"], true, out format))
                    {
                        transcodedFilePath = await MediaTranscoder.GetFromCacheOrTranscodeAsync(request.Segment, sourceFilePath, format);
                    }
                    else
                    {
                        throw new NotSupportedException($"Transcode format \"{request.Params["transcode"]}\" is not recognized!");
                    }
                }

                if (!request.Params.ContainsKey("return") || request.Params["return"] == "path")
                {
                    responseData.Add("transcodedPath", transcodedFilePath);
                }
                else
                {
                    if (request.Params["return"] == "field")
                    {
                        byte[] data = File.ReadAllBytes(transcodedFilePath);
                        responseData.Add("transcodedData", data);
                    }
                    else if (request.Params["return"] == "body")
                    {
                        byte[] data = File.ReadAllBytes(transcodedFilePath);
                        return(new APIResponse(null, (int)HttpStatusCode.OK, format.GetContentType(), data));
                    }
                    else
                    {
                        throw new NotImplementedException();
                    }
                }
            }

            return(new APIResponse(JsonConvert.SerializeObject(new { data = responseData })));
        }
Example #17
0
        async void TranscodePreset(Object sender, RoutedEventArgs e)
        {
            mediaElement.Stop();
            //PickVideo.IsEnabled = false;
            //TransCode.IsEnabled = false;
            MediaTranscoder _Transcoder = new MediaTranscoder();

            GetPresetProfile(ProfileSelect);

            // Clear messages
            StatusMessage.Text = "";

            try
            {
                if (pickedFile != null)
                {
                    //var picker = new Windows.Storage.Pickers.FileSavePicker();
                    //picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.VideosLibrary;
                    //picker.FileTypeChoices.Add("MOV files", new List<string>() { ".mov" });
                    //picker.SuggestedFileName = "TrimmedClip.mov";

                    //StorageFile file = await picker.PickSaveFileAsync();

                    outputFile = await KnownFolders.VideosLibrary.CreateFileAsync(outputFile_name, CreationCollisionOption.GenerateUniqueName);

                    var preparedTranscodeResult = await _Transcoder.PrepareFileTranscodeAsync(pickedFile, outputFile, _Profile);

                    _Transcoder.VideoProcessingAlgorithm = MediaVideoProcessingAlgorithm.Default;

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

                        TranscodeComplete();
                    }
                    else
                    {
                        TranscodeFailure(preparedTranscodeResult.FailureReason);
                    }
                }
            }
            catch (TaskCanceledException)
            {
                OutputText("");
                TranscodeError("Transcode Canceled");
            }
            catch (Exception exception)
            {
                TranscodeError(exception.Message);
            }
        }
        private void AddTranscoderEffect()
        {
            // <SnippetTranscodingAddEffect>
            MediaTranscoder transcoder = new MediaTranscoder();

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

            // <SnippetTranscodingRemoveEffect>
            transcoder.ClearEffects();
            // </SnippetTranscodingRemoveEffect>
        }
Example #19
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>
        }
Example #20
0
        private void CreateMediaObjects()
        {
            var videoProperties = VideoEncodingProperties.CreateUncompressed(MediaEncodingSubtypes.Bgra8, 1920, 1080);

            _videoDescriptor = new VideoStreamDescriptor(videoProperties);

            _mediaStreamSource                  = new MediaStreamSource(_videoDescriptor);
            _mediaStreamSource.BufferTime       = TimeSpan.FromSeconds(0);
            _mediaStreamSource.Starting        += OnMediaStreamSourceStarting;
            _mediaStreamSource.SampleRequested += OnMediaStreamSourceSampleRequested;

            _transcoder = new MediaTranscoder();
            _transcoder.HardwareAccelerationEnabled = IsHardwareAcc;
        }
Example #21
0
        public async void ExtractAudio(string artist, string title, StorageFile videoFile, StorageFile audioFile)
        {
            if (this.transcoder == null)
            {
                this.transcoder      = new MediaTranscoder();
                this.encodingProfile = MediaEncodingProfile.CreateMp3(AudioEncodingQuality.High);
            }

            var preparedTranscodeResult = await this.transcoder.PrepareFileTranscodeAsync(videoFile, audioFile, this.encodingProfile);

            await preparedTranscodeResult.TranscodeAsync();

            await TagStorageFile(artist, title, audioFile);
        }
Example #22
0
        public async Task <Signal> LoadSignalAsync(StorageFile file)
        {
            Stream stream;

            // if user opens WAV-file then we load its contents directly
            if (file.Name.EndsWith("wav", StringComparison.OrdinalIgnoreCase))
            {
                stream = await file.OpenStreamForReadAsync();
            }
            // otherwise transcode to wave
            else
            {
                var transcoder = new MediaTranscoder();
                var profile    = MediaEncodingProfile.CreateWav(AudioEncodingQuality.Medium);

                var temporaryFile = await ApplicationData.Current.TemporaryFolder.TryGetItemAsync(TemporaryWaveFile) as StorageFile;

                if (temporaryFile != null)
                {
                    await temporaryFile.DeleteAsync(StorageDeleteOption.Default);
                }

                temporaryFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(TemporaryWaveFile);

                if (temporaryFile == null)
                {
                    return(null);
                }

                var preparedTranscodeResult = await transcoder.PrepareFileTranscodeAsync(file, temporaryFile, profile);

                if (preparedTranscodeResult.CanTranscode)
                {
                    await preparedTranscodeResult.TranscodeAsync();
                }
                else
                {
                    await new MessageDialog("Error: could not convert to wave!").ShowAsync();
                }

                stream = await temporaryFile.OpenStreamForReadAsync();
            }

            var signal = new Signal();

            await Task.Run(() => signal.Load(stream));

            return(signal);
        }
        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;
                }
            }
        }
Example #24
0
        private async void AcceptButton_Click(object sender, RoutedEventArgs e)
        {
            Pause();

            progressText.Text        = "0";
            progressText.Visibility  = Visibility.Visible;
            completedText.Visibility = Visibility.Collapsed;

            overlayGrid.Visibility = Visibility.Visible;
            OpenProcessingOverlay.Begin();

            Analytics.TrackEvent("VideoEditor_ExportStarted");

            await SaveComposition();

            var transcoder = new MediaTranscoder()
            {
                VideoProcessingAlgorithm = App.RoamingSettings.Read(Constants.VIDEO_PROCESSING, MediaVideoProcessingAlgorithm.Default)
            };
            var props   = await(_model.StorageFile as StorageFile).Properties.GetVideoPropertiesAsync();
            var profile = MediaTranscoding.CreateVideoEncodingProfileFromProps(props);
            var source  = _model.Composition.GenerateMediaStreamSource();

            if (_tempFile == null)
            {
                _tempFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(Path.ChangeExtension(_model.StorageFile.Name, ".mp4"), CreationCollisionOption.GenerateUniqueName);
            }

            if (_tempStream != null)
            {
                _tempStream.Dispose();
            }

            _tempStream = await _tempFile.OpenAsync(FileAccessMode.ReadWrite);

            var result = await transcoder.PrepareMediaStreamSourceTranscodeAsync(source, _tempStream, profile);

            if (!result.CanTranscode)
            {
                await UIUtilities.ShowErrorDialogAsync("Unable to Transcode!", $"Returned {result.FailureReason}");

                return;
            }

            _renderTask            = result.TranscodeAsync();
            _renderTask.Progress   = OnProgress;
            _renderTask.Completed += OnCompleted;
        }
Example #25
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();
        }
        private static async void TranscodeFile(VideoEncodingQuality quality, StorageFile srcFile, StorageFile destFile, Action <StorageFile, ulong> callback, Action <IAsyncActionWithProgress <double> > faultCallback)
        {
            var profile = MediaEncodingProfile.CreateMp4(quality);

            profile.Video.Bitrate      = 750000;
            profile.Audio.ChannelCount = 1;
            profile.Audio.Bitrate      = 62000;
            var transcoder = new MediaTranscoder();

            var prepareOp = await transcoder.PrepareFileTranscodeAsync(srcFile, destFile, profile);

            //message.PrepareTranscodeResult = prepareOp;

            if (prepareOp.CanTranscode)
            {
                var transcodeOp = prepareOp.TranscodeAsync();
                transcodeOp.Progress  += TranscodeProgress;
                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;
                }
            }
        }
Example #27
0
File: Program.cs Project: XCVG/XSMP
        static void Main(string[] args)
        {
            Console.WriteLine($"Starting {ProductNameString}");

            AppDomain.CurrentDomain.ProcessExit        += new EventHandler(HandleExternalExit);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(HandleUnhandledException);

            //portable mode handling
            CheckPortableMode(args);

            SetupFolders();
            LoadUserConfig();

            //port override arg handling
            CheckPortOverride(args);

            MediaDB       mediaDatabase = new MediaDB();
            APIController apiController = new APIController(new APISurface(mediaDatabase));
            RESTServer    restServer    = new RESTServer(apiController);

            IsRunning = true;

            //argument commands handling
            if (args.Contains("-rebuild"))
            {
                mediaDatabase.StartRebuild();
            }

            if (args.Contains("-flushcache"))
            {
                MediaTranscoder.FlushCache();
            }

            while (IsRunning)
            {
                Thread.Sleep(10);
                //TODO poll components?
            }

            Console.WriteLine("Ending XSMP");

            restServer.Dispose();
            mediaDatabase.Dispose();
        }
Example #28
0
        public async Task <StorageFile> ConvertToMP3()
        {
            bool SuccessFlag = true;

            try
            {
                StorageFolder folder = await ApplicationData.Current.TemporaryFolder.CreateFolderAsync("Conversion", CreationCollisionOption.OpenIfExists);

                StorageFile destinationFile = await folder.CreateFileAsync(destination, CreationCollisionOption.GenerateUniqueName);

                if (SuccessFlag)
                {
                    mediatranscoder = new MediaTranscoder();
                    PrepareTranscodeResult transcoderesult = await mediatranscoder.PrepareFileTranscodeAsync(file, destinationFile, isM4A?MediaEncodingProfile.CreateM4a(quality) : MediaEncodingProfile.CreateMp3(quality));

                    if (transcoderesult.CanTranscode)
                    {
                        canceltoken = new CancellationToken();
                        await transcoderesult.TranscodeAsync();

                        SuccessFlag = true;
                    }
                    else
                    {
                        SuccessFlag = false;
                    }
                }

                if (SuccessFlag)
                {
                    return(destinationFile);
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ee)
            {
                Debug.WriteLine(ee.ToString());
            }
            return(null);
        }
Example #29
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();
        }
Example #30
0
        public async Task TranscodeAsync(string sourceFileName, string destinationFileName, uint bitrate, CancellationToken cancellationToken, IProgress <double> progress)
        {
            var transcoder = new MediaTranscoder();
            var sourceFile = await StorageFile.GetFileFromPathAsync(sourceFileName);

            var destinationFolder = await StorageFolder.GetFolderFromPathAsync(Path.GetDirectoryName(destinationFileName));

            var destinationFile = await destinationFolder.CreateFileAsync(Path.GetFileName(destinationFileName));

            var profile = MediaEncodingProfile.CreateMp3(AudioEncodingQuality.High);

            profile.Audio.Bitrate = bitrate;

            var preparedTranscodeResult = await transcoder.PrepareFileTranscodeAsync(sourceFile, destinationFile, profile);

            Exception error = null;

            try
            {
                cancellationToken.ThrowIfCancellationRequested();
                if (preparedTranscodeResult.CanTranscode)
                {
                    await preparedTranscodeResult.TranscodeAsync().AsTask(cancellationToken, progress);
                }
                else
                {
                    throw new InvalidOperationException("Reason: " + preparedTranscodeResult.FailureReason);
                }
            }
            catch (Exception ex)
            {
                error = ex;
            }

            if (error != null)
            {
                await destinationFile.DeleteAsync(StorageDeleteOption.PermanentDelete);

                throw error;
            }
        }