Example #1
0
        private async void addVideoButton_Click(object sender, RoutedEventArgs e)
        {
            StorageFile file;
            IReadOnlyList <StorageFile> files;

            files = await LoadFile("single", ".mp4");

            if (files.Count != 0)
            {
                file = files[0];
                if (file.ContentType == "video/mp4")
                {
                    _videoFile = file;
                    selectedVideoFileTextBlock.Text = _videoFile.DisplayName;
                    _video = await MediaClip.CreateFromFileAsync(_videoFile);

                    SetTimeSliders(_video.OriginalDuration);
                    GenerateButtonEnable();
                    var enc = _video.GetVideoEncodingProperties();
                    Resolutions = new SavingResolutionsCollection(enc);
                    saveResolutionSelector.ItemsSource   = Resolutions;
                    saveResolutionSelector.SelectedIndex = 0;

                    AllowToWatchVideoBeforeGenerating(true);
                }
            }
        }
        public async Task <MediaComposition> TimeBasedReconstruction(Stream aedatFile, CameraParameters cam, EventColor onColor, EventColor offColor, int frameTime, int maxFrames, float playback_frametime)
        {
            byte[]           aedatBytes  = new byte[5 * Convert.ToInt32(Math.Pow(10, 8))];  // Read 0.5 GB at a time
            MediaComposition composition = new MediaComposition();
            int    lastTime = -999999;
            int    timeStamp;
            int    frameCount  = 0;
            Stream pixelStream = InitBitMap(cam);

            byte[] currentFrame = new byte[pixelStream.Length];

            int bytesRead = aedatFile.Read(aedatBytes, 0, aedatBytes.Length);

            while (bytesRead != 0 && frameCount < maxFrames)
            {
                // Read through AEDAT file
                for (int i = 0, length = bytesRead; i < length; i += AedatUtilities.dataEntrySize)                    // iterate through file, 8 bytes at a time.
                {
                    AEDATEvent currentEvent = new AEDATEvent(aedatBytes, i, cam);

                    AedatUtilities.SetPixel(ref currentFrame, currentEvent.x, currentEvent.y, (currentEvent.onOff ? onColor.Color : offColor.Color), cam.cameraX);
                    timeStamp = currentEvent.time;

                    if (lastTime == -999999)
                    {
                        lastTime = timeStamp;
                    }
                    else
                    {
                        if (lastTime + frameTime <= timeStamp)                         // Collected events within specified timeframe, add frame to video
                        {
                            WriteableBitmap b = new WriteableBitmap(cam.cameraX, cam.cameraY);
                            using (Stream stream = b.PixelBuffer.AsStream())
                            {
                                await stream.WriteAsync(currentFrame, 0, currentFrame.Length);
                            }

                            SoftwareBitmap outputBitmap = SoftwareBitmap.CreateCopyFromBuffer(b.PixelBuffer, BitmapPixelFormat.Bgra8, b.PixelWidth, b.PixelHeight, BitmapAlphaMode.Ignore);
                            CanvasBitmap   bitmap2      = CanvasBitmap.CreateFromSoftwareBitmap(CanvasDevice.GetSharedDevice(), outputBitmap);

                            // Set playback framerate
                            MediaClip mediaClip = MediaClip.CreateFromSurface(bitmap2, TimeSpan.FromSeconds(playback_frametime));

                            composition.Clips.Add(mediaClip);
                            frameCount++;

                            // Stop adding frames to video if max frames has been reached
                            if (frameCount >= maxFrames)
                            {
                                break;
                            }
                            currentFrame = new byte[pixelStream.Length];
                            lastTime     = timeStamp;
                        }
                    }
                }
                bytesRead = aedatFile.Read(aedatBytes, 0, aedatBytes.Length);
            }
            return(composition);
        }
Example #3
0
        private async void SelectedVideo_Drop(object sender, DragEventArgs e)
        {
            if (e.DataView.Contains(StandardDataFormats.StorageItems))
            {
                var items = await e.DataView.GetStorageItemsAsync();

                if (items.Count > 0)
                {
                    var file = items[0] as StorageFile;
                    if (file.ContentType == "video/mp4" || file.ContentType == "video/x-matroska")
                    {
                        _videoFile = file;
                        selectedVideoFileTextBlock.Text = _videoFile.DisplayName;
                        _video = await MediaClip.CreateFromFileAsync(_videoFile);

                        SetTimeSliders(_video.OriginalDuration);
                        GenerateButtonEnable();
                        var enc = _video.GetVideoEncodingProperties();
                        Resolutions = new SavingResolutionsCollection(enc);
                        saveResolutionSelector.ItemsSource   = Resolutions;
                        saveResolutionSelector.SelectedIndex = 0;

                        AllowToWatchVideoBeforeGenerating(true);
                    }
                }
            }
            GenerateButtonEnable();
        }
Example #4
0
        private async void specialVideo_Click(object sender, RoutedEventArgs e)
        {
            var picker = new Windows.Storage.Pickers.FileOpenPicker();

            picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.VideosLibrary;
            picker.FileTypeFilter.Add(".mov");
            picker.FileTypeFilter.Add(".mp4");
            StorageFile pickedFilespecial = await picker.PickSingleFileAsync();

            if (pickedFilespecial == null)
            {
                return;
            }
            var clip = await MediaClip.CreateFromFileAsync(pickedFilespecial);

            composition = new MediaComposition();
            composition.Clips.Add(clip);
            var videoEffectDefinition = new VideoEffectDefinition("VideoEffectComponent.ExampleVideoEffect", new PropertySet()
            {
                { "FadeValue", .9 }
            });

            clip.VideoEffectDefinitions.Add(videoEffectDefinition);
            MediaStreamSource mediaStreamSource = composition.GenerateMediaStreamSource();

            mediaElement.SetMediaStreamSource(mediaStreamSource);
        }
Example #5
0
        private void TrimClip_Click(object sender, RoutedEventArgs e)
        {
            // Get the first clip in the MediaComposition
            // We know this beforehand because it's the only clip in the composition
            // that we created from the passed video file
            MediaClip clip = composition.Clips.FirstOrDefault();

            // Trim the end of the clip (you can use TrimTimeFromStart to trim from the beginning)
            clip.TrimTimeFromEnd = TimeSpan.FromMilliseconds((long)EndTrimSlider.Value);

            // Rewind the MediaElement
            EditorMediaElement.Position = TimeSpan.Zero;

            // Update the video source with the trimmed clip
            mediaStreamSource = composition.GeneratePreviewMediaStreamSource((int)EditorMediaElement.ActualWidth, (int)EditorMediaElement.ActualHeight);

            // Set the MediaElement's source
            EditorMediaElement.SetMediaStreamSource(mediaStreamSource);

            // Update the UI
            EndTrimSlider.Value        = 0;
            StatusTextBlock.Text       = "Clip trimmed! Trim again or click Save.";
            StatusTextBlock.Foreground = new SolidColorBrush(Colors.LawnGreen);
            SaveButton.IsEnabled       = true;
        }
        private async Task StartVideoAsync(StorageFile file)
        {
            try
            {
                if (this.videoPlayer.CurrentState == MediaElementState.Playing)
                {
                    this.videoPlayer.Stop();
                }

                FrameRelayVideoEffect.ResetState();

                this.currentVideoId = Guid.NewGuid();
                await this.ResetStateAsync();

                MediaClip clip = await MediaClip.CreateFromFileAsync(file);

                clip.VideoEffectDefinitions.Add(new VideoEffectDefinition(typeof(FrameRelayVideoEffect).FullName));

                MediaComposition compositor = new MediaComposition();
                compositor.Clips.Add(clip);

                this.videoPlayer.SetMediaStreamSource(compositor.GenerateMediaStreamSource());
            }
            catch (Exception ex)
            {
                await Util.GenericApiCallExceptionHandler(ex, "Error starting playback.");
            }
        }
Example #7
0
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            string param = ((string)parameter).ToLower();

            if (value != null && value is MediaClip)
            {
                MediaClip clipVal = value as MediaClip;

                switch (param)
                {
                case "duration":
                    return(clipVal.OriginalDuration.TotalMilliseconds);

                case "start":
                    return(clipVal.TrimTimeFromStart);

                case "end":
                    return(clipVal.TrimTimeFromEnd);

                default:
                    throw new NotImplementedException();
                }
            }
            else
            {
                Debug.WriteLine("Clip not loaded yet. Returning value of 0.");
                return(0);
            }
        }
Example #8
0
        public async void CaptureVideo()
        {
            //<SnippetCaptureVideo>
            CameraCaptureUI captureUI = new CameraCaptureUI();

            captureUI.VideoSettings.Format = CameraCaptureUIVideoFormat.Mp4;

            StorageFile videoFile = await captureUI.CaptureFileAsync(CameraCaptureUIMode.Video);

            if (videoFile == null)
            {
                // User cancelled photo capture
                return;
            }
            //</SnippetCaptureVideo>

            //<SnippetAddToComposition>
            MediaClip mediaClip = await MediaClip.CreateFromFileAsync(videoFile);

            mediaComposition.Clips.Add(mediaClip);
            mediaStreamSource = mediaComposition.GeneratePreviewMediaStreamSource(
                (int)mediaElement.ActualWidth,
                (int)mediaElement.ActualHeight);
            //</SnippetAddToComposition>

            //<SnippetSetMediaElementSource>
            mediaElement.SetMediaStreamSource(mediaStreamSource);
            //</SnippetSetMediaElementSource>
        }
Example #9
0
        /**
         * ソース動画ファイルのサイズにあわせて、EncodingProfileに、いい感じのサイズを設定する(HD720用)
         */
        public static MediaEncodingProfile SetFeelGoodSizeToEncodingProfileForHD720(MediaClip clip, MediaEncodingProfile profile)
        {
            // 動画のサイズ情報取得
            var    prop = clip.GetVideoEncodingProperties();
            double width = prop.Width, height = prop.Height;
            double numerator = prop.PixelAspectRatio.Numerator, denominator = prop.PixelAspectRatio.Denominator;

            // PixelAspectRatio の考慮
            if ((numerator != 1 || denominator != 1) && numerator != 0 && denominator != 0)
            {
                width = width * numerator / denominator;
            }

            // - 短いほうの辺の長さが、720以下となり、かつ、
            // - 長いほうの辺の長さが、1280以下となるように、縮小。(拡大はしない)
            double r;

            if (width > height)
            {
                // 横長
                r = Math.Min(1280.0 / width, 720.0 / height);
            }
            else
            {
                // 縦長
                r = Math.Min(720.0 / width, 1280.0 / height);
            }
            if (r > 1)
            {
                r = 1;  // 拡大はしない
            }
            profile.Video.Width  = (uint)Math.Round(width * r);
            profile.Video.Height = (uint)Math.Round(height * r);
            return(profile);
        }
Example #10
0
        private async void encodeImages_Click(object sender, RoutedEventArgs e)
        {
            FileOpenPicker openPicker = new FileOpenPicker();

            foreach (string extension in FileExtensions.Image)
            {
                openPicker.FileTypeFilter.Add(extension);
            }
            IReadOnlyList <StorageFile> files = await openPicker.PickMultipleFilesAsync();

            composition = new MediaComposition();
            foreach (StorageFile file in files)
            {
                m_files.Add(file);
                var clip = await MediaClip.CreateFromImageFileAsync(file, TimeSpan.FromMilliseconds(1000));

                composition.Clips.Add(clip);
            }

            Debug.WriteLine(composition.Clips.Count);
            //StorageFile fileSave = await openPicker.PickSaveFileAsync();
            //if (file != null)
            //{
            //    var saveOperation = composition.RenderToFileAsync(file, MediaTrimmingPreference.Precise);
            //    await composition.RenderToFileAsync("C://Mike");
            //}
        }
Example #11
0
        /**
         * ターゲットの動画ファイルをセットする
         */
        public async void SetSource(StorageFile source)
        {
            Reset();

            if (null == source)
            {
                return;
            }
            mPlayer.SetSource(source);


            try
            {
                mClip = await MediaClip.CreateFromFileAsync(source);

                mTrimmingSlider.TotalRange = mClip.OriginalDuration.TotalMilliseconds;
                await mExtractor.ExtractAsync(mClip, (s, i, img) =>
                {
                    mFrameListView.Frames[i] = img;
                },
                                              (s, img) =>
                {
                    mFrameListView.FrameListHeight = mExtractor.ThumbnailHeight;
                    for (int i = 0; i < mExtractor.FrameCount; i++)
                    {
                        mFrameListView.Frames.Add(img);
                    }
                });
            }
            catch (Exception e)
            {
                CmLog.error("WvvFrameSelectorView.SetSource", e);
                Error.SetError(e);
            }
        }
Example #12
0
        /// <summary>
        /// Handle the returned files from file picker
        /// This method is triggered by ContinuationManager based on ActivationKind
        /// </summary>
        /// <param name="args">File open picker continuation activation argment. It cantains the list of files user selected with file open picker </param>
        public async void ContinueFileOpenPicker(FileOpenPickerContinuationEventArgs args)
        {
            if (args.Files.Count > 0)
            {
                Debug.WriteLine("Picked video: " + args.Files[0].Name);
                MediaLoaded = true;

                m_clip = await MediaClip.CreateFromFileAsync(args.Files[0]);
                m_composition = new MediaComposition();
                m_composition.Clips.Add(m_clip);

                // Update the sliders to represent the duration in milliseconds
                // TODO: move this databinding
                TrimStart.Maximum = m_clip.OriginalDuration.TotalMilliseconds;
                TrimEnd.Maximum = m_clip.OriginalDuration.TotalMilliseconds;
                TrimEnd.Value = TrimEnd.Maximum;

                //// Set up the MediaElement for preview
                // TODO: pass in the preview streamsource and grab the screensize to determine this in addition to the aspect ratio of the video
                MediaElement.SetMediaStreamSource(m_composition.GenerateMediaStreamSource());
            }
            else
            {
                Debug.WriteLine("Operation cancelled.");
            }
        }
Example #13
0
        private static async Task <MediaClip> AddClipAsync(StorageFile pickedFile, PanelElement element)
        {
            MediaClip clip;

            if (element.FileType == FileType.Picture)
            {
                using (StorageItemThumbnail thumbnail = await pickedFile.GetThumbnailAsync(ThumbnailMode.PicturesView))
                {
                    if (thumbnail != null)
                    {
                        BitmapImage bitmapImage = new BitmapImage();
                        bitmapImage.SetSource(thumbnail);

                        element.Thumbnail = bitmapImage;
                    }
                }
                clip = await MediaClip.CreateFromImageFileAsync(pickedFile, TimeSpan.FromSeconds(5));
            }
            else
            {
                using (StorageItemThumbnail thumbnail = await pickedFile.GetThumbnailAsync(ThumbnailMode.VideosView))
                {
                    if (thumbnail != null)
                    {
                        BitmapImage bitmapImage = new BitmapImage();
                        bitmapImage.SetSource(thumbnail);

                        element.Thumbnail = bitmapImage;
                    }
                }
                clip = await MediaClip.CreateFromFileAsync(pickedFile);
            }

            return(clip);
        }
Example #14
0
        private async void AddPicturesButton_Tapped(object sender, TappedRoutedEventArgs e)
        {
            FileOpenPicker filePicker = new FileOpenPicker {
                SuggestedStartLocation = PickerLocationId.PicturesLibrary
            };

            filePicker.FileTypeFilter.Add(".jpg");
            filePicker.FileTypeFilter.Add(".jpeg");
            filePicker.FileTypeFilter.Add(".png");
            filePicker.FileTypeFilter.Add(".bmp");
            filePicker.FileTypeFilter.Add(".gif");
            filePicker.FileTypeFilter.Add(".tiff");
            filePicker.ViewMode = PickerViewMode.Thumbnail;
            StorageFile file = await filePicker.PickSingleFileAsync();

            if (file != null)
            {
                try
                {
                    StorageItemAccessList storageItemAccessList = StorageApplicationPermissions.FutureAccessList;
                    storageItemAccessList.Add(file);


                    //新建媒体
                    Media media = new Media();

                    //缩略图
                    using (StorageItemThumbnail thumbnail = await file.GetThumbnailAsync(ThumbnailMode.PicturesView))
                    {
                        if (thumbnail != null)
                        {
                            BitmapImage bitmapImage = new BitmapImage();
                            bitmapImage.SetSource(thumbnail);

                            media.Bitmap = bitmapImage;
                        }
                    }

                    //从文件创建媒体剪辑
                    MediaClip clip = await MediaClip.CreateFromImageFileAsync(file, new TimeSpan(24, 1, 0));

                    clip.TrimTimeFromEnd = clip.TrimTimeFromStart = new TimeSpan(12, 0, 0);
                    media.Clip           = clip;

                    //从颜色创建名称
                    media.Name = file.Name;

                    MediaClipList.Add(media);
                    SplitShowMethod();// SplitView:侧栏
                }
                catch (Exception)
                {
                    App.Tip("file err");
                }
            }
            else
            {
                App.Tip("file null");
            }
        }
Example #15
0
        private async Task SetComp(StorageFile backgroundAudio, Dictionary <StorageFile, TimeSpan> imageFiles, CancellationToken cancellationToken)
        {
            StorageFile temporaryFile = await CreateFile("Media Composition", "temp (1)", "cmp", cancellationToken);

            BackgroundAudioTrack backgroundAudioTrack = await BackgroundAudioTrack.CreateFromFileAsync(backgroundAudio);

            AudioEncodingProperties audioEncodingProperties = backgroundAudioTrack.GetAudioEncodingProperties();
            TimeSpan         duration    = backgroundAudioTrack.OriginalDuration;
            MediaComposition composition = new MediaComposition();

            composition.BackgroundAudioTracks.Add(backgroundAudioTrack);

            CancelTask(cancellationToken);

            MediaClip clip;

            foreach (var item in imageFiles)
            {
                CancelTask(cancellationToken);
                clip = await MediaClip.CreateFromImageFileAsync(item.Key, item.Value);

                composition.Clips.Add(clip);
            }
            composition.CreateDefaultEncodingProfile();
            await composition.SaveAsync(temporaryFile);

            ReportProgress(Stage5, Stage4ProgressBar, TextProgress4, 100);

            CancelTask(cancellationToken);
        }
        private async void AddAudio_Click(object sender, RoutedEventArgs e)
        {
            // Create the original MediaComposition
            var clip = await MediaClip.CreateFromFileAsync(pickedFile);

            composition = new MediaComposition();
            composition.Clips.Add(clip);

            // Add background audio
            var picker = new Windows.Storage.Pickers.FileOpenPicker();

            picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.MusicLibrary;
            picker.FileTypeFilter.Add(".mp3");
            picker.FileTypeFilter.Add(".wav");
            picker.FileTypeFilter.Add(".flac");
            var audioFile = await picker.PickSingleFileAsync();

            if (audioFile == null)
            {
                rootPage.NotifyUser("File picking cancelled", NotifyType.ErrorMessage);
                return;
            }

            var backgroundTrack = await BackgroundAudioTrack.CreateFromFileAsync(audioFile);

            composition.BackgroundAudioTracks.Add(backgroundTrack);

            // Render to MediaElement
            mediaElement.Position = TimeSpan.Zero;
            mediaStreamSource     = composition.GeneratePreviewMediaStreamSource((int)mediaElement.ActualWidth, (int)mediaElement.ActualHeight);
            mediaElement.SetMediaStreamSource(mediaStreamSource);

            rootPage.NotifyUser("Background audio added", NotifyType.StatusMessage);
        }
Example #17
0
        private async void Select_OnClick(object sender, RoutedEventArgs e)
        {
            var picker = new FileOpenPicker {
                SuggestedStartLocation = PickerLocationId.Desktop
            };

            picker.FileTypeFilter.Add(".mp4");

            var pickedFiles = await picker.PickMultipleFilesAsync();

            if (pickedFiles == null)
            {
                return;
            }

            TextBlock.Text = $"Importing {pickedFiles.Count} files";

            composition = new MediaComposition();
            var files = pickedFiles.OrderBy(x => x.Name).ToArray();

            foreach (var file in files)
            {
                var clip = await MediaClip.CreateFromFileAsync(file);

                composition.Clips.Add(clip);
                TextBlock.Text = $"Importing {Path.GetFileName(file.Path)}";
            }

            TextBlock.Text = $"All files are imported";
        }
Example #18
0
        public static async Task <ImageSource> GetPreviewBitmapAsync(StorageFile sourceFile, int requestedMinSide = 1280)
        {
            try
            {
                if (sourceFile.ContentType.Equals("video/mp4"))
                {
                    var props = await sourceFile.Properties.GetVideoPropertiesAsync();

                    var composition = new MediaComposition();
                    var clip        = await MediaClip.CreateFromFileAsync(sourceFile);

                    composition.Clips.Add(clip);

                    using (var imageStream = await composition.GetThumbnailAsync(TimeSpan.Zero, (int)props.GetWidth(), (int)props.GetHeight(), VideoFramePrecision.NearestKeyFrame))
                    {
                        return(await GetPreviewBitmapAsync(imageStream, requestedMinSide));
                    }
                }

                using (var imageStream = await sourceFile.OpenReadAsync())
                {
                    return(await GetPreviewBitmapAsync(imageStream, requestedMinSide));
                }
            }
            catch
            {
                return(null);
            }
        }
Example #19
0
        private async void VideoEditDialog_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                Composition = new MediaComposition();
                VideoClip   = await MediaClip.CreateFromFileAsync(VideoFile);

                Composition.Clips.Add(VideoClip);

                PreviewSource    = MediaSource.CreateFromMediaStreamSource(Composition.GeneratePreviewMediaStreamSource(640, 360));
                MediaPlay.Source = PreviewSource;

                CutRange.Maximum  = VideoClip.OriginalDuration.TotalMilliseconds;
                CutRange.RangeMax = CutRange.Maximum;
            }
            catch
            {
                Hide();

                QueueContentDialog dialog = new QueueContentDialog
                {
                    Title           = Globalization.GetString("Common_Dialog_ErrorTitle"),
                    Content         = Globalization.GetString("QueueDialog_EditErrorWhenOpen_Content"),
                    CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton")
                };

                _ = await dialog.ShowAsync().ConfigureAwait(false);
            }
        }
        private async void CreateOverlays()
        {
            var baseVideoClip = await MediaClip.CreateFromFileAsync(baseVideoFile);

            composition = new MediaComposition();
            composition.Clips.Add(baseVideoClip);

            var overlayVideoClip = await MediaClip.CreateFromFileAsync(overlayVideoFile);

            // Overlay video in upper left corner, retain its native aspect ratio
            Rect videoOverlayPosition;
            var  encodingProperties = overlayVideoClip.GetVideoEncodingProperties();

            videoOverlayPosition.Height = mediaElement.ActualHeight / 3;
            videoOverlayPosition.Width  = (double)encodingProperties.Width / (double)encodingProperties.Height * videoOverlayPosition.Height;
            videoOverlayPosition.X      = 0;
            videoOverlayPosition.Y      = 0;

            var videoOverlay = new MediaOverlay(overlayVideoClip);

            videoOverlay.Position = videoOverlayPosition;
            videoOverlay.Opacity  = 0.75;

            var overlayLayer = new MediaOverlayLayer();

            overlayLayer.Overlays.Add(videoOverlay);
            composition.OverlayLayers.Add(overlayLayer);

            // Render to MediaElement
            mediaElement.Position = TimeSpan.Zero;
            mediaStreamSource     = composition.GeneratePreviewMediaStreamSource((int)mediaElement.ActualWidth, (int)mediaElement.ActualHeight);
            mediaElement.SetMediaStreamSource(mediaStreamSource);
            rootPage.NotifyUser("Overlays created", NotifyType.StatusMessage);
        }
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            var videoFile = e.Parameter as StorageFile;

            if (videoFile != null)
            {
                StatusTextBlock.Text = videoFile.DisplayName;

                // Create a MediaClip from the file
                var clip = await MediaClip.CreateFromFileAsync(videoFile);

                // Set the End Trim slider's maximum value so that the user can trim from the end
                // You can also do this from the start
                EndTrimSlider.Maximum = clip.OriginalDuration.TotalMilliseconds;

                // Create a MediaComposition containing the clip and set it on the MediaElement.
                composition = new MediaComposition();
                composition.Clips.Add(clip);

                // start the MediaElement at the beginning
                EditorMediaElement.Position = TimeSpan.Zero;

                // Create the media source and assign it to the media player
                mediaStreamSource = composition.GeneratePreviewMediaStreamSource((int)EditorMediaElement.ActualWidth, (int)EditorMediaElement.ActualHeight);

                // Set the MediaElement's source
                EditorMediaElement.SetMediaStreamSource(mediaStreamSource);

                TrimClipButton.IsEnabled = true;
            }
        }
Example #22
0
 public MediaRendition(
     MediaClip clip
     )
     : base(clip.Document, PdfName.MR)
 {
     Clip = clip;
 }
        async Task <MediaStreamSource> OpenVideo()
        {
            this.progressText.Text = "Downloading video...";

            var thumbnailFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Logo.scale-100.png"));

            var thumbnail = RandomAccessStreamReference.CreateFromFile(thumbnailFile);

            var url = "http://video.ch9.ms/ch9/4597/8db5a656-b173-4897-b2aa-e2075fb24597/windows10recap.mp4";

            var file = await StorageFile.CreateStreamedFileFromUriAsync(
                "windows10recap.mp4",
                new Uri(url),
                thumbnail);

            this.progressText.Text = "Creating clip...";
            var clip = await MediaClip.CreateFromFileAsync(file);

            clip.VideoEffectDefinitions.Add(new VideoEffectDefinition(typeof(ExampleVideoEffect).FullName));

            var composition = new MediaComposition();

            composition.Clips.Add(clip);

            if (ThumbnailGenerator.IsDrawingThumbnail)
            {
                customThumbnail = await composition.GetThumbnailAsync(TimeSpan.FromSeconds(10), 1280, 720, VideoFramePrecision.NearestFrame);
            }

            return(composition.GenerateMediaStreamSource());
        }
Example #24
0
        /// <summary>
        /// TODO: need to dispose CanvasRenderTarget.
        /// </summary>
        /// <param name="canvasDevice"></param>
        /// <param name="canvasBitmap"></param>
        private void CreateClipInMemory(CanvasDevice canvasDevice, CanvasBitmap canvasBitmap)
        {
            CanvasRenderTarget rendertarget = null;

            QueryPerformanceCounter(out long counter);
            var currentTime = TimeSpan.FromMilliseconds(1000f * counter / performanceFrequency);

            try
            {
                rendertarget = new CanvasRenderTarget(canvasDevice, canvasBitmap.SizeInPixels.Width, canvasBitmap.SizeInPixels.Height, canvasBitmap.Dpi, canvasBitmap.Format, canvasBitmap.AlphaMode);
                using (CanvasDrawingSession ds = rendertarget.CreateDrawingSession())
                {
                    ds.Clear(Colors.Transparent);
                    ds.DrawImage(canvasBitmap);
                }
                mediaComposition.Clips.Add(MediaClip.CreateFromSurface(rendertarget, currentTime - _timeSpan));
            }
            catch
            {
            }
            finally
            {
                _timeSpan = currentTime;
            }
        }
        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 #26
0
        private async void  Button_Click(object sender, RoutedEventArgs e)
        {
            var picker = new Windows.Storage.Pickers.FileOpenPicker();

            picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.VideosLibrary;
            picker.FileTypeFilter.Add(".mp4");
            pickedFile = await picker.PickSingleFileAsync();

            var storageItemAccessList = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList;

            storageItemAccessList.Add(pickedFile);

            var clip = await MediaClip.CreateFromFileAsync(pickedFile);

            if (pickedFile == null)
            {
                return;
            }


            else
            {
                composition = new MediaComposition();
                composition.Clips.Add(clip);
                mediaElement1.Position = TimeSpan.Zero;
                mediaStreamSource      = composition.GeneratePreviewMediaStreamSource(500, 200);
                mediaElement1.SetMediaStreamSource(mediaStreamSource);
                import_btn.IsEnabled = false;
            }
        }
Example #27
0
        public void AddClip(MediaClip clip)
        {
            var          aspect  = clip.GetVideoEncodingProperties().PixelAspectRatio;
            MediaOverlay overlay = new MediaOverlay(clip, new Windows.Foundation.Rect(20, 20, 400, 400), 1);

            mediaOverlayLayer.Overlays.Add(overlay);
            AddMediaClip?.Invoke(this);
        }
Example #28
0
        public async Task SetupMediaComposition(MediaComposition mediaComposition)
        {
            var captureVideoFile = await StorageFile.GetFileFromPathAsync(_captureVideoFilePath);

            var clip = await MediaClip.CreateFromFileAsync(captureVideoFile);

            mediaComposition.Clips.Add(clip);
        }
Example #29
0
        private VideoTrimmer(MediaClip clip)
        {
            this.clip = clip;

            // Create a composition with the clip
            this.composition = new MediaComposition();
            composition.Clips.Add(clip);
        }
Example #30
0
        private async Task <Dictionary <TimeSpan, Face[]> > DetectFace_Video(StorageFile fileData)
        {
            // Process configs
            const int frameJumpSize = 15;
            const int frameQuota    = 20;
            const int frameTimeout  = 60_000;

            // Video
            var videoProperties = await fileData.Properties.GetVideoPropertiesAsync();

            var videoTime  = TimeSpan.FromSeconds(0);
            var videoFrame = 0;

            // DetectedFaces
            var detectedFaces = new Dictionary <TimeSpan, Face[]>();

            // Process every frame
            while (videoTime < videoProperties.Duration)
            {
                // Frame cut
                var mediaClip = await MediaClip.CreateFromFileAsync(fileData);

                var mediaComposition = new MediaComposition();
                mediaComposition.Clips.Add(mediaClip);
                var frame = await mediaComposition.GetThumbnailAsync(
                    videoTime,
                    0,
                    0,
                    VideoFramePrecision.NearestFrame
                    );

                // Stream conversion
                var randomAccessStream = new InMemoryRandomAccessStream();
                await RandomAccessStream.CopyAsync(frame, randomAccessStream);

                randomAccessStream.Seek(0);

                // Process and add image
                var detectedFace = await DetectFace_Image(randomAccessStream.AsStreamForRead());

                if (detectedFace != null)
                {
                    detectedFaces.Add(videoTime, detectedFace);
                }

                // Quota overflow
                if (videoFrame != 0 && videoFrame % frameQuota == 0)
                {
                    await Task.Delay(frameTimeout);
                }

                // Frame and time incrementation
                videoTime  += TimeSpan.FromSeconds(frameJumpSize);
                videoFrame += 1;
            }

            return(detectedFaces);
        }
        public void Invoke_GetMediaClip_Returns_Result()
        {
            IsDependentOn("Invoke_CreateMediaClip_Returns_Result");

            MediaClip mediaClip = null;

            Assert.That(() => mediaClip = _podigee.GetMediaClip(_mediaClip.Id), Throws.Nothing);
            CompareMediaClip(mediaClip, _mediaClip);
        }
Example #32
0
 public async Task <BitmapImage> ExtractSingleFrameAsync(MediaClip clip, TimeSpan position)
 {
     using (var imageStream = await ExtractSingleFrameStreamAsync(clip, position))
     {
         var bmp = new BitmapImage();
         bmp.SetSource(imageStream);
         return(bmp);
     }
 }
Example #33
0
        public Task <DataItem> GetData()
        {
            // Use this to create design time data

            DataItem item = new DataItem("Welcome to MVVM Light [design testing]");

            item.Clip = MediaClip.CreateFromColor(Color.FromArgb(byte.MaxValue, byte.MinValue, byte.MaxValue, byte.MinValue), TimeSpan.FromSeconds(5));
            return(Task.FromResult(item));
        }