private async void PropertyDialog_Loading(FrameworkElement sender, object args)
        {
            if (Item.StorageType == StorageItemTypes.File)
            {
                IncludeArea.Visibility = Visibility.Collapsed;

                FileName   = Item.Name;
                Path       = Item.Path;
                FileType   = $"{Item.DisplayType} ({Item.Type})";
                CreateTime = Item.CreationTimeRaw.ToString("F");
                ChangeTime = Item.ModifiedTimeRaw.ToString("F");
                FileSize   = Item.Size + " (" + Item.SizeRaw.ToString("N0") + $" {Globalization.GetString("Device_Capacity_Unit")})";

                if (Item is HyperlinkStorageItem LinkItem)
                {
                    LinkTargetArea.Visibility = Visibility.Visible;
                    ExtraDataArea.Visibility  = Visibility.Collapsed;

                    TargetPath = LinkItem.LinkTargetPath;
                }
                else
                {
                    if (await Item.GetStorageItem().ConfigureAwait(true) is StorageFile File)
                    {
                        if (File.ContentType.StartsWith("video", StringComparison.OrdinalIgnoreCase))
                        {
                            VideoProperties Video = await File.Properties.GetVideoPropertiesAsync();

                            ExtraData.Text = $"{Globalization.GetString("FileProperty_Resolution")}: {((Video.Width == 0 && Video.Height == 0) ? Globalization.GetString("UnknownText") : $"{Video.Width}×{Video.Height}")}{Environment.NewLine}{Globalization.GetString("FileProperty_Bitrate")}: {(Video.Bitrate == 0 ? Globalization.GetString("UnknownText") : (Video.Bitrate / 1024f < 1024 ? Math.Round(Video.Bitrate / 1024f, 2).ToString("0.00") + " Kbps" : Math.Round(Video.Bitrate / 1048576f, 2).ToString("0.00") + " Mbps"))}{Environment.NewLine}{Globalization.GetString("FileProperty_Duration")}: {ConvertTimsSpanToString(Video.Duration)}";
Exemplo n.º 2
0
        public void Dispose()
        {
            EventsHelper.CanRaiseEvent = false;

            CompositionTarget.Rendering -= CompositionTargetRendering;

            Dispatcher.BeginInvoke(
                new Action(
                    delegate
            {
                FreeEvents();
                if (IsPlaying)
                {
                    Stop();
                }
                AudioProperties.Dispose();
                VideoProperties.Dispose();
                LogProperties.Dispose();
                AudioOutputDevices.Dispose();
                VlcContext.InteropManager.MediaPlayerInterops.ReleaseInstance.Invoke(VlcContext.HandleManager.MediaPlayerHandles[this]);
                VlcContext.HandleManager.MediaPlayerHandles.Remove(this);

                myVideoLockCallbackHandle.Free();
                myVideoSetFormatHandle.Free();
                myVideoCleanupHandle.Free();
            }));
        }
Exemplo n.º 3
0
        private async void media_MediaOpened_1(object sender, RoutedEventArgs e)
        {
            try
            {
                endposition.Text = ((media.NaturalDuration.TimeSpan.Hours < 10) ? ("0" + media.NaturalDuration.TimeSpan.Hours.ToString()) : media.NaturalDuration.TimeSpan.Hours.ToString()) + ":" + ((media.NaturalDuration.TimeSpan.Minutes < 10) ? ("0" + media.NaturalDuration.TimeSpan.Minutes.ToString()) : (media.NaturalDuration.TimeSpan.Minutes.ToString())) + ":" + ((media.NaturalDuration.TimeSpan.Seconds < 10) ? ("0" + media.NaturalDuration.TimeSpan.Seconds.ToString()) : (media.NaturalDuration.TimeSpan.Seconds.ToString()));
                vproperties      = await sfile.Properties.GetVideoPropertiesAsync();

                if (FirstInstanceProperty.VideoPlayer.count == 0 && !Constants.isvideofileactivated)
                {
                    InitializeHandles();
                }
                MediaControl.AlbumArt   = new Uri("ms-appx:///Assets/video.jpg");
                MediaControl.ArtistName = vproperties.Publisher.ToString();
                setuptimer();
                seekbar.Maximum            = Math.Round(media.NaturalDuration.TimeSpan.TotalSeconds, MidpointRounding.AwayFromZero);
                seekbar.StepFrequency      = CalculateStepFrequency(media.NaturalDuration.TimeSpan);
                PlayPause.IsEnabled        = true;
                PlayPause.Visibility       = Visibility.Collapsed;
                Mute.Visibility            = Visibility.Visible;
                seekbar.IsEnabled          = true;
                togglefullscreen.IsEnabled = true;;
                keyshortcuts.Text          = name;
                MediaControl.IsPlaying     = isplaying;
                MediaControl.TrackName     = sfile.DisplayName;
                loading.IsActive           = false;
            }
            catch (Exception ex)
            {
                NotifyUser(ex);
            }
        }
Exemplo n.º 4
0
        private async void PropertyDialog_Loading(FrameworkElement sender, object args)
        {
            if (SItem is StorageFile || Item?.StorageType == StorageItemTypes.File)
            {
                IncludeArea.Visibility = Visibility.Collapsed;

                StorageFile file;

                if (Item != null)
                {
                    FileName = Item.Name;
                    Path     = Item.Path;
                    FileType = $"{Item.DisplayType} ({Item.Type})";

                    file = (StorageFile)await Item.GetStorageItem().ConfigureAwait(true);

                    if (Item is HyperlinkStorageItem LinkItem)
                    {
                        LinkTargetArea.Visibility = Visibility.Visible;
                        TargetPath = LinkItem.TargetPath;
                    }
                }
                else
                {
                    file     = (StorageFile)SItem;
                    FileType = $"{file.DisplayType} ({file.FileType})";
                }

                CreateTime = file.DateCreated.ToString("F");

                if (file.ContentType.StartsWith("video"))
                {
                    VideoProperties Video = await file.Properties.GetVideoPropertiesAsync();

                    ExtraData.Text = $"{Globalization.GetString("FileProperty_Resolution")}: {((Video.Width == 0 && Video.Height == 0) ? "Unknown" : $"{Video.Width}×{Video.Height}")}{Environment.NewLine}{Globalization.GetString("FileProperty_Bitrate")}: {(Video.Bitrate == 0 ? "Unknown" : (Video.Bitrate / 1024f < 1024 ? Math.Round(Video.Bitrate / 1024f, 2).ToString("0.00") + " Kbps" : Math.Round(Video.Bitrate / 1048576f, 2).ToString("0.00") + " Mbps"))}{Environment.NewLine}{Globalization.GetString("FileProperty_Duration")}: {ConvertTimsSpanToString(Video.Duration)}";
Exemplo n.º 5
0
        private async Task <Dictionary <string, string> > GetProperties(StorageFile temporaryFile, CancellationToken cancellationToken)
        {
            StorageItemContentProperties properties = temporaryFile.Properties;
            MusicProperties musicProperties         = await properties.GetMusicPropertiesAsync();

            VideoProperties videoProperties = await properties.GetVideoPropertiesAsync();

            BasicProperties basicProperties = await temporaryFile.GetBasicPropertiesAsync();

            CancelTask(cancellationToken);

            Dictionary <string, string> tempDictionary = new Dictionary <string, string>();

            tempDictionary["Display Name"]        = temporaryFile.DisplayName;
            tempDictionary["File Type"]           = temporaryFile.FileType;
            tempDictionary["Current Folder Path"] = temporaryFile.FolderRelativeId;
            tempDictionary["Size"]           = string.Format("{0:0.00}", (Convert.ToDouble(basicProperties.Size) / 1048576d)) + " Mb";
            tempDictionary["Creation Date"]  = temporaryFile.DateCreated.ToString();
            tempDictionary["Modified Date"]  = basicProperties.DateModified.ToString();
            tempDictionary["Audio Bit Rate"] = musicProperties.Bitrate + " bps";
            tempDictionary["Length"]         = videoProperties.Duration.ToString("hh\\:mm\\:ss");
            tempDictionary["Frame Width"]    = videoProperties.Width + "";
            tempDictionary["Frame Height"]   = videoProperties.Height + "";
            tempDictionary["Orientation"]    = videoProperties.Orientation + "";
            tempDictionary["Total Bit Rate"] = videoProperties.Bitrate + " bps";

            CancelTask(cancellationToken);

            return(tempDictionary);
        }
Exemplo n.º 6
0
        async private void AddItemsToListView(StorageFile file)
        {
            listContent listItem = new listContent();

            listItem.name = file.Name;
            VideoProperties properties = await file.Properties.GetVideoPropertiesAsync();

            if (properties.Duration.ToString().Split(".") != null)
            {
                string[] trimTimeSpan = properties.Duration.ToString().Split(".");
                listItem.duration = trimTimeSpan[0];
                Debug.WriteLine("Trimmed : " + trimTimeSpan[0]);
            }
            else
            {
                listItem.duration = properties.Duration.ToString();
                Debug.WriteLine("Not: " + listItem.duration);
            }
            playlist.Items.Add(listItem);
            // files.Items.Add(file.Name);
            if (!fileData.ContainsKey(file.Name))
            {
                fileData.Add(file.Name, file);
            }
        }
        private async Task displayvideos(ObservableCollection <StorageFile> dispvideo)
        {
            foreach (var file in dispvideo)
            {
                VideoProperties property = await file.Properties.GetVideoPropertiesAsync();

                StorageItemThumbnail thumbb = await file.GetThumbnailAsync(ThumbnailMode.VideosView, 230, ThumbnailOptions.ResizeThumbnail);

                var videoname  = file.Name;
                var coverimage = new BitmapImage();
                coverimage.SetSource(thumbb);
                var conuttt = dispvideo.Count();

                var video = new Videoprop();
                totalvideono.Text = string.Format("Total Videos: {0}", conuttt);
                video.ID          = id;
                video.videoname   = videoname;
                video.videotitle  = property.Title;
                video.videoartist = property.Subtitle;
                video.videoalbum  = property.Publisher;
                video.albumcover  = coverimage;
                video.videofile   = file;
                Videos.Add(video);
                id++;
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Set up the needed properties. In this case, the duration.
        /// </summary>
        private async Task <NBVideo> SetupPropertiesAsync()
        {
            StorageFile file = await StorageFile.GetFileFromPathAsync(path);

            VideoProperties properties = await file.Properties.GetVideoPropertiesAsync();

            Duration = properties.Duration;
            return(this);
        }
Exemplo n.º 9
0
 public LocalVideo(VideoProperties videoProps)
 {
     Title = CleanText(videoProps.Title);
     if (!string.IsNullOrEmpty(videoProps.Publisher))
     {
         Author = CleanText(videoProps.Publisher);
     }
     Duration = videoProps.Duration;
 }
Exemplo n.º 10
0
        public async static Task <string> GetVideoDuration(StorageFile file)
        {
            VideoProperties properties = await file.Properties.GetVideoPropertiesAsync();

            if (properties != null)
            {
                string[] trimTimeSpan = properties.Duration.ToString().Split(".");
                return(trimTimeSpan[0]);
            }

            return("0");
        }
Exemplo n.º 11
0
        private async void BrowseBtn_Click(object sender, RoutedEventArgs e)
        {
            FolderPicker pk = new FolderPicker();

            pk.FileTypeFilter.Add("*");
            var vfolder = await pk.PickSingleFolderAsync();

            if (vfolder != null)
            {
                folder = vfolder;
            }

            if (folder != null)
            {
                IReadOnlyList <StorageFile> files = await folder.GetFilesAsync();

                Images.Clear();
                int n   = 0;
                int cnt = files.Count();
                foreach (StorageFile fp in files)
                {
                    ImageItem img = new ImageItem();
                    if (fp.Path.EndsWith(".jpg") || fp.Path.EndsWith(".jpeg") || fp.Path.EndsWith(".JPG") || fp.Path.EndsWith(".JPEG"))
                    {
                        img.path = fp;
                        img.thmb = new BitmapImage();
                        ImageProperties imageProperties = await fp.Properties.GetImagePropertiesAsync();

                        img.timeTaken = imageProperties.DateTaken;
                        img.thmb.SetSource(await fp.GetThumbnailAsync(ThumbnailMode.PicturesView));
                        img.IsVideo = false;
                        img.get_blurriness();
                        Images.Add(img);
                    }
                    if (fp.Path.EndsWith(".mp4") || fp.Path.EndsWith(".m4v") || fp.Path.EndsWith(".avi") || fp.Path.EndsWith(".MP4") || fp.Path.EndsWith(".M4V") || fp.Path.EndsWith(".AVI"))
                    {
                        img.path = fp;
                        img.thmb = new BitmapImage();
                        VideoProperties videoProperties = await fp.Properties.GetVideoPropertiesAsync();

                        img.Duration = videoProperties.Duration;
                        img.thmb.SetSource(await fp.GetThumbnailAsync(ThumbnailMode.VideosView));
                        img.IsVideo = true;
                        //img.get_blurriness();
                        Images.Add(img);
                    }
                    n++;
                    PGBar.Value = 100 * n / cnt;
                }
                PGBar.Value = 0;
            }
        }
Exemplo n.º 12
0
 protected void Dispose(bool disposing)
 {
     if (disposing)
     {
         AudioProperties.Dispose();
         VideoProperties.Dispose();
         LogProperties.Dispose();
         AudioOutputDevices.Dispose();
         FreeEvents();
         VlcContext.InteropManager.MediaPlayerInterops.ReleaseInstance.Invoke(VlcContext.HandleManager.MediaPlayerHandles[this]);
         VlcContext.HandleManager.MediaPlayerHandles.Remove(this);
     }
 }
        public async void GetAllImagesAsync()
        {
            ImageList.Clear();
            VideoImageList.Clear();
            var folder   = Windows.Storage.ApplicationData.Current.LocalFolder;
            var allFiles = await folder.GetFilesAsync();

            foreach (var file in allFiles)
            {
                if (file.FileType.Equals(".jpg") || file.FileType.Equals(".png") || file.FileType.Equals(".jpeg"))
                {
                    ImageProperties imageProperties = await file.Properties.GetImagePropertiesAsync();

                    StorageItemThumbnail storageItemThumbnail = await file.GetThumbnailAsync(ThumbnailMode.PicturesView, 200, ThumbnailOptions.UseCurrentScale);

                    var Picture = new BitmapImage();
                    Picture.SetSource(storageItemThumbnail);
                    Images p = new Images
                    {
                        Name          = file.Name,
                        imageFileName = file.Name,
                        Collection    = Picture
                    };
                    var imageid = await FileHelper.GetImageIDAsync(p, FILE_NAME);

                    p.ID = imageid;
                    ImageList.Add(p);
                }
                if (file.FileType.Equals(".mp4"))
                {
                    VideoProperties videoProperties = await file.Properties.GetVideoPropertiesAsync();

                    StorageItemThumbnail storageItemThumbnail = await file.GetThumbnailAsync(ThumbnailMode.VideosView, 200, ThumbnailOptions.UseCurrentScale);

                    var video = new BitmapImage();
                    video.SetSource(storageItemThumbnail);
                    Images v = new Images
                    {
                        Name          = file.Name,
                        videoFileName = file.Name,
                        Collection    = video
                    };
                    var videoid = await FileHelper.GetImageIDAsync(v, FILE_NAME);

                    v.ID = videoid;
                    VideoImageList.Add(v);
                }
            }
        }
Exemplo n.º 14
0
    void OnTargetFound(TargetAbstractBehaviour behaviour)
    {
        Debug.Log("Found: " + Target.Id + " (" + Target.Name + ")");

        if (previousTarget != Target.Name)
        {
            previousTarget = Target.Name;
            var videoComponents = GetComponentsInChildren <VideoPlayer>(true);
            foreach (var component in videoComponents)
            {
                string videoURL = Application.persistentDataPath + "/" + Target.Name + ".mp4";
                if (System.IO.File.Exists(videoURL))
                {
                    component.targetTexture = new RenderTexture(1, 1, 0);
                    component.source        = VideoSource.Url;
                    component.url           = videoURL;
                    VideoProperties videoProperties = GetVideoProperties(component.url);
                    component.Prepare();
                    previousPlayer              = component;
                    component.prepareCompleted += (VideoPlayer source) =>
                    {
                        previousTarget = Target.Name;
                        float videoWidth  = source.texture.width;
                        float videoHeight = source.texture.height;
                        Debug.Log("Rotation: " + videoProperties.rotation);
                        component.transform.localScale = new Vector3(videoWidth / Mathf.Max(videoWidth, videoHeight) * VIDEO_SCALING,
                                                                     videoHeight / Mathf.Max(videoWidth, videoHeight) * VIDEO_SCALING, 1f);
                        component.transform.rotation = Quaternion.Euler(X_VIDEO_ROTATION, 0, -1 * videoProperties.rotation); // Lay the video flat
                        component.Play();
                        if (timeStamps.ContainsKey(Target.Name))
                        {
                            component.time = timeStamps[previousTarget];
                        }
                    };
                    Debug.Log("Playing from: " + Application.persistentDataPath + "/" + Target.Name + ".mp4");
                }
                else
                {
                    Debug.Log("File does not exists");
                }
            }
        }
        else
        {
            previousPlayer.Play();
            previousPlayer.time = videoTime;
        }
    }
Exemplo n.º 15
0
        // 通过 StorageFolder.Properties 的 GetImagePropertiesAsync(), GetVideoPropertiesAsync(), GetMusicPropertiesAsync(), GetDocumentPropertiesAsync() 方法获取文件的属性
        private async Task ShowProperties4(StorageFile storageFile)
        {
            StorageItemContentProperties storageItemContentProperties = storageFile.Properties;
            ImageProperties imageProperties = await storageItemContentProperties.GetImagePropertiesAsync();          // 图片属性

            VideoProperties videoProperties = await storageItemContentProperties.GetVideoPropertiesAsync();          // 视频属性

            MusicProperties musicProperties = await storageItemContentProperties.GetMusicPropertiesAsync();          // 音频属性

            DocumentProperties documentProperties = await storageItemContentProperties.GetDocumentPropertiesAsync(); // 文档属性

            lblMsg.Text += "image width:" + imageProperties.Width;
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "image height:" + imageProperties.Height;
            lblMsg.Text += Environment.NewLine;
        }
Exemplo n.º 16
0
        //CommandBar

        /**
         * Video Title
         */
        public async void SetVideoTitle(StorageFile storageFile)
        {
            if (storageFile != null)
            {
                VideoProperties videoProperties = await storageFile.Properties.GetVideoPropertiesAsync();

                if (videoProperties.Title == "")
                {
                    title.Text = storageFile.Name;
                }
                else
                {
                    title.Text = videoProperties.Title;
                }
            }
        }
Exemplo n.º 17
0
        public static MediaEncodingProfile CreateVideoEncodingProfileFromProps(VideoProperties props)
        {
            var width  = (double)props.Width;
            var height = (double)props.Height;

            double maxWidth  = App.RoamingSettings.Read(VIDEO_WIDTH, 854);
            double maxHeight = App.RoamingSettings.Read(VIDEO_HEIGHT, 480);

            Drawing.ScaleProportions(ref width, ref height, maxWidth, maxHeight);
            var bitrate = App.RoamingSettings.Read(VIDEO_BITRATE, 1_115_000u);

            if (width == 0)
            {
                width = maxWidth;
            }
            if (height == 0)
            {
                height = maxHeight;
            }

            var profile = new MediaEncodingProfile()
            {
                Container = new ContainerEncodingProperties()
                {
                    Subtype = MediaEncodingSubtypes.Mpeg4
                },
                Video = new VideoEncodingProperties()
                {
                    Width   = (uint)(Math.Round(width / 2.0) * 2),
                    Height  = (uint)(Math.Round(height / 2.0) * 2),
                    Subtype = MediaEncodingSubtypes.H264,
                    Bitrate = bitrate
                },
                Audio = new AudioEncodingProperties()
                {
                    Bitrate       = App.RoamingSettings.Read(AUDIO_BITRATE, 192u),
                    BitsPerSample = 16,
                    ChannelCount  = 2,
                    SampleRate    = App.RoamingSettings.Read(AUDIO_SAMPLERATE, 44100u),
                    Subtype       = MediaEncodingSubtypes.Aac
                }
            };

            return(profile);
        }
Exemplo n.º 18
0
        public async Task LoadFromFolder(StorageFolder storageFolder)
        {
            IReadOnlyList <StorageFile> fileList = await storageFolder.GetFilesAsync();

            const ThumbnailMode thumbnailMode = ThumbnailMode.MusicView;

            foreach (StorageFile f in fileList)
            {
                if (videoFormat.FindIndex(x => x.Equals(f.FileType, StringComparison.OrdinalIgnoreCase)) != -1)
                {
                    const uint size = 100;
                    using (StorageItemThumbnail thumbnail = await f.GetThumbnailAsync(thumbnailMode, size))
                    {
                        // Also verify the type is ThumbnailType.Image (album art) instead of ThumbnailType.Icon
                        // (which may be returned as a fallback if the file does not provide album art)
                        if (thumbnail != null && (thumbnail.Type == ThumbnailType.Image || thumbnail.Type == ThumbnailType.Icon))
                        {
                            BitmapImage bitmapImage = new BitmapImage();
                            bitmapImage.SetSource(thumbnail);
                            MediaFile       o1 = new VideoFile();
                            VideoProperties videoProperties = await f.Properties.GetVideoPropertiesAsync();

                            Image i = new Image();
                            i.Source = bitmapImage;
                            o1.Thumb = i;
                            o1.Title = f.Name;
                            if (videoProperties.Title != "")
                            {
                                o1.Title = videoProperties.Title;
                            }
                            o1.Name = f.Name;
                            o1.Path = f.Path;
                            videoFiles.Add((VideoFile)o1);
                            autoList.Add(o1.Title);
                        }
                    }
                }
            }
            IReadOnlyList <StorageFolder> folderList = await storageFolder.GetFoldersAsync();

            foreach (var i in folderList)
            {
                await LoadFromFolder(i);
            }
        }
Exemplo n.º 19
0
        public VideoReader(String filePath)
        {
            try
            {
                reader = new VideoFileReader();
                reader.Open(filePath);
            }
            catch (Exception e)
            {
                throw e;
            }

            properties            = new VideoProperties();
            properties.Width      = reader.Width;
            properties.Height     = reader.Height;
            properties.FrameCount = reader.FrameCount;
            properties.FrameRate  = reader.FrameRate;
        }
Exemplo n.º 20
0
        public async Task <bool> DeleteVideoAsync(VideoProperties properties)
        {
            //Async delete operation that waits until the file system has deleted the file.
            var fi = new FileInfo(PhysicalFilePath(properties.VirtualFilePath));

            if (fi.Exists)
            {
                fi.Delete();
                fi.Refresh();
                while (fi.Exists)
                {
                    await Task.Delay(100);

                    fi.Refresh();
                }
                return(true);
            }
            return(false);
        }
Exemplo n.º 21
0
        public StorageVideo(StorageFile file, BasicProperties basic, VideoProperties props, MediaEncodingProfile profile)
            : base(file)
        {
            _basic     = basic;
            Properties = props;
            Profile    = profile;

            videoDuration = props.Duration.TotalMilliseconds;

            originalSize    = (long)basic.Size;
            originalWidth   = (int)props.Width;
            originalHeight  = (int)props.Height;
            originalBitrate = bitrate = (int)props.Bitrate; //(trackBitrate / 100000 * 100000);

            if (bitrate > 900000)
            {
                bitrate = 900000;
            }
        }
Exemplo n.º 22
0
        public async Task <VideoProperties> StoreVideoAsync(Stream sourceStream, VideoProperties properties, long expectedLength, CancellationToken token)
        {
            if (string.IsNullOrWhiteSpace(properties.ContainerExt))
            {
                properties.ContainerExt = "unkwn";
            }

            properties.VirtualFilePath = $"{Path.GetRandomFileName()}.{properties.ContainerExt}";
            string physicalFilePath = PhysicalFilePath(properties.VirtualFilePath);
            bool   fileOk           = true;

            try
            {
                if (!token.IsCancellationRequested)
                {
                    using FileStream f = new FileStream(physicalFilePath, FileMode.CreateNew, FileAccess.Write, FileShare.None, 4096, true);
                    await sourceStream.CopyToAsync(f, token);
                }
            }
            finally
            {
                fileOk = !token.IsCancellationRequested;
                if (fileOk)
                {
                    properties.FileSize = new FileInfo(physicalFilePath).Length;
                    if (properties.FileSize < expectedLength)
                    {
                        fileOk = false;
                    }
                }
                if (!fileOk)
                {
                    await DeleteVideoAsync(properties);
                }
            }
            if (!fileOk)
            {
                return(null);
            }

            return(properties);
        }
Exemplo n.º 23
0
        public StorageVideo(StorageFile file, BasicProperties basic, VideoProperties props, MediaEncodingProfile profile)
            : base(file, basic)
        {
            _fullRectangle = new Rect(0, 0, props.GetWidth(), props.GetHeight());

            _basic     = basic;
            Properties = props;
            Profile    = profile;

            videoDuration = props.Duration.TotalMilliseconds;

            originalSize    = (long)basic.Size;
            originalWidth   = (int)props.GetWidth();
            originalHeight  = (int)props.GetHeight();
            originalBitrate = bitrate = (int)props.Bitrate; //(trackBitrate / 100000 * 100000);

            if (bitrate > 900000)
            {
                bitrate = 900000;
            }

            LoadPreview();
        }
Exemplo n.º 24
0
 public static uint GetWidth(this VideoProperties props)
 {
     return(props.Orientation == VideoOrientation.Rotate180 || props.Orientation == VideoOrientation.Normal ? props.Width : props.Height);
 }
Exemplo n.º 25
0
        private void OnFileChangedInternal(StorageFile storageFile)
        {
            Photos.Children.Clear();
            LeftTransform.X = -MaxTranslateX;
            LeftOpacityBorderTransform.X = -465.0;
            Left.IsHitTestVisible = false;
            RightTransform.X = MaxTranslateX;
            RightOpacityBorderTransform.X = 465.0;
            Right.IsHitTestVisible = false;
            _videoProperties = null;
            _composition = null;
            TrimRight = null;
            TrimLeft = null;
            _lastPosition = null;
            _isManipulating = false;

            if (storageFile != null)
            {
                Telegram.Api.Helpers.Execute.BeginOnThreadPool(TimeSpan.FromSeconds(1.0), async () =>
                {
                    _videoProperties = storageFile.Properties.GetVideoPropertiesAsync().AsTask().Result;
                    if (_videoProperties == null) return;

                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        Left.IsHitTestVisible = true;
                        Right.IsHitTestVisible = true;
                    });

                    _composition = new MediaComposition();
                    var clip = await MediaClip.CreateFromFileAsync(storageFile);
                    _composition.Clips.Add(clip);

                    var scaleFactor = 100.0 / Math.Min(_videoProperties.Width, _videoProperties.Height);
                    var thumbnailWidth = _videoProperties.Orientation == VideoOrientation.Normal || _videoProperties.Orientation == VideoOrientation.Rotate180 ? (int)(_videoProperties.Width * scaleFactor) : (int)(_videoProperties.Height * scaleFactor);
                    var thumbnailHeight = _videoProperties.Orientation == VideoOrientation.Normal || _videoProperties.Orientation == VideoOrientation.Rotate180 ? (int)(_videoProperties.Height * scaleFactor) : (int)(_videoProperties.Width * scaleFactor);
                    for (var i = 0; i < 9; i++)
                    {
                        var timeStamp = new TimeSpan(_videoProperties.Duration.Ticks / 9 * i);

                        var photo = await _composition.GetThumbnailAsync(timeStamp, thumbnailWidth, thumbnailHeight, VideoFramePrecision.NearestKeyFrame);
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            var stream = photo.AsStream();
                            var bitmapImage = new BitmapImage();
                            var image = new Image
                            {
                                CacheMode = new BitmapCache(),
                                Stretch = Stretch.UniformToFill,
                                Width = 50.0,
                                Height = 50.0,
                                Source = bitmapImage
                            };
                            Photos.Children.Add(image);

                            bitmapImage.SetSource(stream);
                        });
                    }
                });
            }
        }
        private static void GetVideoProperties(ICollection <StorageFileProperty> results, VideoProperties props)
        {
            var title    = props.Title;
            var subTitle = props.Subtitle;
            var duration = props.Duration;
            var bitRate  = props.Bitrate;
            var height   = props.Height;
            var width    = props.Width;

            var latitude  = props.Latitude.ToString();
            var longitude = props.Longitude.ToString();

            if (!title.IsEmpty())
            {
                if (results.FirstOrDefault(x => x.Name == "Title") == null)
                {
                    results.Add(new StorageFileProperty("Title", title));
                }
            }

            if (!subTitle.IsEmpty())
            {
                if (results.FirstOrDefault(x => x.Name == "Subtitle") == null)
                {
                    results.Add(new StorageFileProperty("Subtitle", subTitle));
                }
            }

            if (duration != TimeSpan.FromSeconds(0))
            {
                var val = duration.ToString("G");
                if (!val.IsEmpty())
                {
                    if (results.FirstOrDefault(x => x.Name == "Duration") == null)
                    {
                        results.Add(new StorageFileProperty("Duration", val));
                    }
                }
            }

            if (bitRate != 0)
            {
                if (results.FirstOrDefault(x => x.Name == "Bitrate") == null)
                {
                    results.Add(new StorageFileProperty("Bitrate", bitRate));
                }
            }

            if (height != 0 || width != 0)
            {
                if (results.FirstOrDefault(x => x.Name == "Height") == null)
                {
                    results.Add(new StorageFileProperty("Height", height));
                }

                if (results.FirstOrDefault(x => x.Name == "Width") == null)
                {
                    results.Add(new StorageFileProperty("Width", width));
                }
            }

            if (!latitude.IsEmpty())
            {
                if (results.FirstOrDefault(x => x.Name == "GPS latitude") == null)
                {
                    results.Add(new StorageFileProperty("GPS latitude", latitude));
                }
            }

            if (!longitude.IsEmpty())
            {
                if (results.FirstOrDefault(x => x.Name == "GPS longitude") == null)
                {
                    results.Add(new StorageFileProperty("GPS longitude", longitude));
                }
            }
        }
Exemplo n.º 27
0
        private async Task GatherSubFolderAndFiles(StorageFolder folder, Directory parent, bool singleVideo = false)
        {
            LogMessage.AppendLine($"***********************");
            LogMessage.AppendLine($"Folder: {folder.Name}");

            bool folderHasImage = false;

            foreach (var file in await folder.GetFilesAsync())
            {
                if (ImageExtensions.Contains(file.FileType.ToUpper()) && !folderHasImage)
                {
                    var copy = await file.CopyAsync(await Cache.GetThumbnailFolder());

                    await copy.RenameAsync(Cache.GetName(parent.Id.Value));

                    folderHasImage = true;
                }

                if (AllowedExtension.Contains(file.FileType.ToUpper()))
                {
                    LogMessage.AppendLine($"    {file.Name}");
                    VideoProperties videoProperties = await file.Properties.GetVideoPropertiesAsync();

                    var title    = videoProperties.Title;
                    var fileName = string.IsNullOrEmpty(title) ? file.Name : title;
                    var video    = new Video()
                    {
                        Name        = file.DisplayName,
                        Parent      = parent,
                        Path        = file.Path,
                        FileName    = fileName,
                        ParentDirId = parent.Id.Value,
                        Id          = Guid.NewGuid(),
                        Markers     = new List <Markers>(),
                    };

                    var thumbnail = await file.GetThumbnailAsync(ThumbnailMode.VideosView);

                    using (var reader = new DataReader(thumbnail.GetInputStreamAt(0)))
                    {
                        await reader.LoadAsync((uint)thumbnail.Size);

                        var buffer = new byte[(int)thumbnail.Size];
                        reader.ReadBytes(buffer);
                        Cache.SaveThumbnail(buffer, video.Id.Value);
                    }
                    parent.Videos.Add(video);

                    if (singleVideo)
                    {
                        return;
                    }
                }
            }

            foreach (var subFolder in await folder.GetFoldersAsync())
            {
                if (subFolder.Name.ToLower() == "sample" || subFolder.Name.ToLower() == "subtitles" || subFolder.Name.ToLower() == "subs")
                {
                    continue;
                }
                var directory = new Directory()
                {
                    Name        = subFolder.Name,
                    Parent      = parent,
                    Path        = subFolder.Path,
                    Id          = Guid.NewGuid(),
                    ParentDirId = parent.Id.Value
                };
                parent.Directories.Add(directory);
                await GatherSubFolderAndFiles(subFolder, directory);
            }
        }
Exemplo n.º 28
0
        public static async Task <TLPhotoSizeBase> GetVideoThumbnailAsync(StorageFile file, VideoProperties props, VideoTransformEffectDefinition effect)
        {
            double originalWidth  = props.GetWidth();
            double originalHeight = props.GetHeight();

            if (effect != null && !effect.CropRectangle.IsEmpty)
            {
                file = await CropAsync(file, effect.CropRectangle);

                originalWidth  = effect.CropRectangle.Width;
                originalHeight = effect.CropRectangle.Height;
            }

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

            var desiredName = string.Format("{0}_{1}_{2}.jpg", fileLocation.VolumeId, fileLocation.LocalId, fileLocation.Secret);
            var desiredFile = await FileUtils.CreateTempFileAsync(desiredName);

            using (var fileStream = await OpenReadAsync(file))
                using (var outputStream = await desiredFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    var decoder = await BitmapDecoder.CreateAsync(fileStream);

                    double ratioX = (double)90 / originalWidth;
                    double ratioY = (double)90 / originalHeight;
                    double ratio  = Math.Min(ratioX, ratioY);

                    uint width  = (uint)(originalWidth * ratio);
                    uint height = (uint)(originalHeight * ratio);

                    var transform = new BitmapTransform();
                    transform.ScaledWidth       = width;
                    transform.ScaledHeight      = height;
                    transform.InterpolationMode = BitmapInterpolationMode.Linear;

                    if (effect != null)
                    {
                        transform.Flip = effect.Mirror == MediaMirroringOptions.Horizontal ? BitmapFlip.Horizontal : BitmapFlip.None;
                    }

                    var pixelData = await decoder.GetSoftwareBitmapAsync(decoder.BitmapPixelFormat, decoder.BitmapAlphaMode, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage);

                    var propertySet  = new BitmapPropertySet();
                    var qualityValue = new BitmapTypedValue(0.77, PropertyType.Single);
                    propertySet.Add("ImageQuality", qualityValue);

                    var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, outputStream);

                    encoder.SetSoftwareBitmap(pixelData);
                    await encoder.FlushAsync();

                    result = new TLPhotoSize
                    {
                        W        = (int)width,
                        H        = (int)height,
                        Size     = (int)outputStream.Size,
                        Type     = string.Empty,
                        Location = fileLocation
                    };
                }

            return(result);
        }
Exemplo n.º 29
0
 public Stream GetVideo(VideoProperties properties) => new FileStream(PhysicalFilePath(properties.VirtualFilePath), FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true);
Exemplo n.º 30
0
 public static uint GetHeight(this VideoProperties props)
 {
     return(props.Orientation is VideoOrientation.Rotate180 or VideoOrientation.Normal ? props.Height : props.Width);
 }