예제 #1
0
 //called when current playing file is stopped
 private static void OnStopped()
 {
   //check if we're playing
   if (Playing && PlayBackStopped != null)
   {
     //yes, then raise event
     Log.Info("g_Player.OnStopped()");
     if (PlayBackStopped != null)
     {
       PlayBackStopped(_currentMedia, (int)CurrentPosition,
                       (!String.IsNullOrEmpty(currentFileName) ? currentFileName : CurrentFile));
       currentFileName = String.Empty;
       _mediaInfo = null;
     }
   }
 }
예제 #2
0
 //called when current playing file ends
 private static void OnEnded()
 {
   //check if we're playing
   if (PlayBackEnded != null)
   {
     //yes, then raise event
     Log.Info("g_Player.OnEnded()");
     PlayBackEnded(_currentMedia, (!String.IsNullOrEmpty(currentFileName) ? currentFileName : _currentFilePlaying));
     RefreshRateChanger.AdaptRefreshRate();
     currentFileName = String.Empty;
     _mediaInfo = null;
   }
 }
예제 #3
0
    public static bool Play(string strFile, MediaType type, TextReader chapters, bool fromPictures)
    {
      try
      {
        if (string.IsNullOrEmpty(strFile))
        {
          Log.Error("g_Player.Play() called without file attribute");
          return false;
        }

        IsPicture = false;
        bool playingRemoteUrl = Util.Utils.IsRemoteUrl(strFile);
        string extension = Util.Utils.GetFileExtension(strFile).ToLower();
        bool isImageFile = !playingRemoteUrl && Util.VirtualDirectory.IsImageFile(extension);
        if (isImageFile)
        {
          if (!File.Exists(Util.DaemonTools.GetVirtualDrive() + @"\VIDEO_TS\VIDEO_TS.IFO"))
            if (!File.Exists(Util.DaemonTools.GetVirtualDrive() + @"\BDMV\index.bdmv"))
            {
              _currentFilePlaying = strFile;
              MediaPortal.Ripper.AutoPlay.ExamineCD(Util.DaemonTools.GetVirtualDrive(), true);
              return true;
            }
        }

        if (!playingRemoteUrl && Util.Utils.IsDVD(strFile))
        {
          ChangeDriveSpeed(strFile, DriveType.CD);
        }

        if (!playingRemoteUrl) // MediaInfo can only be used on files (local or SMB)
        {
          _mediaInfo = new MediaInfoWrapper(strFile);
        }

        if ((!playingRemoteUrl && Util.Utils.IsVideo(strFile)) || Util.Utils.IsLiveTv(strFile)) //local video, tv, rtsp
        {
          if (type == MediaType.Unknown)
          {
            Log.Debug("g_Player.Play - Mediatype Unknown, forcing detection as Video");
            type = MediaType.Video;
          }

          // Refreshrate change done here. Blu-ray player will handle the refresh rate changes by itself
          if (strFile.ToUpper().IndexOf(@"\BDMV\INDEX.BDMV") == -1)
          {
            RefreshRateChanger.AdaptRefreshRate(strFile, (RefreshRateChanger.MediaType)(int)type);
          }

          if (RefreshRateChanger.RefreshRateChangePending)
          {
            TimeSpan ts = DateTime.Now - RefreshRateChanger.RefreshRateChangeExecutionTime;
            if (ts.TotalSeconds > RefreshRateChanger.WAIT_FOR_REFRESHRATE_RESET_MAX)
            {
              Log.Info(
                "g_Player.Play - waited {0}s for refreshrate change, but it never took place (check your config). Proceeding with playback.",
                RefreshRateChanger.WAIT_FOR_REFRESHRATE_RESET_MAX);
              RefreshRateChanger.ResetRefreshRateState();
            }
            else
            {
              return true;
            }
          }
        }

        Starting = true;
        _currentStep = 0;
        _currentStepIndex = -1;
        _seekTimer = DateTime.MinValue;
        _isInitialized = true;
        _subs = null;

        if (_player != null)
        {
          GUIGraphicsContext.ShowBackground = true;
          OnChanged(strFile);
          OnStopped();
          bool doStop = true;
          if (type != MediaType.Video && Util.Utils.IsAudio(strFile))
          {
            if (type == MediaType.Unknown)
            {
              type = MediaType.Music;
            }
            if (BassMusicPlayer.IsDefaultMusicPlayer && BassMusicPlayer.Player.Playing)
            {
              doStop = !BassMusicPlayer.Player.CrossFadingEnabled;
            }
          }
          if (doStop)
          {
            if (_player != null)
            {
              _player.Stop();
            }
            CachePlayer();
            _player = null;
          }
        }

        Log.Info("g_Player.Play({0} {1})", strFile, type);
        if (!playingRemoteUrl && Util.Utils.IsVideo(strFile))
        {
          if (!Util.Utils.IsRTSP(strFile) && extension != ".ts") // do not play recorded tv with external player
          {
            using (MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.MPSettings())
            {
              bool bInternal = xmlreader.GetValueAsBool("movieplayer", "internal", true);
              bool bInternalDVD = xmlreader.GetValueAsBool("dvdplayer", "internal", true);
              
              // External player extension filter
              _externalPlayerExtensions = xmlreader.GetValueAsString("movieplayer", "extensions", "");
              if (!bInternal && !string.IsNullOrEmpty(_externalPlayerExtensions) && 
                  extension != ".ifo" && extension != ".vob" && !Util.Utils.IsDVDImage(strFile))
              {
                // Do not use external player if file ext is not in the extension list
                if (!CheckExtension(strFile))
                  bInternal = true;
              }
              
              if ((!bInternalDVD && !isImageFile && (extension == ".ifo" || extension == ".vob")) ||
                  (!bInternalDVD && isImageFile && Util.Utils.IsDVDImage(strFile)) ||
                  // No image and no DVD folder rips
                  (!bInternal && !isImageFile && extension != ".ifo" && extension != ".vob") ||
                  // BluRay image
                  (!bInternal && isImageFile && Util.Utils.IsBDImage(strFile))) // external player used
              {
                if (isImageFile)
                {
                  // Check for DVD ISO
                  strFile = Util.DaemonTools.GetVirtualDrive() + @"\VIDEO_TS\VIDEO_TS.IFO";
                  if (!File.Exists(strFile))
                  {
                    // Check for BluRayISO
                    strFile = Util.DaemonTools.GetVirtualDrive() + (@"\BDMV\index.bdmv");
                    if (!File.Exists(strFile))
                      return false;
                  }
                }
                if (Util.Utils.PlayMovie(strFile))
                {
                  return true;
                }
                else // external player error
                {
                  UnableToPlay(strFile, type);
                  return false;
                }
              }
            }
          }
        }
        // Still for BDISO strFile = ISO filename, convert it
        if (!playingRemoteUrl) Util.Utils.IsBDImage(strFile, ref strFile);

        _currentFileName = strFile;
        _player = _factory.Create(strFile, type);
        
        if (_player != null)
        {
          if (chapters != null)
          {
            LoadChapters(chapters);
          }
          else
          {
            if (!playingRemoteUrl) LoadChapters(strFile);
          }
          _player = CachePreviousPlayer(_player);
          bool bResult = _player.Play(strFile);
          if (!bResult)
          {
            Log.Info("g_Player: ended");
            _player.SafeDispose();
            _player = null;
            _subs = null;
            UnableToPlay(strFile, type);
          }
          else if (_player.Playing)
          {
            _isInitialized = false;
            _currentFilePlaying = _player.CurrentFile;
            //if (_chapters == null)
            //{
            //  _chapters = _player.Chapters;
            //}
            if (_chaptersname == null)
            {
              _chaptersname = _player.ChaptersName;
            }
            OnStarted();
          }

          // Set bool to know if video if played from MyPictures
          if (fromPictures)
          {
            IsPicture = true;
          }

          return bResult;
        }
      }
      finally
      {
        Starting = false;
      }
      UnableToPlay(strFile, type);
      return false;
    }
예제 #4
0
    public static void UnableToPlay(string FileName, MediaType type)
    {
      try
      {
        bool playingRemoteUrl = Util.Utils.IsRemoteUrl(FileName);
        if (_mediaInfo == null && !playingRemoteUrl)
          _mediaInfo = new MediaInfoWrapper(FileName);

        GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_CODEC_MISSING, 0, 0, 0, 0, 0, null);
        msg.Label = string.Format("{0}: {1}", GUILocalizeStrings.Get(1451), Util.Utils.GetFilename(FileName));
        msg.Label2 = _mediaInfo == null || string.IsNullOrEmpty(_mediaInfo.VideoCodec)
                       ? string.Empty
                       : string.Format("Video codec: {0}", _mediaInfo.VideoCodec);
        msg.Label3 = _mediaInfo == null || string.IsNullOrEmpty(_mediaInfo.AudioCodec)
                       ? string.Empty
                       : string.Format("Audio codec: {0}", _mediaInfo.AudioCodec);
        GUIGraphicsContext.SendMessage(msg);
        _mediaInfo = null;
      }
      catch (Exception ex)
      {
        Log.Error("g_player: Error notifying user about unsuccessful playback of {0} - {1}", FileName, ex.ToString());
      }
    }
예제 #5
0
    // GUIMusicVideos and GUITRailer called this function, altough they want to play a Video.
    // When BASS is enabled this resulted in no Picture being shown. they should now indicate that a Video is to be played.
    public static bool PlayAudioStream(string strURL, bool isMusicVideo)
    {
      try
      {
        _mediaInfo = null;
        string strAudioPlayer = string.Empty;
        using (Settings xmlreader = new MPSettings())
        {
          strAudioPlayer = xmlreader.GetValueAsString("audioplayer", "player", "Internal dshow player");
        }
        Starting = true;
        //stop radio
        GUIMessage msgRadio = new GUIMessage(GUIMessage.MessageType.GUI_MSG_RECORDER_STOP_RADIO, 0, 0, 0, 0, 0, null);
        GUIWindowManager.SendMessage(msgRadio);
        PlayListType currentList = PlayListPlayer.SingletonPlayer.CurrentPlaylistType;
        if (isMusicVideo)
        {
          // Clear any temp. playlists before starting playback
          if (currentList == PlayListType.PLAYLIST_MUSIC_TEMP || currentList == PlayListType.PLAYLIST_VIDEO_TEMP)
          {
            PlayListPlayer.SingletonPlayer.GetPlaylist(currentList).Clear();
            PlayListPlayer.SingletonPlayer.Reset();
          }
        }
        //stop timeshifting tv
        //GUIMessage msgTv = new GUIMessage(GUIMessage.MessageType.GUI_MSG_RECORDER_STOP_TIMESHIFT, 0, 0, 0, 0, 0, null);
        //GUIWindowManager.SendMessage(msgTv);
        _currentStep = 0;
        _currentStepIndex = -1;
        _seekTimer = DateTime.MinValue;
        _isInitialized = true;
        _subs = null;
        Log.Info("g_Player.PlayAudioStream({0})", strURL);
        if (_player != null)
        {
          GUIGraphicsContext.ShowBackground = true;
          OnChanged(strURL);
          OnStopped();
          if (_player != null)
          {
            _player.Stop();
          }
          CachePlayer();
          GUIGraphicsContext.form.Invalidate(true);
          _player = null;
        }

        if (strAudioPlayer == "BASS engine" && !isMusicVideo)
        {
          if (BassMusicPlayer.BassFreed)
          {
            BassMusicPlayer.Player.InitBass();
          }
          _player = BassMusicPlayer.Player;
        }
        else
        {
          _player = new AudioPlayerWMP9();
        }
        _player = CachePreviousPlayer(_player);
        bool bResult = _player.Play(strURL);
        if (!bResult)
        {
          Log.Info("player:ended");
          _player.SafeDispose();
          _player = null;
          _subs = null;
          GC.Collect();
          GC.Collect();
          GC.Collect();
        }
        else if (_player.Playing)
        {
          _currentFilePlaying = _player.CurrentFile;
          OnStarted();
        }
        _isInitialized = false;
        if (!bResult)
        {
          UnableToPlay(strURL, MediaType.Unknown);
        }
        return bResult;
      }
      finally
      {
        Starting = false;
      }
    }
예제 #6
0
    public static bool PlayVideoStream(string strURL, string streamName)
    {
      try
      {
        _mediaInfo = null;
        Starting = true;
        //stop radio
        GUIMessage msgRadio = new GUIMessage(GUIMessage.MessageType.GUI_MSG_RECORDER_STOP_RADIO, 0, 0, 0, 0, 0, null);
        GUIWindowManager.SendMessage(msgRadio);
        _currentStep = 0;
        _currentStepIndex = -1;
        _seekTimer = DateTime.MinValue;
        if (string.IsNullOrEmpty(strURL))
        {
          UnableToPlay(strURL, MediaType.Unknown);
          return false;
        }

        _isInitialized = true;
        _subs = null;
        Log.Info("g_Player.PlayVideoStream({0})", strURL);
        if (_player != null)
        {
          GUIGraphicsContext.ShowBackground = true;
          OnChanged(strURL);
          OnStopped();
          if (_player != null)
          {
            _player.Stop();
          }
          CachePlayer();
          GUIGraphicsContext.form.Invalidate(true);
          _player = null;
          GC.Collect();
          GC.Collect();
          GC.Collect();
          GC.Collect();
        }

        //int iUseVMR9inMYMovies = 0;
        //using (MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.MPSettings())
        //{
        //  iUseVMR9inMYMovies = xmlreader.GetValueAsInt("movieplayer", "vmr9", 1);
        //}
        //if (iUseVMR9inMYMovies == 0)
        //  _player = new Player.VideoPlayerVMR7();
        //else
        _player = new VideoPlayerVMR9();
        _player = CachePreviousPlayer(_player);
        bool isPlaybackPossible;
        if (streamName != null)
        {
          if (streamName != "")
          {
            isPlaybackPossible = _player.PlayStream(strURL, streamName);
          }
          else
          {
            isPlaybackPossible = _player.Play(strURL);
          }
        }
        else
        {
          isPlaybackPossible = _player.Play(strURL);
        }
        if (!isPlaybackPossible)
        {
          Log.Info("player:ended");
          _player.SafeDispose();
          _player = null;
          _subs = null;
          GC.Collect();
          GC.Collect();
          GC.Collect();
          //2nd try
          _player = new VideoPlayerVMR9();
          isPlaybackPossible = _player.Play(strURL);
          if (!isPlaybackPossible)
          {
            Log.Info("player2:ended");
            _player.SafeDispose();
            _player = null;
            _subs = null;
            GC.Collect();
            GC.Collect();
            GC.Collect();
          }
        }
        else if (_player.Playing)
        {
          _currentFilePlaying = _player.CurrentFile;
          OnStarted();
        }
        _isInitialized = false;
        if (!isPlaybackPossible)
        {
          UnableToPlay(strURL, MediaType.Unknown);
        }
        return isPlaybackPossible;
      }
      finally
      {
        Starting = false;
      }
    }
    /// <summary>
    /// Total video duration in seconds (single or multiple -> stacked file(s))
    /// Also sets duration into videodatabase (movie table) -> full lenght with stacked parts
    /// Parameter refresh force duration update even if data is in the videodatabase
    /// </summary>
    /// <param name="files"></param>
    /// <param name="refresh"></param>
    /// <returns></returns>
    public static int MovieDuration(ArrayList files, bool refresh)
    {
      TotalMovieDuration = 0;

      if (files == null || files.Count == 0)
      {
        return TotalMovieDuration;
      }

      try
      {
        foreach (string file in files)
        {
          int fileID = VideoDatabase.GetFileId(file);
          int tempDuration = VideoDatabase.GetVideoDuration(fileID);

          if (tempDuration > 0 && !refresh)
          {
            TotalMovieDuration += tempDuration;
          }
          else
          {
            MediaInfoWrapper mInfo = new MediaInfoWrapper(file);

            if (fileID > -1)
            {
              // Set video file duration
              VideoDatabase.SetVideoDuration(fileID, mInfo.VideoDuration / 1000);
              TotalMovieDuration += mInfo.VideoDuration / 1000;
            }
          }
        }
        // Set movie duration
        VideoDatabase.SetMovieDuration(VideoDatabase.GetMovieId(files[0].ToString()), TotalMovieDuration);
      }
      catch (Exception)
      {
      }

      return TotalMovieDuration;
    }
예제 #8
0
    public static bool Play(string strFile, MediaType type, TextReader chapters, bool fromPictures, int title, bool forcePlay, bool fromExtTS)
    {
      try
      {
        if (string.IsNullOrEmpty(strFile))
        {
          Log.Error("g_Player.Play() called without file attribute");
          return false;
        }

        g_Player.SetResumeBDTitleState = title;

        IsPicture = false;
        IsExtTS = false;
        bool AskForRefresh = true;
        bool playingRemoteUrl = Util.Utils.IsRemoteUrl(strFile);
        string extension = Util.Utils.GetFileExtension(strFile).ToLowerInvariant();
        bool isImageFile = !playingRemoteUrl && Util.VirtualDirectory.IsImageFile(extension);
        if (isImageFile)
        {
          if (!File.Exists(Util.DaemonTools.GetVirtualDrive() + @"\VIDEO_TS\VIDEO_TS.IFO"))
            if (!File.Exists(Util.DaemonTools.GetVirtualDrive() + @"\BDMV\index.bdmv"))
            {
              _currentFilePlaying = strFile;
              MediaPortal.Ripper.AutoPlay.ExamineCD(Util.DaemonTools.GetVirtualDrive(), true);
              return true;
            }
        }

        if (!playingRemoteUrl) // MediaInfo can only be used on files (local or SMB)
        {
          if (currentMediaInfoFilePlaying != strFile)
          {
          _mediaInfo = new MediaInfoWrapper(strFile);
            currentMediaInfoFilePlaying = strFile;
        }
        }

        // back to previous Windows if we are only in video fullscreen to do a proper release when next item is music only
        if (((GUIWindow.Window) (Enum.Parse(typeof (GUIWindow.Window), GUIWindowManager.ActiveWindow.ToString())) ==
             GUIWindow.Window.WINDOW_FULLSCREEN_VIDEO) && !MediaInfo.hasVideo && type == MediaType.Music)
        {
          GUIWindowManager.ShowPreviousWindow();
        }

        Starting = true;
        _currentStep = 0;
        _currentStepIndex = -1;
        _seekTimer = DateTime.MinValue;
        _isInitialized = true;
        _subs = null;

        if (_player != null)
        {
          GUIGraphicsContext.ShowBackground = true;
          OnChanged(strFile);
          OnStopped();
          bool doStop = true;
          if (type != MediaType.Video && Util.Utils.IsAudio(strFile))
          {
            if (type == MediaType.Unknown)
            {
              type = MediaType.Music;
            }
            if (MediaInfo != null && MediaInfo.hasVideo && type == MediaType.Music)
            {
              type = MediaType.Video;
            }
            if (BassMusicPlayer.IsDefaultMusicPlayer && BassMusicPlayer.Player.Playing && type != MediaType.Video)
            {
              doStop = !BassMusicPlayer.Player.CrossFadingEnabled;
            }
          }

          // Set currentMedia needed for correct detection when BASS Engine is doing a Stop
          _currentMediaForBassEngine = type;

          if (doStop)
          {
            if (_player != null)
            {
              _player.Stop();
              
              if (BassMusicPlayer.IsDefaultMusicPlayer && type != MediaType.Music)
              {
                // This would be better to be handled in a new Stop() parameter, but it would break the interface compatibility
                BassMusicPlayer.Player.FreeBass();
              }
            }

            CachePlayer();
            _player = null;
          }
        }

        if (!playingRemoteUrl && Util.Utils.IsDVD(strFile))
        {
          ChangeDriveSpeed(strFile, DriveType.CD);
        }

        if (MediaInfo != null && MediaInfo.hasVideo && type == MediaType.Music)
        {
          type = MediaType.Video;
        }

        if ((!playingRemoteUrl && Util.Utils.IsVideo(strFile)) || Util.Utils.IsLiveTv(strFile) ||
            Util.Utils.IsRTSP(strFile)) //local video, tv, rtsp
        {
          if (type == MediaType.Unknown)
          {
            Log.Debug("g_Player.Play - Mediatype Unknown, forcing detection as Video");
            type = MediaType.Video;
          }
          if (type != MediaType.Music)
          {
            using (MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.MPSettings())
            {
              _BDInternalMenu = xmlreader.GetValueAsBool("bdplayer", "useInternalBDPlayer", true);
            }
            if (_BDInternalMenu && extension == ".bdmv")
            {
              AskForRefresh = false;
            }
            if (AskForRefresh)
            {
              // Refreshrate change done here. Blu-ray player will handle the refresh rate changes by itself
              // Identify if it's a video
              if (strFile.IndexOf(@"\BDMV\INDEX.BDMV") == -1 && type != MediaType.Radio)
              {
                // Make a double check on .ts because it can be recorded TV or Radio
                if (extension == ".ts")
                {
                  if (MediaInfo != null && MediaInfo.hasVideo)
                  {
                    RefreshRateChanger.AdaptRefreshRate(strFile, (RefreshRateChanger.MediaType)(int)type);
                  }
                }
                else
                {
                  RefreshRateChanger.AdaptRefreshRate(strFile, (RefreshRateChanger.MediaType)(int)type);
                }
              }
            }
          }

          if (RefreshRateChangePending())
          {
            return true;
          }

          // Set bool to know if we want to use video codec for .ts files
          if (fromExtTS)
          {
            IsExtTS = true;
          }
          // Set bool to know if video if we force play
          if (forcePlay)
          {
            ForcePlay = true;
          }
          else
          {
            ForcePlay = false;
          }
        }

        // Set currentMedia needed for correct detection when BASS Engine is doing a Stop
        _currentMediaForBassEngine = type;

        Log.Info("g_Player.Play({0} {1})", strFile, type);
        if (!playingRemoteUrl && Util.Utils.IsVideo(strFile) && type != MediaType.Music)
        {
          if (!Util.Utils.IsRTSP(strFile) && extension != ".ts") // do not play recorded tv with external player
          {
            using (MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.MPSettings())
            {
              bool bInternal = xmlreader.GetValueAsBool("movieplayer", "internal", true);
              bool bInternalDVD = xmlreader.GetValueAsBool("dvdplayer", "internal", true);

              // check if we are running from Images / Discs
              string pathRoot = Path.GetPathRoot(strFile);
              if (Util.Utils.getDriveType(pathRoot) == 5 && !bInternalDVD)
              {
                bInternalDVD = false;
              }
              else
              {
                bInternalDVD = true;
              }

              // External player extension filter
              _externalPlayerExtensions = xmlreader.GetValueAsString("movieplayer", "extensions", "");
              if (!bInternal && !string.IsNullOrEmpty(_externalPlayerExtensions) &&
                  extension != ".ifo" && extension != ".vob" && extension != ".bdmv" && !Util.Utils.IsDVDImage(strFile))
              {
                // Do not use external player if file ext is not in the extension list
                if (!CheckExtension(strFile))
                  bInternal = true;
              }

              if ((!bInternalDVD && !isImageFile && (extension == ".ifo" || extension == ".vob" || extension == ".bdmv")) ||
                  (!bInternalDVD && isImageFile && Util.Utils.IsDVDImage(strFile)) ||
                  // No image and no DVD folder rips
                  (!bInternal && !isImageFile && extension != ".ifo" && extension != ".vob" && extension != ".bdmv") ||
                  // BluRay image
                  (!bInternal && isImageFile && Util.Utils.IsBDImage(strFile))) // external player used
              {
                if (isImageFile)
                {
                  // Check for DVD ISO
                  strFile = Util.DaemonTools.GetVirtualDrive() + @"\VIDEO_TS\VIDEO_TS.IFO";
                  if (!File.Exists(strFile))
                  {
                    // Check for BluRayISO
                    strFile = Util.DaemonTools.GetVirtualDrive() + (@"\BDMV\index.bdmv");
                    if (!File.Exists(strFile))
                      return false;
                  }
                }
                // Do refresh rate
                RefreshRateChanger.AdaptRefreshRate(strFile, (RefreshRateChanger.MediaType)(int)type);

                if (RefreshRateChangePending())
                {
                  return true;
                }

                if (Util.Utils.PlayMovie(strFile))
                {
                  if (MediaInfo != null && MediaInfo.hasVideo)
                  {
                    RefreshRateChanger.AdaptRefreshRate();
                  }
                  return true;
                }
                else // external player error
                {
                  UnableToPlay(strFile, type);
                  return false;
                }
              }
            }
          }
        }
        // Still for BDISO strFile = ISO filename, convert it
        if (!playingRemoteUrl) Util.Utils.IsBDImage(strFile, ref strFile);

        _currentFileName = strFile;
        _player = _factory.Create(strFile, type);

        if (_player != null)
        {
          if (chapters != null)
          {
            LoadChapters(chapters);
          }
          else
          {
            if (!playingRemoteUrl) LoadChapters(strFile);
          }
          _player = CachePreviousPlayer(_player);
          bool bResult = _player.Play(strFile);
          if (!bResult)
          {
            Log.Info("g_Player: ended");
            _player.SafeDispose();
            _player = null;
            _subs = null;
            UnableToPlay(strFile, type);
          }
          else if (_player != null && _player.Playing)
          {
            _isInitialized = false;
            _currentFilePlaying = _player.CurrentFile;
            //if (_chapters == null)
            //{
            //  _chapters = _player.Chapters;
            //}
            if (_chaptersname == null)
            {
              _chaptersname = _player.ChaptersName;
            }
            OnStarted();
          }

          // Set bool to know if video if played from MyPictures
          if (fromPictures)
          {
            IsPicture = true;
          }

          // Set bool to know if video if we force play
          if (forcePlay)
          {
            ForcePlay = true;
          }
          else
          {
            ForcePlay = false;
          }
          return bResult;
        }
      }
      finally
      {
        _currentMediaForBassEngine = _currentMedia;
        currentMediaInfoFilePlaying = "";
        Starting = false;
      }
      UnableToPlay(strFile, type);
      return false;
    }
예제 #9
0
    private static string GetAspectRatio(string FileName)
    {
      try
      {
        var minfo = new MediaInfoWrapper(FileName);

        LogMyFilms.Debug("Mediainfo width: " + minfo.Width.ToString());
        LogMyFilms.Debug("Mediainfo height: " + minfo.Height.ToString());
        //ToDo: Calculate aspect ratio here...

        return minfo.AspectRatio;
      }
      catch (Exception ex)
      {
        LogMyFilms.Error("GetAspectRatio: Error getting aspectratio via mediainfo.dll - Exception: " + ex.ToString());
      }
      return "";
    }
예제 #10
0
 //called when current playing file is stopped
 private static void OnStopped()
 {
   //check if we're playing
   if (Playing && PlayBackStopped != null)
   {
     //yes, then raise event
     Log.Info("g_Player.OnStopped()");
     if (PlayBackStopped != null)
     {
       if ((_currentMedia == MediaType.TV || _currentMedia == MediaType.Video || _currentMedia == MediaType.Recording))
       {
         RefreshRateChanger.AdaptRefreshRate();
       }
       // Check if we play image file to search db with the proper filename
       if (Util.Utils.IsISOImage(currentFileName))
       {
         currentFileName = DaemonTools.MountedIsoFile;
       }
       PlayBackStopped(_currentMedia, (int)CurrentPosition,
                       (!String.IsNullOrEmpty(currentFileName) ? currentFileName : CurrentFile));
       currentFileName = String.Empty;
       _mediaInfo = null;
     }
   }
 }
예제 #11
0
        /// <summary>
        /// Initialize the system (Objects, Controls etc.)
        /// </summary>
        /// <param name="isVideo">Indícate if the file has video</param>
        private void InitSystem(bool isVideo)
        {
            _mediaInfo = new MediaInfoWrapper(_currentFile);

              _playState = PlayState.Playing;
              if (_configManager.OsdMode == OSDMode.InternalMPlayer || !isVideo)
              {
            _osdHandler = new InternalOSDHandler(this, true);
              }
              else if (_configManager.OsdMode == OSDMode.ExternalOSDLibrary)
              {
            _osdHandler = new ExternalOSDLibrary(this);
              }
              _videoHandler = new VideoHandler(this, _osdHandler);
              _audioSubtitleHandler = new AudioSubtitleHandler(this, _osdHandler);
              _seekingHandler = new SeekingHandler(this, _osdHandler);
              _messageHandlers = new List<IMessageHandler> { _videoHandler, _audioSubtitleHandler, _seekingHandler, _osdHandler };
              _actionHandler = OnNewAction;
              GUIWindowManager.OnNewAction += _actionHandler;
        }
예제 #12
0
 //called when current playing file ends
 public static void OnEnded()
 {
   //check if we're playing
   if (PlayBackEnded != null)
   {
     //yes, then raise event
     Log.Info("g_Player.OnEnded()");
     RefreshRateChanger.AdaptRefreshRate();
     PlayBackEnded(_currentMedia, (!String.IsNullOrEmpty(currentFileName) ? currentFileName : _currentFilePlaying));
     if (_player != null && _player.Playing)
     {
       // Don't reset currentFileName and _mediaInfo
     }
     else
     {
       currentFileName = String.Empty;
       _mediaInfo = null;
     }
   }
 }
예제 #13
0
    public static void UnableToPlay(string FileName, MediaType type)
    {
      try
      {
        bool playingRemoteUrl = Util.Utils.IsRemoteUrl(FileName);
        if (_mediaInfo == null && !playingRemoteUrl)
        {
          _mediaInfo = new MediaInfoWrapper(FileName);
        }

        GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_CODEC_MISSING, 0, 0, 0, 0, 0, null);
        msg.Label = string.Format("{0}: {1}", GUILocalizeStrings.Get(1451), Util.Utils.GetFilename(FileName));
        msg.Label2 = _mediaInfo == null || string.IsNullOrEmpty(_mediaInfo.VideoCodec)
                       ? string.Empty
                       : string.Format("Video codec: {0}", _mediaInfo.VideoCodec);
        msg.Label3 = _mediaInfo == null || string.IsNullOrEmpty(_mediaInfo.AudioCodec)
                       ? string.Empty
                       : string.Format("Audio codec: {0}", _mediaInfo.AudioCodec);
        GUIGraphicsContext.SendMessage(msg);
        _mediaInfo = null;
        PlayListType currentList = PlayListPlayer.SingletonPlayer.CurrentPlaylistType;
        if (type == MediaType.Music)
        {
          // Clear music playlists when failed to play.
          if (currentList == PlayListType.PLAYLIST_MUSIC)
          {
            PlayListPlayer.SingletonPlayer.GetPlaylist(currentList).Clear();
            PlayListPlayer.SingletonPlayer.Reset();
          }
        }
      }
      catch (Exception ex)
      {
        Log.Error("g_player: Error notifying user about unsuccessful playback of {0} - {1}", FileName, ex.ToString());
      }
    }
예제 #14
0
    public static int MovieDuration(ArrayList files)
    {
      _totalMovieDuration = 0;

      foreach (string file in files)
      {
        int fileID = VideoDatabase.GetFileId(file);
        int tempDuration = VideoDatabase.GetMovieDuration(fileID);

        if (tempDuration > 0)
        {
          _totalMovieDuration += tempDuration;
        }
        else
        {
          MediaInfoWrapper mInfo = new MediaInfoWrapper(file);

          if (fileID > -1)
            VideoDatabase.SetMovieDuration(fileID, mInfo.VideoDuration / 1000);
          _totalMovieDuration += mInfo.VideoDuration / 1000;
        }
      }
      return _totalMovieDuration;
    }
예제 #15
0
    /// <summary> create the used COM components and get the interfaces. </summary>
    protected override bool GetInterfaces()
    {
      GetInterface = true;
      try
      {
        graphBuilder = (IGraphBuilder) new FilterGraph();
        _rotEntry = new DsROTEntry((IFilterGraph) graphBuilder);
        // add preferred video & audio codecs
        int hr;
        filterConfig = GetFilterConfiguration();
        //Get filterCodecName
        filterCodec = GetFilterCodec();

        if (filterConfig.bAutoDecoderSettings)
        {
          AutoRenderingCheck = true;
          return AutoRendering(this.filterConfig.wmvAudio);
        }

        string extension = Path.GetExtension(m_strCurrentFile).ToLowerInvariant();

        //Get video/audio Info
        _mediaInfo = new MediaInfoWrapper(m_strCurrentFile);

        //Manually add codecs based on file extension if not in auto-settings
        // switch back to directx fullscreen mode
        Log.Info("VideoPlayer9: Enabling DX9 exclusive mode");
        GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SWITCH_FULL_WINDOWED, 0, 0, 0, 1, 0, null);
        GUIWindowManager.SendMessage(msg);

        // add the VMR9 in the graph
        // after enabeling exclusive mode, if done first it causes MediPortal to minimize if for example the "Windows key" is pressed while playing a video
        Vmr9 = new VMR9Util();
        if (File.Exists(m_strCurrentFile) && extension != ".dts" && extension != ".mp3" && extension != ".mka" && extension != ".ac3")
        {
          Vmr9.AddVMR9(graphBuilder);
          Vmr9.Enable(false);
        }
        else
        {
          AudioOnly = true;
        }

        if (extension == ".mpls" || extension == ".bdmv")
          filterConfig.bForceSourceSplitter = false;

        if (filterConfig.strsplitterfilter == LAV_SPLITTER_FILTER_SOURCE && filterConfig.bForceSourceSplitter)
        {
          LoadLAVSplitter(LAV_SPLITTER_FILTER_SOURCE);
          hr = graphBuilder.AddFilter(_interfaceSourceFilter, LAV_SPLITTER_FILTER_SOURCE);
          DsError.ThrowExceptionForHR(hr);

          Log.Debug("VideoPlayer9: Add LAVSplitter Source to graph");

          IFileSourceFilter interfaceFile = (IFileSourceFilter)_interfaceSourceFilter;
          hr = interfaceFile.Load(m_strCurrentFile, null);

          if (hr != 0)
          {
            Error.SetError("Unable to play movie", "Unable build graph for VMR9");
            Cleanup();
            return false;
          }
        }
        else
        {
          _interfaceSourceFilter = filterConfig.bForceSourceSplitter
                                     ? DirectShowUtil.AddFilterToGraph(graphBuilder, filterConfig.strsplitterfilter)
                                     : null;
          if (_interfaceSourceFilter == null && !filterConfig.bForceSourceSplitter)
          {
            graphBuilder.AddSourceFilter(m_strCurrentFile, null, out _interfaceSourceFilter);
          }
          else
          {
            try
            {
              int result = ((IFileSourceFilter) _interfaceSourceFilter).Load(m_strCurrentFile, null);
              if (result != 0)
              {
                graphBuilder.RemoveFilter(_interfaceSourceFilter);
                DirectShowUtil.ReleaseComObject(_interfaceSourceFilter);
                _interfaceSourceFilter = null;
                graphBuilder.AddSourceFilter(m_strCurrentFile, null, out _interfaceSourceFilter);
              }
            }

            catch (Exception ex)
            {
              Log.Error(
                "VideoPlayer9: Exception loading Source Filter setup in setting in DShow graph , try to load by merit",
                ex);
              graphBuilder.RemoveFilter(_interfaceSourceFilter);
              DirectShowUtil.ReleaseComObject(_interfaceSourceFilter);
              _interfaceSourceFilter = null;
              graphBuilder.AddSourceFilter(m_strCurrentFile, null, out _interfaceSourceFilter);
            }
          }

          //Detection of File Source (Async.) as source filter, return true if found
          IBaseFilter fileSyncbaseFilter = null;
          DirectShowUtil.FindFilterByClassID(graphBuilder, ClassId.FilesyncSource, out fileSyncbaseFilter);
          if (fileSyncbaseFilter == null)
            graphBuilder.FindFilterByName("File Source (Async.)", out fileSyncbaseFilter);
          if (fileSyncbaseFilter != null && filterConfig.bForceSourceSplitter)
          {
            FileSync = true;
            DirectShowUtil.ReleaseComObject(fileSyncbaseFilter);
            fileSyncbaseFilter = null;
            if (filterConfig.strsplitterfilefilter == LAV_SPLITTER_FILTER)
            {
              LoadLAVSplitter(LAV_SPLITTER_FILTER);
              hr = graphBuilder.AddFilter(Splitter, LAV_SPLITTER_FILTER);
              DsError.ThrowExceptionForHR(hr);

              Log.Debug("VideoPlayer9: Add LAVSplitter to graph");

              if (hr != 0)
              {
                Error.SetError("Unable to play movie", "Unable build graph for VMR9");
                Cleanup();
                return false;
              }
            }
            else
            {
              Splitter = DirectShowUtil.AddFilterToGraph(graphBuilder, filterConfig.strsplitterfilefilter);
            }
          }
        }

        // Add preferred video filters
        UpdateFilters("Video");

        //Add Audio Renderer
        if (filterConfig.AudioRenderer.Length > 0 && filterCodec._audioRendererFilter == null)
        {
          filterCodec._audioRendererFilter = DirectShowUtil.AddAudioRendererToGraph(graphBuilder,
                                                                                    filterConfig.AudioRenderer, false);
        }

        #region load external audio streams

        // check if current "File" is a file... it could also be a URL
        // Directory.Getfiles, ... will other give us an exception
        if (File.Exists(m_strCurrentFile) && !AudioOnly)
        {
          //load audio file (ac3, dts, mka, mp3) only with if the name matches partially with video file.
          string[] audioFiles = Directory.GetFiles(Path.GetDirectoryName(m_strCurrentFile),
                                                   Path.GetFileNameWithoutExtension(m_strCurrentFile) + "*.*");
          bool audioSwitcherLoaded = false;
          foreach (string file in audioFiles)
          {
            switch (Path.GetExtension(file))
            {
              case ".mp3":
              case ".dts":
              case ".mka":
              case ".ac3":
                if (!audioSwitcherLoaded)
                {
                  IBaseFilter switcher = DirectShowUtil.GetFilterByName(graphBuilder, MEDIAPORTAL_AUDIOSWITCHER_FILTER);
                  if (switcher != null)
                  {
                    DirectShowUtil.ReleaseComObject(switcher);
                    switcher = null;
                  }
                  else
                  {
                    _audioSwitcher = DirectShowUtil.AddFilterToGraph(graphBuilder, MEDIAPORTAL_AUDIOSWITCHER_FILTER);
                  }
                  audioSwitcherLoaded = true;
                }
                _AudioSourceFilter = DirectShowUtil.AddFilterToGraph(graphBuilder, FILE_SYNC_FILTER);
                int result = ((IFileSourceFilter) _AudioSourceFilter).Load(file, null);

                //Force using LAVFilter
                _AudioExtSplitterFilter = DirectShowUtil.AddFilterToGraph(graphBuilder, LAV_SPLITTER_FILTER);

                if (result != 0 || _AudioExtSplitterFilter == null)
                {
                  if (_AudioSourceFilter != null)
                  {
                    graphBuilder.RemoveFilter(_AudioSourceFilter);
                    DirectShowUtil.ReleaseComObject(_AudioSourceFilter);
                    _AudioSourceFilter = null;
                  }
                  if (_AudioExtSplitterFilter != null)
                  {
                    graphBuilder.RemoveFilter(_AudioExtSplitterFilter);
                    DirectShowUtil.ReleaseComObject(_AudioExtSplitterFilter);
                    _AudioExtSplitterFilter = null;
                  }
                  //Trying Add Audio decoder in graph
                  AddFilterToGraphAndRelease(filterConfig.Audio);
                  graphBuilder.RenderFile(file, string.Empty);
                  Log.Debug("VideoPlayerVMR9 : External audio file loaded \"{0}\"", file);
                  AudioExternal = true;
                  break;
                }

                //Add Audio decoder in graph
                _AudioExtFilter = DirectShowUtil.AddFilterToGraph(graphBuilder, filterConfig.Audio);

                //Connect Filesource with the splitter
                IPin pinOutAudioExt1 = DsFindPin.ByDirection((IBaseFilter) _AudioSourceFilter, PinDirection.Output, 0);
                IPin pinInAudioExt2 = DsFindPin.ByDirection((IBaseFilter) _AudioExtSplitterFilter, PinDirection.Input, 0);
                hr = graphBuilder.Connect(pinOutAudioExt1, pinInAudioExt2);

                //Connect Splitter with the Audio Decoder
                IPin pinOutAudioExt3 = DsFindPin.ByDirection((IBaseFilter) _AudioExtSplitterFilter, PinDirection.Output,
                                                             0);
                IPin pinInAudioExt4 = DsFindPin.ByDirection((IBaseFilter) _AudioExtFilter, PinDirection.Input, 0);
                hr = graphBuilder.Connect(pinOutAudioExt3, pinInAudioExt4);

                //Render outpin from Audio Decoder
                DirectShowUtil.RenderUnconnectedOutputPins(graphBuilder, _AudioExtFilter);

                //Cleanup External Audio (Release)
                if (_AudioSourceFilter != null)
                {
                  DirectShowUtil.ReleaseComObject(_AudioSourceFilter);
                  _AudioSourceFilter = null;
                }
                if (_AudioExtSplitterFilter != null)
                {
                  DirectShowUtil.ReleaseComObject(_AudioExtSplitterFilter);
                  _AudioExtSplitterFilter = null;
                }
                if (_AudioExtFilter != null)
                {
                  DirectShowUtil.ReleaseComObject(_AudioExtFilter);
                  _AudioExtFilter = null;
                }
                if (pinOutAudioExt1 != null)
                {
                  DirectShowUtil.ReleaseComObject(pinOutAudioExt1);
                  pinOutAudioExt1 = null;
                }
                if (pinInAudioExt2 != null)
                {
                  DirectShowUtil.ReleaseComObject(pinInAudioExt2);
                  pinInAudioExt2 = null;
                }
                if (pinOutAudioExt3 != null)
                {
                  DirectShowUtil.ReleaseComObject(pinOutAudioExt3);
                  pinOutAudioExt3 = null;
                }
                if (pinInAudioExt4 != null)
                {
                  DirectShowUtil.ReleaseComObject(pinInAudioExt4);
                  pinInAudioExt4 = null;
                }

                Log.Debug("VideoPlayerVMR9 : External audio file loaded \"{0}\"", file);
                AudioExternal = true;
                break;
            }
          }
        }

        #endregion

        // Add preferred audio filters
        UpdateFilters("Audio");

        #region Set High Audio

        //Set High Resolution Output > 2 channels
        IBaseFilter baseFilter = null;
        bool FFDShowLoaded = false;
        graphBuilder.FindFilterByName("WMAudio Decoder DMO", out baseFilter);
        if (baseFilter != null && filterConfig.wmvAudio != false) //Also check configuration option enabled
        {
          //Set the filter setting to enable more than 2 audio channels
          const string g_wszWMACHiResOutput = "_HIRESOUTPUT";
          object val = true;
          IPropertyBag propBag = (IPropertyBag) baseFilter;
          hr = propBag.Write(g_wszWMACHiResOutput, ref val);
          if (hr != 0)
          {
            Log.Info("VideoPlayer9: Unable to turn WMAudio multichannel on. Reason: {0}", hr);
          }
          else
          {
            Log.Info("VideoPlayer9: WMAudio Decoder now set for > 2 audio channels");
          }
          if (!FFDShowLoaded)
          {
            IBaseFilter FFDShowAudio = DirectShowUtil.GetFilterByName(graphBuilder, FFDSHOW_AUDIO_DECODER_FILTER);
            if (FFDShowAudio != null)
            {
              DirectShowUtil.ReleaseComObject(FFDShowAudio);
              FFDShowAudio = null;
            }
            else
            {
              _FFDShowAudio = DirectShowUtil.AddFilterToGraph(graphBuilder, FFDSHOW_AUDIO_DECODER_FILTER);
            }
            FFDShowLoaded = true;
          }
          DirectShowUtil.ReleaseComObject(baseFilter);
          baseFilter = null;
        }

        #endregion

        if (_interfaceSourceFilter != null)
        {
          DirectShowUtil.RenderGraphBuilderOutputPins(graphBuilder, _interfaceSourceFilter);
        }

        //Test and remove orphelin Audio Renderer
        //RemoveAudioR();

        //remove InternalScriptRenderer as it takes subtitle pin
        disableISR();

        //disable Closed Captions!
        disableCC();

        DirectShowUtil.RemoveUnusedFiltersFromGraph(graphBuilder);

        //remove orphelin audio renderer
        RemoveAudioR();

        //EnableClock();

        if (Vmr9 == null || !Vmr9.IsVMR9Connected && !AudioOnly)
        {
          Log.Error("VideoPlayer9: Failed to render file -> vmr9");
          mediaCtrl = null;
          Cleanup();
          return false;
        }

        mediaCtrl = (IMediaControl) graphBuilder;
        mediaEvt = (IMediaEventEx) graphBuilder;
        mediaSeek = (IMediaSeeking) graphBuilder;
        mediaPos = (IMediaPosition) graphBuilder;
        basicAudio = (IBasicAudio) graphBuilder;
        videoWin = (IVideoWindow) graphBuilder;
        m_iVideoWidth = Vmr9.VideoWidth;
        m_iVideoHeight = Vmr9.VideoHeight;
        Vmr9.SetDeinterlaceMode();
        return true;
      }
      catch (Exception ex)
      {
        Error.SetError("Unable to play movie", "Unable build graph for VMR9");
        Log.Error("VideoPlayer9: Exception while creating DShow graph {0} {1}", ex.Message, ex.StackTrace);
        Cleanup();
        return false;
      }
    }
예제 #16
0
    // Check and add, if necessary, media info for video files
    // Use (file, pathID and fileID) or (full filename with path and fileID)
    private void CheckMediaInfo(string file, string fullPathFilename, int pathID, int fileID, bool refresh)
    {
      string strSQL = string.Empty;
      string strFilenameAndPath = string.Empty;

      // Get path name from pathID
      strSQL = String.Format("SELECT * FROM path WHERE idPath={0}", pathID);
      SQLiteResultSet results = m_db.Execute(strSQL);
      // No ftp or http videos
      string path = DatabaseUtility.Get(results, 0, "strPath");

      if (path.IndexOf("remote:") >= 0 || path.IndexOf("http:") >= 0)
      {
        return;
      }

      // We can use (path+file) or full path filename
      if (fullPathFilename == string.Empty)
      {
        strFilenameAndPath = path + file.Replace("''", "'");
      }
      else
      {
        strFilenameAndPath = fullPathFilename;
      }

      // Prevent empty database record for empty media scan
      if (!File.Exists(strFilenameAndPath))
      {
        return;
      }

      // Check if we processed file allready
      strSQL = String.Format("SELECT * FROM filesmediainfo WHERE idFile={0}", fileID);
      results = m_db.Execute(strSQL);

      if (results.Rows.Count == 0 || refresh)
      {
        Log.Info("VideoDatabase media info scanning file: {0}", strFilenameAndPath);
        bool isImage = false;
        string drive = string.Empty;
        bool daemonAutoPlay = false;
        string autoplayVideo = string.Empty;

        if (VirtualDirectory.IsImageFile(Path.GetExtension(strFilenameAndPath)))
        {
          if (!DaemonTools.IsMounted(strFilenameAndPath))
          {
            using (Settings xmlreader = new MPSettings())
            {
              daemonAutoPlay = xmlreader.GetValueAsBool("daemon", "askbeforeplaying", false);
              autoplayVideo = xmlreader.GetValueAsString("general", "autoplay_video", "Ask");
              xmlreader.SetValueAsBool("daemon", "askbeforeplaying", false);
              xmlreader.SetValue("general", "autoplay_video", "No");
            }

            if (!DaemonTools.Mount(strFilenameAndPath, out drive))
            {
              return;
            }
          }
          isImage = true;
        }

        MediaInfoWrapper mInfo = new MediaInfoWrapper(strFilenameAndPath);

        if (isImage && DaemonTools.IsMounted(strFilenameAndPath))
        {
          DaemonTools.UnMount();
          using (Settings xmlwriter = new MPSettings())
          {
            xmlwriter.SetValueAsBool("daemon", "askbeforeplaying", daemonAutoPlay);
            xmlwriter.SetValue("general", "autoplay_video", autoplayVideo);
          }
        }

        int subtitles = 0;

        if (mInfo.HasSubtitles)
        {
          subtitles = 1;
        }

        try
        {
          if (results.Rows.Count == 0)
          {
            strSQL = String.Format(
              "INSERT INTO filesmediainfo (idFile, videoCodec, videoResolution, aspectRatio, hasSubtitles, audioCodec, audioChannels) VALUES({0},'{1}','{2}','{3}',{4},'{5}','{6}')",
              fileID,
              Util.Utils.MakeFileName(mInfo.VideoCodec),
              mInfo.VideoResolution,
              mInfo.AspectRatio,
              subtitles,
              Util.Utils.MakeFileName(mInfo.AudioCodec),
              mInfo.AudioChannelsFriendly);
          }
          else
          {
            strSQL = String.Format(
              "UPDATE filesmediainfo SET videoCodec='{1}', videoResolution='{2}', aspectRatio='{3}', hasSubtitles='{4}', audioCodec='{5}', audioChannels='{6}' WHERE idFile={0}",
              fileID,
              Util.Utils.MakeFileName(mInfo.VideoCodec),
              mInfo.VideoResolution,
              mInfo.AspectRatio,
              subtitles,
              Util.Utils.MakeFileName(mInfo.AudioCodec),
              mInfo.AudioChannelsFriendly);
          }

          // Prevent empty record for future or unknown codecs
          if (mInfo.VideoCodec == string.Empty)
          {
            return;
          }

          m_db.Execute(strSQL);
          SetVideoDuration(fileID, mInfo.VideoDuration / 1000);
          ArrayList movieFiles = new ArrayList();
          int movieId = VideoDatabase.GetMovieId(strFilenameAndPath);
          VideoDatabase.GetFilesForMovie(movieId, ref movieFiles);
          SetMovieDuration(movieId, MovieDuration(movieFiles));

          //Update movie subtitle field
          strSQL = String.Format("UPDATE movie SET hasSubtitles={0} WHERE idMovie={1} ", subtitles, movieId);
          m_db.Execute(strSQL);
        }
        catch (ThreadAbortException)
        {
          // Will be logged in thread main code
        }
        catch (Exception) { }
      }
    }
예제 #17
0
    public static bool Play(string strFile, MediaType type, TextReader chapters)
    {
      try
      {
        if (string.IsNullOrEmpty(strFile))
        {
          Log.Error("g_Player.Play() called without file attribute");
          return false;
        }

        string extension = Path.GetExtension(strFile).ToLower();
        bool isImageFile = Util.VirtualDirectory.IsImageFile(extension);
        if (isImageFile)
        {
          if (!File.Exists(Util.DaemonTools.GetVirtualDrive() + @"\VIDEO_TS\VIDEO_TS.IFO"))
          {
            _currentFilePlaying = strFile;
            MediaPortal.Ripper.AutoPlay.ExamineCD(Util.DaemonTools.GetVirtualDrive(), true);
            return true;
          }
        }

        if (Util.Utils.IsDVD(strFile))
        {
          ChangeDriveSpeed(strFile, DriveType.CD);
        }

        _mediaInfo = new MediaInfoWrapper(strFile);
        Starting = true;

        if (Util.Utils.IsVideo(strFile) || Util.Utils.IsLiveTv(strFile)) //video, tv, rtsp
        {
          if (type == MediaType.Unknown)
          {
            Log.Debug("g_Player.Play - Mediatype Unknown, forcing detection as Video");
            type = MediaType.Video;
          }
          // refreshrate change done here.
          RefreshRateChanger.AdaptRefreshRate(strFile, (RefreshRateChanger.MediaType)(int)type);

          if (RefreshRateChanger.RefreshRateChangePending)
          {
            TimeSpan ts = DateTime.Now - RefreshRateChanger.RefreshRateChangeExecutionTime;
            if (ts.TotalSeconds > RefreshRateChanger.WAIT_FOR_REFRESHRATE_RESET_MAX)
            {
              Log.Info(
                "g_Player.Play - waited {0}s for refreshrate change, but it never took place (check your config). Proceeding with playback.",
                RefreshRateChanger.WAIT_FOR_REFRESHRATE_RESET_MAX);
              RefreshRateChanger.ResetRefreshRateState();
            }
            else
            {
              return true;
            }
          }
        }

        _currentStep = 0;
        _currentStepIndex = -1;
        _seekTimer = DateTime.MinValue;
        _isInitialized = true;
        _subs = null;

        if (_player != null)
        {
          GUIGraphicsContext.ShowBackground = true;
          OnChanged(strFile);
          OnStopped();
          bool doStop = true;
          if (type != MediaType.Video && Util.Utils.IsAudio(strFile))
          {
            if (type == MediaType.Unknown)
            {
              type = MediaType.Music;
            }
            if (BassMusicPlayer.IsDefaultMusicPlayer && BassMusicPlayer.Player.Playing)
            {
              doStop = !BassMusicPlayer.Player.CrossFadingEnabled;
            }
          }
          if (doStop)
          {
            if (_player != null)
            {
              _player.Stop();
            }
            CachePlayer();
            _player = null;
          }
        }

        Log.Info("g_Player.Play({0} {1})", strFile, type);
        if (!Util.Utils.IsAVStream(strFile) && Util.Utils.IsVideo(strFile))
        {
          if (!Util.Utils.IsRTSP(strFile) && extension != ".ts") // do not play recorded tv with external player
          {
            using (MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.MPSettings())
            {
              bool bInternal = xmlreader.GetValueAsBool("movieplayer", "internal", true);
              bool bInternalDVD = xmlreader.GetValueAsBool("dvdplayer", "internal", true);

              if ((!bInternalDVD && (extension == ".ifo" || extension == ".vob" || isImageFile)) ||
                  (!bInternal && (extension != ".ifo" && extension != ".vob" && !isImageFile))) // external player used
              {
                if (isImageFile)
                {
                  strFile = Util.DaemonTools.GetVirtualDrive() + @"\VIDEO_TS\VIDEO_TS.IFO";
                }
                if (Util.Utils.PlayMovie(strFile))
                {
                  return true;
                }
                else // external player error
                {
                  UnableToPlay(strFile, type);
                  return false;
                }
              }
            }
          }
        }

        _player = _factory.Create(strFile, type);

        if (_player != null)
        {
          if (chapters != null)
          {
            LoadChapters(chapters);
          }
          else
          {
            LoadChapters(strFile);
          }
          _player = CachePreviousPlayer(_player);
          bool bResult = _player.Play(strFile);
          if (!bResult)
          {
            Log.Info("g_Player: ended");
            _player.SafeDispose();
            _player = null;
            _subs = null;
            UnableToPlay(strFile, type);
          }
          else if (_player.Playing)
          {
            _isInitialized = false;
            _currentFilePlaying = _player.CurrentFile;
            if (_chapters == null)
            {
              _chapters = _player.Chapters;
            }
            if (_chaptersname == null)
            {
              _chaptersname = _player.ChaptersName;
            }
            OnStarted();
          }
          return bResult;
        }
      }
      finally
      {
        Starting = false;
      }
      UnableToPlay(strFile, type);
      return false;
    }