Example #1
0
        public virtual void readMetadata(MediaProbe mediaProbe, Stream data, MetadataFactory.ReadOptions options, BaseMetadata media, CancellationToken token, int timeoutSeconds)
        {
            XMPLib.MetaData.ErrorCallbackDelegate errorCallbackDelegate = new XMPLib.MetaData.ErrorCallbackDelegate(errorCallback);

            //XMPLib.MetaData xmpMetaDataReader = new XMPLib.MetaData(errorCallbackDelegate, null);
            XMPLib.MetaData xmpMetaDataReader = new XMPLib.MetaData(null, null);

            try
            {
                FileInfo info = new FileInfo(media.Location);
                info.Refresh();
                media.LastModifiedDate = info.LastWriteTime < sqlMinDate ? sqlMinDate : info.LastWriteTime;
                media.FileDate         = info.CreationTime < sqlMinDate ? sqlMinDate : info.CreationTime;
                media.MimeType         = MediaFormatConvert.fileNameToMimeType(media.Name);

                if (media.SupportsXMPMetadata == false)
                {
                    return;
                }

                xmpMetaDataReader.open(media.Location, Consts.OpenOptions.XMPFiles_OpenForRead);

                readXMPMetadata(xmpMetaDataReader, media);
            }
            catch (Exception e)
            {
                Logger.Log.Error("Cannot read XMP metadata for: " + media.Location, e);
                media.MetadataReadError = e;
            } finally {
                xmpMetaDataReader.Dispose();
                xmpMetaDataReader = null;
            }
        }
        public void startDownload(String outputPath, List <MediaItem> items)
        {
            TotalProgress    = 0;
            TotalProgressMax = items.Count;

            try
            {
                foreach (YoutubeVideoItem item in items)
                {
                    CancellationToken.ThrowIfCancellationRequested();

                    YoutubeVideoStreamedItem videoStream, audioStream;
                    item.getStreams(out videoStream, out audioStream, (int)Properties.Settings.Default.MaxDownloadResolution);

                    if (videoStream == null)
                    {
                        InfoMessages.Add("Skipping: " + item.Name + " no streams found");
                        continue;
                    }

                    YoutubeItemMetadata metadata = item.Metadata as YoutubeItemMetadata;

                    String fullpath;
                    String ext      = "." + MediaFormatConvert.mimeTypeToExtension(metadata.MimeType);
                    String filename = FileUtils.removeIllegalCharsFromFileName(item.Name, " ") + ext;

                    try
                    {
                        fullpath = FileUtils.getUniqueFileName(outputPath + "\\" + filename);
                    }
                    catch (Exception)
                    {
                        fullpath = FileUtils.getUniqueFileName(outputPath + "\\" + "stream" + ext);
                    }

                    if (audioStream == null)
                    {
                        singleStreamDownload(fullpath, videoStream);
                    }
                    else
                    {
                        downloadAndMuxStreams(fullpath, videoStream, audioStream);
                    }

                    saveMetadata(fullpath, item);

                    InfoMessages.Add("Finished: " + videoStream.Name + " -> " + fullpath);

                    TotalProgress++;
                }
            }
            catch (Exception e)
            {
                InfoMessages.Add("Error: " + e.Message);
            }
        }
        private bool addInputMedia(FileInfo info, object state)
        {
            ObservableCollection <MediaFileItem> items = (ObservableCollection <MediaFileItem>)state;

            if (MediaFormatConvert.isMediaFile(info.FullName))
            {
                items.Add(MediaFileItem.Factory.create(info.FullName));
            }

            return(true);
        }
Example #4
0
        private static bool getFiles(FileInfo info, object state)
        {
            List <MediaFileItem> items = (List <MediaFileItem>)state;

            if (MediaFormatConvert.isMediaFile(info.FullName))
            {
                items.Add(MediaFileItem.Factory.create(info.FullName));
            }

            return(true);
        }
Example #5
0
        public async Task generatePreviews()
        {
            await Task.Factory.StartNew(() =>
            {
                try
                {
                    TotalProgressMax = asyncState.Media.Count;

                    for (TotalProgress = 0; TotalProgress < TotalProgressMax; TotalProgress++)
                    {
                        MediaFileItem item = asyncState.Media.ElementAt(TotalProgress);

                        if (CancellationToken.IsCancellationRequested)
                        {
                            return;
                        }
                        if (!MediaFormatConvert.isVideoFile(item.Location))
                        {
                            InfoMessages.Add("Skipping: " + item.Location + " is not a video file.");
                            continue;
                        }
                        if (item.Metadata == null)
                        {
                            item.EnterUpgradeableReadLock();
                            try
                            {
                                item.readMetadata_URLock(MetadataFactory.ReadOptions.AUTO, CancellationToken);
                                if (item.ItemState != MediaItemState.LOADED)
                                {
                                    InfoMessages.Add("Skipping: " + item.Location + " could not read metadata.");
                                    continue;
                                }
                            }
                            finally
                            {
                                item.ExitUpgradeableReadLock();
                            }
                        }

                        generatePreview(item);
                    }
                }
                finally
                {
                    App.Current.Dispatcher.Invoke(() =>
                    {
                        OkCommand.IsExecutable     = true;
                        CancelCommand.IsExecutable = false;
                    });
                }
            });
        }
Example #6
0
        protected BaseMetadata(String location, Stream data)
        {
            Tags = new List <Tag>();



            MimeType = MediaFormatConvert.fileNameToMimeType(location);

            Location  = location;
            Data      = data;
            Thumbnail = null;

            isReadOnly        = false;
            isImported        = false;
            isModified        = false;
            metadataReadError = null;
        }
Example #7
0
        private void listMediaFiles(string path)
        {
            DirectoryInfo imageDirInfo = new DirectoryInfo(path);

            FileInfo[] fileInfo = imageDirInfo.GetFiles();

            List <MediaFileItem> items = new List <MediaFileItem>();

            for (int i = 0; i < fileInfo.Length; i++)
            {
                if (MediaFormatConvert.isMediaFile(fileInfo[i].FullName))
                {
                    items.Add(MediaFileItem.Factory.create(fileInfo[i].FullName));
                }
            }

            MediaFileState.clearUIState(imageDirInfo.Name, imageDirInfo.CreationTime, MediaStateType.Directory);
            MediaFileState.addUIState(items);
        }
Example #8
0
        static List <BitmapSource> getImages(List <MediaFileItem> items, bool useThumbs)
        {
            List <BitmapSource> images = new List <BitmapSource>();

            foreach (MediaFileItem item in items)
            {
                if (MediaFormatConvert.isImageFile(item.Location) && !useThumbs)
                {
                    images.Add(new BitmapImage(new Uri(item.Location)));
                }
                else
                {
                    if (item.Metadata != null && item.Metadata.Thumbnail != null)
                    {
                        images.Add(item.Metadata.Thumbnail.Image);
                    }
                }
            }

            return(images);
        }
        private void requestNavigateEvent(object sender, RoutedEventArgs e)
        {
            RequestNavigateEventArgs args = e as RequestNavigateEventArgs;

            Uri uri = args.Uri;

            if (uri.IsFile)
            {
                String location = null;

                location = HttpUtility.UrlDecode(uri.AbsolutePath);

                if (MediaFormatConvert.isVideoFile(location))
                {
                    NameValueCollection values = HttpUtility.ParseQueryString(uri.Query);

                    String[] formats = { @"h'h'm'm's's'", @"m'm's's'", @"s's'" };

                    String   timeOffsetString = values["t"];
                    TimeSpan time             = new TimeSpan();

                    if (timeOffsetString != null)
                    {
                        try
                        {
                            bool success = TimeSpan.TryParseExact(timeOffsetString, formats, null, out time);
                        }
                        catch (Exception ex)
                        {
                            Logger.Log.Error("Error parsing timestring: " + timeOffsetString + " for " + location, ex);
                        }
                    }

                    MediaItem item = MediaItemFactory.create(location);
                    Shell.ShellViewModel.navigateToVideoView(item, (int)time.TotalSeconds);
                }

                e.Handled = true;
            }
        }
Example #10
0
        public void startDownload(String outputPath, List <MediaItem> items)
        {
            TotalProgress    = 0;
            TotalProgressMax = items.Count;

            foreach (ImageResultItem item in items)
            {
                if (CancellationToken.IsCancellationRequested)
                {
                    throw new OperationCanceledException(CancellationToken);
                }

                String fullpath = null;
                String ext      = "." + MediaFormatConvert.mimeTypeToExtension(item.ImageInfo.ContentType);

                try
                {
                    String filename = Path.GetFileName(item.ImageInfo.MediaUrl);

                    if (!filename.EndsWith(ext))
                    {
                        filename  = filename.Substring(0, filename.LastIndexOf('.'));
                        filename += ext;
                    }

                    fullpath = FileUtils.getUniqueFileName(outputPath + "\\" + filename);
                }
                catch (Exception)
                {
                    fullpath = FileUtils.getUniqueFileName(outputPath + "\\" + "image" + ext);
                }

                FileStream outFile = null;

                try
                {
                    outFile = new FileStream(fullpath, FileMode.Create);
                    string mimeType;

                    ItemProgressMax = 1;
                    ItemProgress    = 0;

                    ItemInfo = "Downloading: " + fullpath;
                    StreamUtils.readHttpRequest(new Uri(item.ImageInfo.MediaUrl), outFile, out mimeType, CancellationToken, progressCallback);
                    TotalProgress++;
                    ItemProgressMax = 1;
                    ItemProgress    = 1;
                    InfoMessages.Add("Downloaded: " + fullpath);

                    outFile.Close();
                }
                catch (Exception e)
                {
                    InfoMessages.Add("Error downloading: " + fullpath + " " + e.Message);

                    if (outFile != null)
                    {
                        outFile.Close();
                        File.Delete(fullpath);
                    }

                    return;
                }
            }
        }
Example #11
0
        private bool getMediaFiles(System.IO.FileInfo info, object state)
        {
            if (CancellationToken.IsCancellationRequested)
            {
                return(false);
            }

            ScanLocation location = (state as Tuple <ScanLocation, ObservableCollection <ScanLocation>, List <String> >).Item1;
            ObservableCollection <ScanLocation> excludeLocations = (state as Tuple <ScanLocation, ObservableCollection <ScanLocation>, List <String> >).Item2;
            List <String> items = (state as Tuple <ScanLocation, ObservableCollection <ScanLocation>, List <String> >).Item3;

            String addItem = null;

            switch (location.MediaType)
            {
            case Search.MediaType.All:
            {
                if (MediaViewer.Model.Utils.MediaFormatConvert.isMediaFile(info.Name))
                {
                    addItem = info.FullName;
                }
                break;
            }

            case Search.MediaType.Images:
            {
                if (MediaFormatConvert.isImageFile(info.Name))
                {
                    addItem = info.FullName;
                }
                break;
            }

            case Search.MediaType.Video:
            {
                if (MediaFormatConvert.isVideoFile(info.Name))
                {
                    addItem = info.FullName;
                }
                break;
            }
            }

            if (addItem != null)
            {
                String path = FileUtils.getPathWithoutFileName(addItem);

                bool excluded = false;

                foreach (ScanLocation excludeLocation in excludeLocations)
                {
                    if (excludeLocation.IsRecursive)
                    {
                        if (path.StartsWith(excludeLocation.Location))
                        {
                            if (excludeLocation.MediaType == Search.MediaType.All ||
                                (excludeLocation.MediaType == Search.MediaType.Images && MediaFormatConvert.isImageFile(addItem)) ||
                                (excludeLocation.MediaType == Search.MediaType.Video && MediaFormatConvert.isVideoFile(addItem)))
                            {
                                excluded = true;
                                break;
                            }
                        }
                    }
                    else
                    {
                        if (path.Equals(excludeLocation.Location))
                        {
                            if (excludeLocation.MediaType == Search.MediaType.All ||
                                (excludeLocation.MediaType == Search.MediaType.Images && MediaFormatConvert.isImageFile(addItem)) ||
                                (excludeLocation.MediaType == Search.MediaType.Video && MediaFormatConvert.isVideoFile(addItem)))
                            {
                                excluded = true;
                                break;
                            }
                        }
                    }
                }

                if (!items.Contains(addItem) && !excluded)
                {
                    items.Add(addItem);
                }
            }

            return(true);
        }
        public MainWindowViewModel()
        {
            WindowTitle = "MediaViewer";

            // recieve messages requesting the display of media items

/*
 *          GlobalMessenger.Instance.Register<string>("MainWindowViewModel.ViewMediaCommand", new Action<string>((fileName) =>
 *          {
 *              ViewMediaCommand.DoExecute(fileName);
 *          }));
 */
            ViewMediaCommand = new Command <String>(new Action <String>((location) =>
            {
                if (String.IsNullOrEmpty(location))
                {
                    return;
                }

                String mimeType = MediaFormatConvert.fileNameToMimeType(location);

                if (mimeType.StartsWith("image"))
                {
                    CurrentImageLocation = location;
                }
                else if (mimeType.StartsWith("video"))
                {
                    CurrentVideoLocation = location;
                }
                else
                {
                    Logger.Log.Warn("Trying to view media of unknown mime type: " + (string)location + ", mime type: " + mimeType);
                }
            }));

            TagEditorCommand = new Command(() =>
            {
                //TagEditorView tagEditor = new TagEditorView();
                //tagEditor.ShowDialog();
            });


            ShowLogCommand = new Command(() =>
            {
                //log4net.Appender.IAppender[] appenders = log4net.LogManager.GetRepository().GetAppenders();
                //VisualAppender appender = (VisualAppender)(appenders[0]);

                LogView logView = new LogView();
                //logView.DataContext = appender.LogViewModel;

                logView.Show();
            });

            ClearHistoryCommand = new Command(() =>
            {
                if (MessageBox.Show("Clear all history?", "Warning", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                {
                    Settings.Default.Reset();
                }
            });
        }
Example #13
0
        private void startTranscode()
        {
            Dictionary <String, Object> options = new Dictionary <string, object>();

            if (State.Width != null)
            {
                options.Add("Width", State.Width.Value);
            }

            if (State.Height != null)
            {
                options.Add("Height", State.Height.Value);
            }

            options.Add("QualityLevel", State.JpegQuality);
            options.Add("Rotation", Enum.Parse(typeof(Rotation), State.JpegRotationCollectionView.CurrentItem.ToString()));
            options.Add("Interlace", Enum.Parse(typeof(PngInterlaceOption), State.PngInterlacingCollectionView.CurrentItem.ToString()));
            options.Add("TiffCompression", Enum.Parse(typeof(TiffCompressOption), State.TiffCompressionCollectionView.CurrentItem.ToString()));
            options.Add("FlipHorizontal", State.FlipHorizontal);
            options.Add("FlipVertical", State.FlipVertical);

            TotalProgress    = 0;
            TotalProgressMax = State.Items.Count;

            foreach (MediaFileItem item in State.Items)
            {
                if (CancellationToken.IsCancellationRequested)
                {
                    return;
                }

                FileStream imageStream = null;

                item.EnterReadLock();
                try
                {
                    ItemProgress = 0;

                    if (MediaFormatConvert.isImageFile(item.Location))
                    {
                        String outputPath = State.OutputPath + "\\" + Path.GetFileNameWithoutExtension(item.Location) + "." + ((String)State.OutputFormatCollectionView.CurrentItem).ToLower();

                        outputPath = FileUtils.getUniqueFileName(outputPath);

                        ItemInfo = "Loading image: " + item.Location;

                        imageStream = File.Open(item.Location, FileMode.Open, FileAccess.Read);
                        Rotation rotation = ImageUtils.getBitmapRotation(imageStream);
                        imageStream.Position = 0;

                        BitmapImage loadedImage = new BitmapImage();

                        loadedImage.BeginInit();
                        loadedImage.CacheOption  = BitmapCacheOption.OnLoad;
                        loadedImage.StreamSource = imageStream;
                        loadedImage.Rotation     = rotation;
                        loadedImage.EndInit();

                        imageStream.Close();
                        imageStream = null;

                        ItemInfo = "Writing image: " + outputPath;

                        ImageTranscoder.writeImage(outputPath, loadedImage, options,
                                                   State.IsCopyMetadata ? item.Metadata as ImageMetadata : null, this);

                        InfoMessages.Add("Finished: " + item.Location + " -> " + outputPath);
                    }
                    else
                    {
                        InfoMessages.Add("Skipped: " + item.Location + " is not a image file");
                    }

                    TotalProgress++;
                    ItemProgress = 100;
                }
                catch (Exception e)
                {
                    InfoMessages.Add("Error: " + e.Message);
                    Logger.Log.Error("Error: " + e.Message);
                    return;
                }
                finally
                {
                    item.ExitReadLock();
                    if (imageStream != null)
                    {
                        imageStream.Close();
                    }
                }
            }
        }
Example #14
0
        private bool iterateFiles(System.IO.DirectoryInfo location, object state)
        {
            if (CancellationToken.IsCancellationRequested)
            {
                return(false);
            }

            Tuple <ScanLocation, ObservableCollection <ScanLocation> > locationArgs = state as Tuple <ScanLocation, ObservableCollection <ScanLocation> >;

            ScanLocation scanLocation = locationArgs.Item1;
            ObservableCollection <ScanLocation> excludeLocations = locationArgs.Item2;

            FileInfo[] files = null;

            try
            {
                files = location.GetFiles("*.*");
            }
            catch (UnauthorizedAccessException e)
            {
                Logger.Log.Warn(e.Message);
            }
            catch (DirectoryNotFoundException e)
            {
                Logger.Log.Warn(e.Message);
            }

            List <BaseMetadata> staleItems = new List <BaseMetadata>();

            using (MetadataDbCommands metadataCommands = new MetadataDbCommands())
            {
                staleItems = metadataCommands.getAllMetadataInDirectory(location.FullName);
            }

            foreach (FileInfo info in files)
            {
                if (CancellationToken.IsCancellationRequested)
                {
                    return(false);
                }

                if (MediaViewer.Model.Utils.MediaFormatConvert.isMediaFile(info.Name))
                {
                    staleItems.RemoveAll(x => x.Name.Equals(info.Name));
                }

                String addItem = null;

                switch (scanLocation.MediaType)
                {
                case Search.MediaType.All:
                {
                    if (MediaViewer.Model.Utils.MediaFormatConvert.isMediaFile(info.Name))
                    {
                        addItem = info.FullName;
                    }
                    break;
                }

                case Search.MediaType.Images:
                {
                    if (MediaFormatConvert.isImageFile(info.Name))
                    {
                        addItem = info.FullName;
                    }
                    break;
                }

                case Search.MediaType.Video:
                {
                    if (MediaFormatConvert.isVideoFile(info.Name))
                    {
                        addItem = info.FullName;
                    }
                    break;
                }

                case Search.MediaType.Audio:
                {
                    if (MediaFormatConvert.isAudioFile(info.Name))
                    {
                        addItem = info.FullName;
                    }
                    break;
                }
                }

                if (addItem != null)
                {
                    String path = FileUtils.getPathWithoutFileName(addItem);

                    bool excluded = false;

                    foreach (ScanLocation excludeLocation in excludeLocations)
                    {
                        if (excludeLocation.IsRecursive)
                        {
                            if (path.StartsWith(excludeLocation.Location))
                            {
                                if (excludeLocation.MediaType == Search.MediaType.All ||
                                    (excludeLocation.MediaType == Search.MediaType.Images && MediaFormatConvert.isImageFile(addItem)) ||
                                    (excludeLocation.MediaType == Search.MediaType.Video && MediaFormatConvert.isVideoFile(addItem)))
                                {
                                    excluded = true;
                                    break;
                                }
                            }
                        }
                        else
                        {
                            if (path.Equals(excludeLocation.Location))
                            {
                                if (excludeLocation.MediaType == Search.MediaType.All ||
                                    (excludeLocation.MediaType == Search.MediaType.Images && MediaFormatConvert.isImageFile(addItem)) ||
                                    (excludeLocation.MediaType == Search.MediaType.Video && MediaFormatConvert.isVideoFile(addItem)))
                                {
                                    excluded = true;
                                    break;
                                }
                            }
                        }
                    }

                    if (!excluded)
                    {
                        importItem(info);
                    }
                }
            }

            if (staleItems.Count > 0)
            {
                using (MetadataDbCommands metadataCommands = new MetadataDbCommands())
                {
                    foreach (BaseMetadata staleItem in staleItems)
                    {
                        metadataCommands.delete(staleItem);
                    }
                }

                Logger.Log.Info("Removed " + staleItems.Count + " stale media items from " + location.FullName);
                InfoMessages.Add("Removed " + staleItems.Count + " stale media items from " + location.FullName);
            }

            return(true);
        }
Example #15
0
        public void OnImportsSatisfied()
        {
            ShellViewModel = new ShellViewModel(MediaFileWatcher.Instance, RegionManager, EventAggregator);

            DataContext = ShellViewModel;

            this.RegionManager.RegisterViewWithRegion(RegionNames.MainNavigationToolBarRegion, typeof(ImageNavigationItemView));
            this.RegionManager.RegisterViewWithRegion(RegionNames.MainNavigationToolBarRegion, typeof(VideoNavigationItemView));
            this.RegionManager.RegisterViewWithRegion(RegionNames.MainNavigationToolBarRegion, typeof(MediaFileBrowserNavigationItemView));
            this.RegionManager.RegisterViewWithRegion(RegionNames.MainNavigationToolBarRegion, typeof(SettingsNavigationItemView));

            EventAggregator.GetEvent <TitleChangedEvent>().Subscribe((title) =>
            {
                if (!String.IsNullOrEmpty(title))
                {
                    this.Title = "MediaViewer - " + title;
                }
                else
                {
                    this.Title = "MediaViewer";
                }
            }, ThreadOption.UIThread);

            EventAggregator.GetEvent <ToggleFullScreenEvent>().Subscribe((isFullscreen) =>
            {
                if (isFullscreen)
                {
                    prevWindowState         = WindowState;
                    WindowState             = System.Windows.WindowState.Maximized;
                    WindowStyle             = System.Windows.WindowStyle.None;
                    toolBarPanel.Visibility = Visibility.Collapsed;
                }
                else
                {
                    WindowState             = prevWindowState;
                    WindowStyle             = System.Windows.WindowStyle.SingleBorderWindow;
                    toolBarPanel.Visibility = Visibility.Visible;
                }
            }, ThreadOption.UIThread);


            // initialize several settings
            ServiceLocator.Current.GetInstance(typeof(DbSettingsViewModel));
            ServiceLocator.Current.GetInstance(typeof(AboutViewModel));

            try {
                String location = App.Args.Count() > 0 ? FileUtils.getProperFilePathCapitalization(App.Args[0]) : "";

                if (MediaViewer.Model.Utils.MediaFormatConvert.isImageFile(location))
                {
                    MediaFileWatcher.Instance.Path = FileUtils.getPathWithoutFileName(location);
                    MediaItem item = MediaItemFactory.create(location);
                    ShellViewModel.navigateToImageView(item);
                }
                else if (MediaFormatConvert.isVideoFile(location))
                {
                    MediaFileWatcher.Instance.Path = FileUtils.getPathWithoutFileName(location);
                    MediaItem item = MediaItemFactory.create(location);
                    ShellViewModel.navigateToVideoView(item);
                }
                else
                {
                    ShellViewModel.navigateToMediaFileBrowser();
                }
            } catch (Exception e) {
                Logger.Log.Error("Error in command line argument: " + App.Args[0], e);
                ShellViewModel.navigateToMediaFileBrowser();
            }
        }
Example #16
0
        public VideoViewModel(IEventAggregator eventAggregator)
        {
            EventAggregator = eventAggregator;
            VideoSettings   = ServiceLocator.Current.GetInstance(typeof(VideoSettingsViewModel)) as VideoSettingsViewModel;
            VideoSettings.SettingsChanged += VideoSettings_SettingsChanged;

            IsInitialized       = false;
            isInitializedSignal = new SemaphoreSlim(0, 1);

            CurrentItem = new VideoAudioPair(null, null);

            OpenAndPlayCommand = new AsyncCommand <VideoAudioPair>(async item =>
            {
                await isInitializedSignal.WaitAsync();
                isInitializedSignal.Release();

                try
                {
                    CurrentItem = item;

                    String videoLocation   = null;
                    String videoFormatName = null;

                    if (item.Video != null)
                    {
                        videoLocation = item.Video.Location;
                        if (item.Video is MediaStreamedItem)
                        {
                            if (item.Video.Metadata != null)
                            {
                                videoFormatName = MediaFormatConvert.mimeTypeToExtension(item.Video.Metadata.MimeType);
                            }
                        }
                    }

                    String audioLocation   = null;
                    String audioFormatName = null;

                    if (item.Audio != null)
                    {
                        audioLocation = item.Audio.Location;

                        if (item.Audio is MediaStreamedItem && item.Audio.Metadata != null)
                        {
                            audioFormatName = MediaFormatConvert.mimeTypeToExtension(item.Audio.Metadata.MimeType);
                        }
                    }

                    CloseCommand.IsExecutable = true;

                    IsLoading = true;

                    await VideoPlayer.openAndPlay(videoLocation, videoFormatName, audioLocation, audioFormatName);
                }
                catch (OperationCanceledException)
                {
                    CloseCommand.IsExecutable = false;
                    throw;
                }
                catch (Exception e)
                {
                    CloseCommand.IsExecutable = false;
                    MessageBox.Show("Error opening " + item.Video.Location + "\n\n" + e.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    throw;
                }
                finally
                {
                    IsLoading = false;
                }

                EventAggregator.GetEvent <TitleChangedEvent>().Publish(CurrentItem.IsEmpty ? null : CurrentItem.Name);
            });

            PlayCommand = new AsyncCommand(async() =>
            {
                if (VideoState == VideoPlayerControl.VideoState.CLOSED && !CurrentItem.IsEmpty)
                {
                    await openAndPlay(CurrentItem);
                }
                else if (VideoState == VideoPlayerControl.VideoState.OPEN || VideoState == VideoPlayerControl.VideoState.PAUSED)
                {
                    VideoPlayer.play();
                }
            }, false);

            PauseCommand = new Command(() => {
                VideoPlayer.pause();
            }, false);

            CloseCommand = new AsyncCommand(async() => {
                await VideoPlayer.close();
            }, false);

            SeekCommand = new AsyncCommand <double>(async(pos) =>
            {
                await VideoPlayer.seek(pos);
            }, false);

            StepForwardCommand = new AsyncCommand(async() =>
            {
                StepForwardCommand.IsExecutable = false;

                double timeStamp = VideoPlayer.getFrameSeekTimeStamp() + Settings.Default.VideoStepDurationSeconds;
                await VideoPlayer.seek(timeStamp, VideoLib.VideoPlayer.SeekKeyframeMode.SEEK_FORWARDS);

                StepForwardCommand.IsExecutable = true;
            }, false);

            StepBackwardCommand = new AsyncCommand(async() =>
            {
                StepBackwardCommand.IsExecutable = false;

                double timeStamp = VideoPlayer.getFrameSeekTimeStamp() - Settings.Default.VideoStepDurationSeconds;
                await VideoPlayer.seek(timeStamp, VideoLib.VideoPlayer.SeekKeyframeMode.SEEK_BACKWARDS);

                StepBackwardCommand.IsExecutable = true;
            }, false);

            FrameByFrameCommand = new Command(() => {
                VideoPlayer.displayNextFrame();
            }, false);

            CutVideoCommand = new Command(() =>
            {
                String outputPath;

                if (FileUtils.isUrl(VideoPlayer.VideoLocation))
                {
                    outputPath = MediaFileWatcher.Instance.Path;
                }
                else
                {
                    outputPath = FileUtils.getPathWithoutFileName(VideoPlayer.VideoLocation);
                }

                VideoTranscodeView videoTranscode = new VideoTranscodeView();
                videoTranscode.ViewModel.Items.Add(CurrentItem);
                videoTranscode.ViewModel.Title   = "Cut Video";
                videoTranscode.ViewModel.IconUri = "/MediaViewer;component/Resources/Icons/videocut.ico";

                videoTranscode.ViewModel.OutputPath         = outputPath;
                videoTranscode.ViewModel.IsTimeRangeEnabled = IsTimeRangeEnabled;
                videoTranscode.ViewModel.StartTimeRange     = startTimeRangeTimeStamp;
                videoTranscode.ViewModel.EndTimeRange       = endTimeRangeTimeStamp;

                String extension = Path.GetExtension(VideoPlayer.VideoLocation).ToLower().TrimStart('.');

                foreach (ContainerFormats format in Enum.GetValues(typeof(ContainerFormats)))
                {
                    if (format.ToString().ToLower().Equals(extension))
                    {
                        videoTranscode.ViewModel.ContainerFormat = format;
                    }
                }

                videoTranscode.ShowDialog();
            }, false);

            ScreenShotCommand = new Command(() =>
            {
                try
                {
                    String screenShotName = FileUtils.removeIllegalCharsFromFileName(CurrentItem.Video.Name, " ");

                    screenShotName += "." + "jpg";

                    String path = null;

                    switch (Settings.Default.VideoScreenShotSaveMode)
                    {
                    case MediaViewer.Infrastructure.Constants.SaveLocation.Current:
                        {
                            path = MediaFileWatcher.Instance.Path;
                            break;
                        }

                    case MediaViewer.Infrastructure.Constants.SaveLocation.Ask:
                        {
                            DirectoryPickerView directoryPicker = new DirectoryPickerView();
                            DirectoryPickerViewModel vm         = (DirectoryPickerViewModel)directoryPicker.DataContext;
                            directoryPicker.Title = "Screenshot Output Directory";
                            vm.SelectedPath       = Settings.Default.VideoScreenShotLocation;
                            vm.PathHistory        = Settings.Default.VideoScreenShotLocationHistory;

                            if (directoryPicker.ShowDialog() == true)
                            {
                                path = vm.SelectedPath;
                            }
                            else
                            {
                                return;
                            }
                            break;
                        }

                    case MediaViewer.Infrastructure.Constants.SaveLocation.Fixed:
                        {
                            path = Settings.Default.VideoScreenShotLocation;
                            break;
                        }

                    default:
                        break;
                    }

                    String fullPath = FileUtils.getUniqueFileName(path + "\\" + screenShotName);

                    VideoPlayer.createScreenShot(fullPath, VideoSettings.VideoScreenShotTimeOffset);
                }
                catch (Exception e)
                {
                    MessageBox.Show("Error creating screenshot.\n\n" + e.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }, false);

            SetLeftMarkerCommand = new Command(() =>
            {
                if (IsTimeRangeEnabled == false)
                {
                    IsTimeRangeEnabled = true;
                }

                // get the exact time of the current audio or video frame, positionseconds is potentially inaccurate
                StartTimeRange          = VideoPlayer.PositionSeconds;
                startTimeRangeTimeStamp = VideoPlayer.getFrameSeekTimeStamp();
            }, false);

            SetRightMarkerCommand = new Command(() =>
            {
                if (IsTimeRangeEnabled == false)
                {
                    IsTimeRangeEnabled      = true;
                    StartTimeRange          = VideoPlayer.PositionSeconds;
                    startTimeRangeTimeStamp = VideoPlayer.getFrameSeekTimeStamp();
                }
                else
                {
                    EndTimeRange          = VideoPlayer.PositionSeconds;
                    endTimeRangeTimeStamp = VideoPlayer.getFrameSeekTimeStamp();
                }
            }, false);

            OpenLocationCommand = new Command(async() =>
            {
                VideoOpenLocationView openLocation = new VideoOpenLocationView();

                bool?success = openLocation.ShowDialog();
                if (success == true)
                {
                    MediaItem video = null;
                    MediaItem audio = null;

                    if (!String.IsNullOrWhiteSpace(openLocation.ViewModel.VideoLocation))
                    {
                        video = MediaItemFactory.create(openLocation.ViewModel.VideoLocation);
                        MiscUtils.insertIntoHistoryCollection(Settings.Default.VideoLocationHistory, openLocation.ViewModel.VideoLocation);
                    }

                    if (!String.IsNullOrWhiteSpace(openLocation.ViewModel.AudioLocation))
                    {
                        audio = MediaItemFactory.create(openLocation.ViewModel.AudioLocation);
                        MiscUtils.insertIntoHistoryCollection(Settings.Default.AudioLocationHistory, openLocation.ViewModel.AudioLocation);
                    }

                    await openAndPlay(new VideoAudioPair(video, audio));
                }
            });

            HasAudio   = true;
            VideoState = VideoPlayerControl.VideoState.CLOSED;

            IsTimeRangeEnabled      = false;
            StartTimeRange          = 0;
            EndTimeRange            = 0;
            startTimeRangeTimeStamp = 0;
            endTimeRangeTimeStamp   = 0;
        }
Example #17
0
        public static void writeImage(String outputPath, BitmapSource image, Dictionary <String, Object> options = null, ImageMetadata metaData = null, CancellableOperationProgressBase progress = null)
        {
            int width  = image.PixelWidth;
            int height = image.PixelHeight;

            float scale = ImageUtils.resizeRectangle(width, height, Constants.MAX_THUMBNAIL_WIDTH, Constants.MAX_THUMBNAIL_HEIGHT);

            TransformedBitmap thumbnail = new TransformedBitmap(image, new System.Windows.Media.ScaleTransform(scale, scale));

            if (options != null)
            {
                if (options.ContainsKey("Width"))
                {
                    width = (int)options["Width"];

                    if (!options.ContainsKey("Height"))
                    {
                        height = (int)(((float)width / image.PixelWidth) * image.PixelHeight);
                    }
                }

                if (options.ContainsKey("Height"))
                {
                    height = (int)options["Height"];

                    if (!options.ContainsKey("Width"))
                    {
                        width = (int)(((float)height / image.PixelHeight) * image.PixelWidth);
                    }
                }
            }

            BitmapSource outImage = image;

            if (width != image.PixelWidth || height != image.PixelHeight)
            {
                outImage = new TransformedBitmap(image, new System.Windows.Media.ScaleTransform((double)width / image.PixelWidth, (double)height / image.PixelHeight));
            }

            ImageFormat format = MediaFormatConvert.fileNameToImageFormat(outputPath);

            BitmapEncoder encoder = null;

            if (format == ImageFormat.Jpeg)
            {
                encoder = configureJpeg(options, ref thumbnail);
            }
            else if (format == ImageFormat.Png)
            {
                encoder = configurePng(options);
            }
            else if (format == ImageFormat.Gif)
            {
                encoder = new GifBitmapEncoder();
            }
            else if (format == ImageFormat.Bmp)
            {
                encoder = new BmpBitmapEncoder();
            }
            else if (format == ImageFormat.Tiff)
            {
                encoder = configureTiff(options);
            }

            encoder.Frames.Add(BitmapFrame.Create(outImage, thumbnail, null, null));

            FileStream outputFile = new FileStream(outputPath, FileMode.Create);

            encoder.Save(outputFile);

            outputFile.Close();

            if (metaData != null)
            {
                metaData.Location = outputPath;
                ImageFileMetadataWriter metadataWriter = new ImageFileMetadataWriter();
                metadataWriter.writeMetadata(metaData, progress);
            }
        }