protected override void SetPreferredSubtitle()
        {
            ISubtitleStream subtitleStream = _tsReader as ISubtitleStream;
            ITeletextSource teletextSource = _tsReader as ITeletextSource;

            if (_streamInfoSubtitles == null || (subtitleStream == null && teletextSource == null))
            {
                return;
            }

            VideoSettings settings = ServiceRegistration.Get <ISettingsManager>().Load <VideoSettings>() ?? new VideoSettings();

            // first try to find a stream by it's exact LCID.
            StreamInfo streamInfo = _streamInfoSubtitles.FindStream(settings.PreferredSubtitleLanguage) ?? _streamInfoSubtitles.FindSimilarStream(settings.PreferredSubtitleStreamName);

            if (streamInfo == null || !settings.EnableDvbSubtitles || !settings.EnableTeletextSubtitles)
            {
                // Tell the renderer it should not render subtitles
                if (_subtitleRenderer != null)
                {
                    _subtitleRenderer.RenderSubtitles = false;
                }
            }
            else
            {
                _streamInfoSubtitles.EnableStream(streamInfo.Name);
            }
        }
        public TsReaderTeletextInfoHandler(ITeletextSource teletextSource)
        {
            if (teletextSource == null)
            {
                return;
            }
            int teletextStreamCount = 0;

            _teletextSource = teletextSource;
            teletextSource.GetTeletextStreamCount(ref teletextStreamCount);
            if (teletextStreamCount > 0)
            {
                StreamInfo subStream = new StreamInfo(null, NO_STREAM_INDEX, VideoPlayer.GetNoSubsName(), 0);
                AddUnique(subStream);
            }
            for (int i = 0; i < teletextStreamCount; ++i)
            {
                //FIXME: language should be passed back also as LCID
                SubtitleLanguage language = new SubtitleLanguage();
                teletextSource.GetTeletextStreamLanguage(i, ref language);
                int        lcid      = BaseDXPlayer.LookupLcidFromName(language.lang);
                string     name      = language.lang;
                StreamInfo subStream = new StreamInfo(null, i, name, lcid);
                AddUnique(subStream);
            }
        }
        protected override bool EnumerateStreams(bool forceRefresh)
        {
            bool refreshed = base.EnumerateStreams(forceRefresh);

            if (refreshed)
            {
                ISubtitleStream subtitleStream      = _tsReader as ISubtitleStream;
                int             subtitleStreamCount = 0;
                subtitleStream?.GetSubtitleStreamCount(ref subtitleStreamCount);

                if (subtitleStreamCount >= 1)
                {
                    _streamInfoSubtitles = new TsReaderStreamInfoHandler(subtitleStream);
                    SetPreferredSubtitle();
                    return(true);
                }
                ITeletextSource teletextSource      = _tsReader as ITeletextSource;
                int             teletextStreamCount = 0;
                teletextSource?.GetTeletextStreamCount(ref teletextStreamCount);
                if (teletextStreamCount >= 1)
                {
                    _streamInfoSubtitles = new TsReaderTeletextInfoHandler(teletextSource);
                    SetPreferredSubtitle();
                    return(true);
                }
            }
            return(false);
        }
        protected override void SetPreferredSubtitle()
        {
            ISubtitleStream subtitleStream = _tsReader as ISubtitleStream;
            ITeletextSource teletextSource = _tsReader as ITeletextSource;

            if (_streamInfoSubtitles == null || (subtitleStream == null && teletextSource == null))
            {
                ServiceRegistration.Get <ILogger>().Debug("SetPreferredSubtitle: no valid subtitles stream.");
                return;
            }

            VideoSettings settings = ServiceRegistration.Get <ISettingsManager>().Load <VideoSettings>() ?? new VideoSettings();

            // first try to find a stream by it's exact LCID.
            int             preferredSubtitleLanguage = settings.PreferredSubtitleLanguage;
            IUserManagement userManagement            = ServiceRegistration.Get <IUserManagement>();

            if (userManagement?.CurrentUser != null)
            {
                preferredSubtitleLanguage = 0;
                var cultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
                if (userManagement.CurrentUser.TryGetAdditionalData(UserDataKeysKnown.KEY_PREFERRED_SUBTITLE_LANGUAGE, 0, out string subLang))
                {
                    int langId = cultures?.FirstOrDefault(c => c.TwoLetterISOLanguageName == subLang)?.LCID ?? 0;
                    if (_streamInfoSubtitles.Any(s => s.LCID == langId))
                    {
                        preferredSubtitleLanguage = langId;
                    }
                }
                if (preferredSubtitleLanguage == 0 && userManagement.CurrentUser.TryGetAdditionalData(UserDataKeysKnown.KEY_PREFERRED_SUBTITLE_LANGUAGE, 1, out string subLang2))
                {
                    int langId = cultures?.FirstOrDefault(c => c.TwoLetterISOLanguageName == subLang2)?.LCID ?? 0;
                    if (_streamInfoSubtitles.Any(s => s.LCID == langId))
                    {
                        preferredSubtitleLanguage = langId;
                    }
                }
                if (preferredSubtitleLanguage == 0)
                {
                    preferredSubtitleLanguage = settings.PreferredSubtitleLanguage;
                }
            }

            StreamInfo streamInfo = _streamInfoSubtitles.FindStream(preferredSubtitleLanguage) ?? _streamInfoSubtitles.FindSimilarStream(settings.PreferredSubtitleStreamName);

            if (streamInfo == null || !settings.EnableDvbSubtitles || !settings.EnableTeletextSubtitles)
            {
                // Tell the renderer it should not render subtitles
                if (_subtitleRenderer != null)
                {
                    _subtitleRenderer.RenderSubtitles = false;
                    ServiceRegistration.Get <ILogger>().Debug("SetPreferredSubtitle: set RenderSubtitles to false.");
                }
            }
            else
            {
                ServiceRegistration.Get <ILogger>().Debug("SetPreferredSubtitle: enable stream for {0}", streamInfo.Name);
                _streamInfoSubtitles.EnableStream(streamInfo.Name);
            }
        }
        protected override void AddSubtitleFilter(bool isSourceFilterPresent)
        {
            VideoSettings settings = ServiceRegistration.Get <ISettingsManager>().Load <VideoSettings>() ?? new VideoSettings();

            ISubtitleStream subtitleStream      = _tsReader as ISubtitleStream;
            int             subtitleStreamCount = 0;

            subtitleStream?.GetSubtitleStreamCount(ref subtitleStreamCount);

            ITeletextSource teletextSource      = _tsReader as ITeletextSource;
            int             teletextStreamCount = 0;

            teletextSource?.GetTeletextStreamCount(ref teletextStreamCount);

            bool shouldAddDvbFilter            = isSourceFilterPresent && subtitleStreamCount >= 1 && settings.EnableDvbSubtitles;
            bool shouldRenderTeletextSubtitles = isSourceFilterPresent && teletextStreamCount >= 1 && settings.EnableTeletextSubtitles;
            bool shouldAddClosedCaptionsFilter = settings.EnableAtscClosedCaptions && (subtitleStreamCount == 0 && teletextStreamCount == 0);

            if (shouldAddDvbFilter)
            {
                _subtitleRenderer.SetPlayer(this);
                _subtitleFilter = _subtitleRenderer.AddDvbSubtitleFilter(_graphBuilder);
                if (_subtitleFilter != null)
                {
                    _subtitleRenderer.RenderSubtitles = true;
                }
            }
            else if (shouldRenderTeletextSubtitles)
            {
                _subtitleRenderer.AddTeletextSubtitleDecoder(teletextSource);
                _subtitleRenderer.SetPlayer(this);
                _subtitleRenderer.RenderSubtitles = true;
            }
            else if (shouldAddClosedCaptionsFilter)
            {
                _subtitleRenderer.AddClosedCaptionsFilter(_graphBuilder);
            }
            ServiceRegistration.Get <ILogger>().Debug("TsVideoPlayer.AddSubtitleFilter: shouldAddDvbFilter: {0},  shouldRenderTeletextSubtitles: {1}, " +
                                                      "shouldAddClosedCaptionsFilter: {2}, RenderSubtitles is: {3}, subtitleStreamCount: {4}, teletextStreamCount: {5}",
                                                      shouldAddDvbFilter.ToString(), shouldRenderTeletextSubtitles.ToString(), shouldAddClosedCaptionsFilter.ToString(), _subtitleRenderer.RenderSubtitles.ToString(),
                                                      subtitleStreamCount.ToString(), teletextStreamCount.ToString());
        }
        public TeletextReceiver(ITeletextSource source, IDVBTeletextDecoder ttxtDecoder)
        {
            assert(source != null, "Source is null");
            assert(ttxtDecoder != null, "Decoder is null");
            ServiceRegistration.Get <ILogger>().Debug("Setting up teletext receiver ... ");
            _eventCallback       = new TeletextEventCallback(OnEvent);
            _packetCallback      = new TeletextPacketCallback(OnTSPacket);
            _serviceInfoCallback = new TeletextServiceInfoCallback(OnServiceInfo);

            // tell the tsreader's teletext source interface to deliver ts packets to us
            // and to inform us on resets
            ServiceRegistration.Get <ILogger>().Debug("Setting up callbacks with ITeletextSource");
            source.SetTeletextTSPacketCallback(Marshal.GetFunctionPointerForDelegate(_packetCallback));
            source.SetTeletextEventCallback(Marshal.GetFunctionPointerForDelegate(_eventCallback));
            source.SetTeletextServiceInfoCallback(Marshal.GetFunctionPointerForDelegate(_serviceInfoCallback));

            //tsPackets = new Queue<Packet>();

            ServiceRegistration.Get <ILogger>().Debug("Setting up ttxtdecoder and pes decoder");
            this._ttxtDecoder = ttxtDecoder;
            _pesDecoder       = new PESDecoder(OnPesPacket);
            ServiceRegistration.Get <ILogger>().Debug("Done setting up teletext receiver ... ");
        }
    public TeletextReceiver(ITeletextSource source, IDVBTeletextDecoder ttxtDecoder)
    {
      assert(source != null, "Source is null");
      assert(ttxtDecoder != null, "Decoder is null");
      ServiceRegistration.Get<ILogger>().Debug("Setting up teletext receiver ... ");
      _eventCallback = new TeletextEventCallback(OnEvent);
      _packetCallback = new TeletextPacketCallback(OnTSPacket);
      _serviceInfoCallback = new TeletextServiceInfoCallback(OnServiceInfo);

      // tell the tsreader's teletext source interface to deliver ts packets to us
      // and to inform us on resets
      ServiceRegistration.Get<ILogger>().Debug("Setting up callbacks with ITeletextSource");
      source.SetTeletextTSPacketCallback(Marshal.GetFunctionPointerForDelegate(_packetCallback));
      source.SetTeletextEventCallback(Marshal.GetFunctionPointerForDelegate(_eventCallback));
      source.SetTeletextServiceInfoCallback(Marshal.GetFunctionPointerForDelegate(_serviceInfoCallback));

      //tsPackets = new Queue<Packet>();

      ServiceRegistration.Get<ILogger>().Debug("Setting up ttxtdecoder and pes decoder");
      this._ttxtDecoder = ttxtDecoder;
      _pesDecoder = new PESDecoder(OnPesPacket);
      ServiceRegistration.Get<ILogger>().Debug("Done setting up teletext receiver ... ");
    }
    /// <summary> create the used COM components and get the interfaces. </summary>
    protected override bool GetInterfaces(string filename)
    {
      Log.Info("TSReaderPlayer: GetInterfaces()");
      try
      {
        string strAudioRenderer = "";
        int intFilters = 0; // FlipGer: count custom filters
        string strFilters = ""; // FlipGer: collect custom filters

        LoadMyTvFilterSettings(ref intFilters, ref strFilters, ref strVideoCodec, ref strAudioCodec,
                               ref strAACAudioCodec, ref strDDPLUSAudioCodec, ref strH264VideoCodec,
                               ref strAudioRenderer,
                               ref enableDVBBitmapSubtitles, ref enableDVBTtxtSubtitles, ref relaxTsReader);

        _graphBuilder = (IGraphBuilder)new FilterGraph();
        _rotEntry = new DsROTEntry((IFilterGraph)_graphBuilder);

        if (strAudioRenderer.Length > 0) //audio renderer must be in graph before audio switcher
        {
          _audioRendererFilter = DirectShowUtil.AddAudioRendererToGraph(_graphBuilder, strAudioRenderer, true);
        }

        #region add AudioSwitcher

        if (enableMPAudioSwitcher) //audio switcher must be in graph before tsreader audiochangecallback
        {
          _audioSwitcherFilter = DirectShowUtil.AddFilterToGraph(_graphBuilder, "MediaPortal AudioSwitcher");
          if (_audioSwitcherFilter == null)
          {
            Log.Error("TSReaderPlayer: Failed to add AudioSwitcher to graph");
          }
        }

        #endregion

        #region add TsReader

        TsReader reader = new TsReader();
        _fileSource = (IBaseFilter)reader;
        _ireader = (ITSReader)reader;
        _interfaceTSReader = _fileSource;
        _ireader.SetRelaxedMode(relaxTsReader); // enable/disable continousity filtering
        _ireader.SetTsReaderCallback(this);
        _ireader.SetRequestAudioChangeCallback(this);
        Log.Info("TSReaderPlayer: Add TsReader to graph");
        int hr = _graphBuilder.AddFilter((IBaseFilter)_fileSource, "TsReader");
        DsError.ThrowExceptionForHR(hr);

        #endregion

        #region load file in TsReader

        IFileSourceFilter interfaceFile = (IFileSourceFilter)_fileSource;
        if (interfaceFile == null)
        {
          Log.Error("TSReaderPlayer: Failed to get IFileSourceFilter");
          Cleanup();
          return false;
        }
        Log.Info("TSReaderPlayer: Open file: {0}", filename);
        hr = interfaceFile.Load(filename, null);
        if (hr != 0)
        {
          Log.Error("TSReaderPlayer: Failed to open file:{0} :0x{1:x}", filename, hr);
          Cleanup();
          return false;
        }

        #endregion

        #region add codecs

        Log.Info("TSReaderPlayer: Add codecs");
        // add preferred video & audio codecs
        MatchFilters("Video");
        MatchFilters("Audio");

        // does .ts file contain video?
        // default is _isRadio=false which prevents recorded radio file playing
        if (!_videoFormat.IsValid)
          _isRadio = true;

        if (!_isRadio)
        {
          _vmr9 = new VMR9Util();
          _vmr9.AddVMR9(_graphBuilder);
          _vmr9.Enable(false);

          DirectShowUtil.AddFilterToGraph(_graphBuilder, videoFilter);
          if (enableDVBBitmapSubtitles)
          {
            try
            {
              SubtitleRenderer.GetInstance().AddSubtitleFilter(_graphBuilder);
            }
            catch (Exception e)
            {
              Log.Error(e);
            }
          }
        }

        DirectShowUtil.AddFilterToGraph(_graphBuilder, audioFilter);

        // FlipGer: add custom filters to graph
        string[] arrFilters = strFilters.Split(';');
        for (int i = 0; i < intFilters; i++)
        {
          DirectShowUtil.AddFilterToGraph(_graphBuilder, arrFilters[i]);
        }

        #endregion

        #region PostProcessingEngine Detection

        IPostProcessingEngine postengine = PostProcessingEngine.GetInstance(true);
        if (!postengine.LoadPostProcessing(_graphBuilder))
        {
          PostProcessingEngine.engine = new PostProcessingEngine.DummyEngine();
        }

        #endregion

        #region render TsReader output pins

        Log.Info("TSReaderPlayer: Render TsReader outputs");
        if (_isRadio)
        {
          IEnumPins enumPins;
          hr = _fileSource.EnumPins(out enumPins);
          DsError.ThrowExceptionForHR(hr);
          IPin[] pins = new IPin[1];
          int fetched = 0;
          while (enumPins.Next(1, pins, out fetched) == 0)
          {
            if (fetched != 1)
            {
              break;
            }
            PinDirection direction;
            pins[0].QueryDirection(out direction);
            if (direction == PinDirection.Output)
            {
              IEnumMediaTypes enumMediaTypes;
              pins[0].EnumMediaTypes(out enumMediaTypes);
              AMMediaType[] mediaTypes = new AMMediaType[20];
              int fetchedTypes;
              enumMediaTypes.Next(20, mediaTypes, out fetchedTypes);
              for (int i = 0; i < fetchedTypes; ++i)
              {
                if (mediaTypes[i].majorType == MediaType.Audio)
                {
                  hr = _graphBuilder.Render(pins[0]);
                  DsError.ThrowExceptionForHR(hr);
                  break;
                }
              }
            }
            DirectShowUtil.ReleaseComObject(pins[0]);
          }
          DirectShowUtil.ReleaseComObject(enumPins);
        }
        else
        {
          DirectShowUtil.RenderGraphBuilderOutputPins(_graphBuilder, _fileSource);
        }
        DirectShowUtil.RemoveUnusedFiltersFromGraph(_graphBuilder);

        #endregion

        _mediaCtrl = (IMediaControl)_graphBuilder;
        _mediaEvt = (IMediaEventEx)_graphBuilder;
        _mediaSeeking = (IMediaSeeking)_graphBuilder;
        if (_mediaSeeking == null)
        {
          Log.Error("TSReaderPlayer: Unable to get IMediaSeeking interface");
        }
        _audioStream = (IAudioStream)_fileSource;
        if (_audioStream == null)
        {
          Log.Error("TSReaderPlayer: Unable to get IAudioStream interface");
        }
        _audioSelector = new AudioSelector(_audioStream);

        if (!_isRadio)
        {
          if (enableDVBTtxtSubtitles || enableDVBBitmapSubtitles)
          {
            try
            {
              SubtitleRenderer.GetInstance().SetPlayer(this);
              _dvbSubRenderer = SubtitleRenderer.GetInstance();
            }
            catch (Exception e)
            {
              Log.Error(e);
            }
          }
          if (enableDVBBitmapSubtitles)
          {
            _subtitleStream = (ISubtitleStream)_fileSource;
            if (_subtitleStream == null)
            {
              Log.Error("TSReaderPlayer: Unable to get ISubtitleStream interface");
            }
          }
          if (enableDVBTtxtSubtitles)
          {
            //Log.Debug("TSReaderPlayer: Obtaining TeletextSource");
            _teletextSource = (ITeletextSource)_fileSource;
            if (_teletextSource == null)
            {
              Log.Error("TSReaderPlayer: Unable to get ITeletextSource interface");
            }
            Log.Debug("TSReaderPlayer: Creating Teletext Receiver");
            try
            {
                using (MPSettings xmlreader = new MPSettings())
                    xmlreader.SetValue("tvservice", "dvbdefttxtsubtitles", "999;999");
            }
            catch { }
            TeletextSubtitleDecoder ttxtDecoder = new TeletextSubtitleDecoder(_dvbSubRenderer);
            _ttxtReceiver = new TeletextReceiver(_teletextSource, ttxtDecoder);
            // regardless of whether dvb subs are enabled, the following call is okay
            // if _subtitleStream is null the subtitle will just not setup for bitmap subs 
            _subSelector = new SubtitleSelector(_subtitleStream, _dvbSubRenderer, ttxtDecoder);
          }
          else if (enableDVBBitmapSubtitles)
          {
            // if only dvb subs are enabled, pass null for ttxtDecoder
            _subSelector = new SubtitleSelector(_subtitleStream, _dvbSubRenderer, null);
          }
        }
        if (_audioRendererFilter != null)
        {
          //Log.Info("TSReaderPlayer:set reference clock");
          IMediaFilter mp = (IMediaFilter)_graphBuilder;
          IReferenceClock clock = (IReferenceClock)_audioRendererFilter;
          hr = mp.SetSyncSource(null);
          hr = mp.SetSyncSource(clock);
          //Log.Info("TSReaderPlayer:set reference clock:{0:X}", hr);
          _basicAudio = (IBasicAudio)_graphBuilder;
        }
        if (!_isRadio)
        {
          IBaseFilter basefilter;
          _graphBuilder.FindFilterByName("Line 21 Decoder", out basefilter);
          if (basefilter == null)
          {
            _graphBuilder.FindFilterByName("Line21 Decoder", out basefilter);
          }
          if (basefilter == null)
          {
            _graphBuilder.FindFilterByName("Line 21 Decoder 2", out basefilter);
          }
          if (basefilter != null)
          {
            Log.Info("TSreaderPlayer: Line21 Decoder (Closed Captions), in use"); //: {0}", showClosedCaptions);
            _line21Decoder = (IAMLine21Decoder)basefilter;
            if (_line21Decoder != null)
            {
              AMLine21CCState state = AMLine21CCState.Off;
              hr = _line21Decoder.SetServiceState(state);
              if (hr == 0)
              {
                Log.Info("TSReaderPlayer: Closed Captions state change successful");
              }
              else
              {
                Log.Info("TSReaderPlayer: Failed to change Closed Captions state");
              }
            }
          }
          if (!_vmr9.IsVMR9Connected)
          {
            Log.Error("TSReaderPlayer: Failed vmr9 not connected");
            Cleanup();
            return false;
          }
          DirectShowUtil.EnableDeInterlace(_graphBuilder);
          _vmr9.SetDeinterlaceMode();
        }

        using (MPSettings xmlreader = new MPSettings())
        {
          int lastSubIndex = xmlreader.GetValueAsInt("tvservice", "lastsubtitleindex", 0);
          Log.Debug("TSReaderPlayer: Last subtitle index: {0}", lastSubIndex);
          CurrentSubtitleStream = lastSubIndex;
        }
        return true;
      }
      catch (Exception ex)
      {
        Log.Error("TSReaderPlayer: Exception while creating DShow graph {0}", ex.Message);
        Cleanup();
        return false;
      }
    }
    /// <summary> create the used COM components and get the interfaces. </summary>
    protected override bool GetInterfaces(string filename)
    {
      Log.Info("TSReaderPlayer: GetInterfaces()");
      try
      {
        _graphBuilder = (IGraphBuilder)new FilterGraphNoThread();
        _rotEntry = new DsROTEntry((IFilterGraph)_graphBuilder);

        //Get filterCodecName and filterConfig
        filterConfig = GetFilterConfiguration();
        filterCodec = GetFilterCodec();

        #region add AudioRenderer

        //Add Audio Renderer
        AudioRendererAdd();

        #endregion

        #region add AudioSwitcher

        MPAudioSwitcherAdd();

        #endregion

        #region add TsReader

        TsReader reader = new TsReader();
        _fileSource = (IBaseFilter)reader;
        _ireader = (ITSReader)reader;
        _interfaceTSReader = _fileSource;
        if (filterConfig != null)
        _ireader.SetRelaxedMode(filterConfig.relaxTsReader); // enable/disable continousity filtering
        _ireader.SetTsReaderCallback(this);
        _ireader.SetRequestAudioChangeCallback(this);
        Log.Info("TSReaderPlayer: Add TsReader to graph");
        int hr = _graphBuilder.AddFilter((IBaseFilter)_fileSource, "TsReader");
        DsError.ThrowExceptionForHR(hr);

        #endregion

        #region load file in TsReader

        IFileSourceFilter interfaceFile = (IFileSourceFilter)_fileSource;
        if (interfaceFile == null)
        {
          Log.Error("TSReaderPlayer: Failed to get IFileSourceFilter");
          Cleanup();
          return false;
        }
        Log.Info("TSReaderPlayer: Open file: {0}", filename);
        hr = interfaceFile.Load(filename, null);
        if (hr != 0)
        {
          Log.Error("TSReaderPlayer: Failed to open file:{0} :0x{1:x}", filename, hr);
          Cleanup();
          return false;
        }

        #endregion

        #region add codecs

        Log.Info("TSReaderPlayer: Add codecs");

        // does .ts file contain video?
        // default is _isRadio=false which prevents recorded radio file playing
        if (!_videoFormat.IsValid && g_Player.AudioStreams == 1)
        {
          Log.Debug("TSReaderPlayer: Stream is Radio");
          _isRadio = true;
        }

        if (!_isRadio)
        {
          if (_videoFormat.IsValid)
          {
            _vmr9 = VMR9Util.g_vmr9 = new VMR9Util();
            bool AddVMR9 = VMR9Util.g_vmr9.AddVMR9(_graphBuilder);
            if (!AddVMR9)
            {
              Log.Error("TSReaderPlayer:Failed to add VMR9 to graph");
              return false;
            }
            VMR9Util.g_vmr9.Enable(false);
          }

          // Add preferred video filters
          UpdateFilters("Video");
          Log.Debug("TSReaderPlayer: UpdateFilters Video done");

          if (filterConfig != null && filterConfig.enableDVBBitmapSubtitles)
          {
            try
            {
              SubtitleRenderer.GetInstance().AddSubtitleFilter(_graphBuilder);
              Log.Debug("TSReaderPlayer: SubtitleRenderer AddSubtitleFilter");
            }
            catch (Exception e)
            {
              Log.Error(e);
            }
          }
        }

        // Add preferred audio filters
        UpdateFilters("Audio");
        Log.Debug("TSReaderPlayer: UpdateFilters Audio done");

        #endregion

        #region PostProcessingEngine Detection

        IPostProcessingEngine postengine = PostProcessingEngine.GetInstance(true);
        if (!postengine.LoadPostProcessing(_graphBuilder))
        {
          PostProcessingEngine.engine = new PostProcessingEngine.DummyEngine();
          Log.Debug("TSReaderPlayer: PostProcessingEngine to DummyEngine");
        }

        #endregion

        #region render TsReader output pins

        Log.Info("TSReaderPlayer: Render TsReader outputs");
        if (_isRadio && g_Player.AudioStreams == 1)
        {
          IEnumPins enumPins;
          hr = _fileSource.EnumPins(out enumPins);
          DsError.ThrowExceptionForHR(hr);
          IPin[] pins = new IPin[1];
          int fetched = 0;
          while (enumPins.Next(1, pins, out fetched) == 0)
          {
            if (fetched != 1)
            {
              break;
            }
            PinDirection direction;
            pins[0].QueryDirection(out direction);
            if (direction == PinDirection.Output)
            {
              IEnumMediaTypes enumMediaTypes;
              pins[0].EnumMediaTypes(out enumMediaTypes);
              AMMediaType[] mediaTypes = new AMMediaType[20];
              int fetchedTypes;
              enumMediaTypes.Next(20, mediaTypes, out fetchedTypes);
              for (int i = 0; i < fetchedTypes; ++i)
              {
                if (mediaTypes[i].majorType == MediaType.Audio)
                {
                  hr = _graphBuilder.Render(pins[0]);
                  DsError.ThrowExceptionForHR(hr);
                  break;
                }
              }
            }
            DirectShowUtil.ReleaseComObject(pins[0]);
          }
          DirectShowUtil.ReleaseComObject(enumPins);
        }
        else
        {
          DirectShowUtil.RenderGraphBuilderOutputPins(_graphBuilder, _fileSource);
          if (filterConfig != null && !filterConfig.enableCCSubtitles)
          {
            CleanupCC();
            Log.Debug("TSReaderPlayer: CleanupCC filter (Tv/Recorded Stream Detected)");
          }
        }
        DirectShowUtil.RemoveUnusedFiltersFromGraph(_graphBuilder);

        #endregion

        _mediaCtrl = (IMediaControl)_graphBuilder;
        _mediaEvt = (IMediaEventEx)_graphBuilder;
        _mediaSeeking = (IMediaSeeking)_graphBuilder;
        if (_mediaSeeking == null)
        {
          Log.Error("TSReaderPlayer: Unable to get IMediaSeeking interface");
        }
        _audioStream = (IAudioStream)_fileSource;
        if (_audioStream == null)
        {
          Log.Error("TSReaderPlayer: Unable to get IAudioStream interface");
        }
        _audioSelector = new AudioSelector(_audioStream);

        if (!_isRadio)
        {
          if (filterConfig != null && (filterConfig != null && filterConfig.enableDVBTtxtSubtitles || filterConfig.enableDVBBitmapSubtitles))
          {
            try
            {
              SubtitleRenderer.GetInstance().SetPlayer(this);
              _dvbSubRenderer = SubtitleRenderer.GetInstance();
            }
            catch (Exception e)
            {
              Log.Error(e);
            }
          }
          if (filterConfig != null && filterConfig.enableDVBBitmapSubtitles)
          {
            _subtitleStream = (ISubtitleStream)_fileSource;
            if (_subtitleStream == null)
            {
              Log.Error("TSReaderPlayer: Unable to get ISubtitleStream interface");
            }
          }
          if (filterConfig != null && filterConfig.enableDVBTtxtSubtitles)
          {
            //Log.Debug("TSReaderPlayer: Obtaining TeletextSource");
            _teletextSource = (ITeletextSource)_fileSource;
            if (_teletextSource == null)
            {
              Log.Error("TSReaderPlayer: Unable to get ITeletextSource interface");
            }
            Log.Debug("TSReaderPlayer: Creating Teletext Receiver");
            try
            {
                using (MPSettings xmlreader = new MPSettings())
                    xmlreader.SetValue("tvservice", "dvbdefttxtsubtitles", "999;999");
            }
            catch { }
            TeletextSubtitleDecoder ttxtDecoder = new TeletextSubtitleDecoder(_dvbSubRenderer);
            _ttxtReceiver = new TeletextReceiver(_teletextSource, ttxtDecoder);
            // regardless of whether dvb subs are enabled, the following call is okay
            // if _subtitleStream is null the subtitle will just not setup for bitmap subs 
            _subSelector = new SubtitleSelector(_subtitleStream, _dvbSubRenderer, ttxtDecoder);
          }
          else if (filterConfig != null && filterConfig.enableDVBBitmapSubtitles)
          {
            // if only dvb subs are enabled, pass null for ttxtDecoder
            _subSelector = new SubtitleSelector(_subtitleStream, _dvbSubRenderer, null);
          }
        }
        if (filterCodec._audioRendererFilter != null)
        {
          //Log.Info("TSReaderPlayer:set reference clock");
          /*IMediaFilter mp = (IMediaFilter)_graphBuilder;
          IReferenceClock clock = (IReferenceClock)filterCodec._audioRendererFilter;
          hr = mp.SetSyncSource(null);
          hr = mp.SetSyncSource(clock);*/
          //Log.Info("TSReaderPlayer:set reference clock:{0:X}", hr);
          SyncAudioRenderer();
          _basicAudio = (IBasicAudio)_graphBuilder;
        }
        if (!_isRadio)
        {
          if (VMR9Util.g_vmr9 != null && filterConfig != null && filterConfig.enableCCSubtitles)
          {
            CleanupCC();
            ReleaseCC();
            ReleaseCC2();
            CoreCCParserCheck();
            DirectShowUtil.RenderUnconnectedOutputPins(_graphBuilder, filterCodec.VideoCodec);
            Log.Debug("TSReaderPlayer: Render VideoCodec filter (Tv/Recorded Stream Detected)");
            EnableCC();
            Log.Debug("TSReaderPlayer: EnableCC");
            if (CoreCCPresent)
            {
              DirectShowUtil.RenderUnconnectedOutputPins(_graphBuilder, filterCodec.CoreCCParser);
              Log.Debug("TSReaderPlayer: Render CoreCCParser filter (Tv/Recorded Stream Detected)");
              EnableCC2();
              Log.Debug("TSReaderPlayer: EnableCC2");
            }
          }
          if (VMR9Util.g_vmr9 != null && !VMR9Util.g_vmr9.IsVMR9Connected)
          {
            Log.Error("TSReaderPlayer: Failed vmr9 not connected");
            Cleanup();
            return false;
          }
          DirectShowUtil.EnableDeInterlace(_graphBuilder);
          if (VMR9Util.g_vmr9 != null)
          {
            VMR9Util.g_vmr9.SetDeinterlaceMode();
          }
        }

        using (MPSettings xmlreader = new MPSettings())
        {
          if (filterConfig.autoShowSubWhenTvStarts && SupportsCC && CurrentSubtitleStream == 0)
          {
            CurrentSubtitleStream = -1;
          }
          else
          {
            int lastSubIndex = xmlreader.GetValueAsInt("tvservice", "lastsubtitleindex", 0);
            Log.Debug("TSReaderPlayer: Last subtitle index: {0}", lastSubIndex);
            CurrentSubtitleStream = lastSubIndex;
          }
        }

        if (filterConfig != null && !filterConfig.autoShowSubWhenTvStarts)
        {
          Log.Debug("TSReaderPlayer: Automatically show subtitles when TV starts is set to {0}", filterConfig.autoShowSubWhenTvStarts);
          EnableSubtitle = filterConfig.autoShowSubWhenTvStarts;
        }

        return true;
      }
      catch (Exception ex)
      {
        Log.Error("TSReaderPlayer: Exception while creating DShow graph {0}", ex.Message);
        Cleanup();
        return false;
      }
    }
        public void AddTeletextSubtitleDecoder(ITeletextSource teletextSource)
        {
            TeletextSubtitleDecoder ttxtDecoder = new TeletextSubtitleDecoder(this);

            _ttxtReceiver = new TeletextReceiver(teletextSource, ttxtDecoder);
        }
        /// <summary> create the used COM components and get the interfaces. </summary>
        protected override bool GetInterfaces(string filename)
        {
            Log.Info("TSReaderPlayer: GetInterfaces()");
            try
            {
                string strAudioRenderer = "";
                int    intFilters       = 0;  // FlipGer: count custom filters
                string strFilters       = ""; // FlipGer: collect custom filters

                LoadMyTvFilterSettings(ref intFilters, ref strFilters, ref strVideoCodec, ref strAudioCodec,
                                       ref strAACAudioCodec, ref strDDPLUSAudioCodec, ref strH264VideoCodec,
                                       ref strAudioRenderer,
                                       ref enableDVBBitmapSubtitles, ref enableDVBTtxtSubtitles, ref relaxTsReader);

                _graphBuilder = (IGraphBuilder) new FilterGraph();
                _rotEntry     = new DsROTEntry((IFilterGraph)_graphBuilder);

                if (strAudioRenderer.Length > 0) //audio renderer must be in graph before audio switcher
                {
                    _audioRendererFilter = DirectShowUtil.AddAudioRendererToGraph(_graphBuilder, strAudioRenderer, true);
                }

                #region add AudioSwitcher

                if (enableMPAudioSwitcher) //audio switcher must be in graph before tsreader audiochangecallback
                {
                    _audioSwitcherFilter = DirectShowUtil.AddFilterToGraph(_graphBuilder, "MediaPortal AudioSwitcher");
                    if (_audioSwitcherFilter == null)
                    {
                        Log.Error("TSReaderPlayer: Failed to add AudioSwitcher to graph");
                    }
                }

                #endregion

                #region add TsReader

                TsReader reader = new TsReader();
                _fileSource        = (IBaseFilter)reader;
                _ireader           = (ITSReader)reader;
                _interfaceTSReader = _fileSource;
                _ireader.SetRelaxedMode(relaxTsReader); // enable/disable continousity filtering
                _ireader.SetTsReaderCallback(this);
                _ireader.SetRequestAudioChangeCallback(this);
                Log.Info("TSReaderPlayer: Add TsReader to graph");
                int hr = _graphBuilder.AddFilter((IBaseFilter)_fileSource, "TsReader");
                DsError.ThrowExceptionForHR(hr);

                #endregion

                #region load file in TsReader

                IFileSourceFilter interfaceFile = (IFileSourceFilter)_fileSource;
                if (interfaceFile == null)
                {
                    Log.Error("TSReaderPlayer: Failed to get IFileSourceFilter");
                    Cleanup();
                    return(false);
                }
                Log.Info("TSReaderPlayer: Open file: {0}", filename);
                hr = interfaceFile.Load(filename, null);
                if (hr != 0)
                {
                    Log.Error("TSReaderPlayer: Failed to open file:{0} :0x{1:x}", filename, hr);
                    Cleanup();
                    return(false);
                }

                #endregion

                #region add codecs

                Log.Info("TSReaderPlayer: Add codecs");
                // add preferred video & audio codecs
                MatchFilters("Video");
                MatchFilters("Audio");

                // does .ts file contain video?
                // default is _isRadio=false which prevents recorded radio file playing
                if (!_videoFormat.IsValid)
                {
                    _isRadio = true;
                }

                if (!_isRadio)
                {
                    _vmr9 = new VMR9Util();
                    _vmr9.AddVMR9(_graphBuilder);
                    _vmr9.Enable(false);

                    DirectShowUtil.AddFilterToGraph(_graphBuilder, videoFilter);
                    if (enableDVBBitmapSubtitles)
                    {
                        try
                        {
                            SubtitleRenderer.GetInstance().AddSubtitleFilter(_graphBuilder);
                        }
                        catch (Exception e)
                        {
                            Log.Error(e);
                        }
                    }
                }

                DirectShowUtil.AddFilterToGraph(_graphBuilder, audioFilter);

                // FlipGer: add custom filters to graph
                string[] arrFilters = strFilters.Split(';');
                for (int i = 0; i < intFilters; i++)
                {
                    DirectShowUtil.AddFilterToGraph(_graphBuilder, arrFilters[i]);
                }

                #endregion

                #region PostProcessingEngine Detection

                IPostProcessingEngine postengine = PostProcessingEngine.GetInstance(true);
                if (!postengine.LoadPostProcessing(_graphBuilder))
                {
                    PostProcessingEngine.engine = new PostProcessingEngine.DummyEngine();
                }

                #endregion

                #region render TsReader output pins

                Log.Info("TSReaderPlayer: Render TsReader outputs");
                if (_isRadio)
                {
                    IEnumPins enumPins;
                    hr = _fileSource.EnumPins(out enumPins);
                    DsError.ThrowExceptionForHR(hr);
                    IPin[] pins    = new IPin[1];
                    int    fetched = 0;
                    while (enumPins.Next(1, pins, out fetched) == 0)
                    {
                        if (fetched != 1)
                        {
                            break;
                        }
                        PinDirection direction;
                        pins[0].QueryDirection(out direction);
                        if (direction == PinDirection.Output)
                        {
                            IEnumMediaTypes enumMediaTypes;
                            pins[0].EnumMediaTypes(out enumMediaTypes);
                            AMMediaType[] mediaTypes = new AMMediaType[20];
                            int           fetchedTypes;
                            enumMediaTypes.Next(20, mediaTypes, out fetchedTypes);
                            for (int i = 0; i < fetchedTypes; ++i)
                            {
                                if (mediaTypes[i].majorType == MediaType.Audio)
                                {
                                    hr = _graphBuilder.Render(pins[0]);
                                    DsError.ThrowExceptionForHR(hr);
                                    break;
                                }
                            }
                        }
                        DirectShowUtil.ReleaseComObject(pins[0]);
                    }
                    DirectShowUtil.ReleaseComObject(enumPins);
                }
                else
                {
                    DirectShowUtil.RenderGraphBuilderOutputPins(_graphBuilder, _fileSource);
                }
                DirectShowUtil.RemoveUnusedFiltersFromGraph(_graphBuilder);

                #endregion

                _mediaCtrl    = (IMediaControl)_graphBuilder;
                _mediaEvt     = (IMediaEventEx)_graphBuilder;
                _mediaSeeking = (IMediaSeeking)_graphBuilder;
                if (_mediaSeeking == null)
                {
                    Log.Error("TSReaderPlayer: Unable to get IMediaSeeking interface");
                }
                _audioStream = (IAudioStream)_fileSource;
                if (_audioStream == null)
                {
                    Log.Error("TSReaderPlayer: Unable to get IAudioStream interface");
                }
                _audioSelector = new AudioSelector(_audioStream);

                if (!_isRadio)
                {
                    if (enableDVBTtxtSubtitles || enableDVBBitmapSubtitles)
                    {
                        try
                        {
                            SubtitleRenderer.GetInstance().SetPlayer(this);
                            _dvbSubRenderer = SubtitleRenderer.GetInstance();
                        }
                        catch (Exception e)
                        {
                            Log.Error(e);
                        }
                    }
                    if (enableDVBBitmapSubtitles)
                    {
                        _subtitleStream = (ISubtitleStream)_fileSource;
                        if (_subtitleStream == null)
                        {
                            Log.Error("TSReaderPlayer: Unable to get ISubtitleStream interface");
                        }
                    }
                    if (enableDVBTtxtSubtitles)
                    {
                        //Log.Debug("TSReaderPlayer: Obtaining TeletextSource");
                        _teletextSource = (ITeletextSource)_fileSource;
                        if (_teletextSource == null)
                        {
                            Log.Error("TSReaderPlayer: Unable to get ITeletextSource interface");
                        }
                        Log.Debug("TSReaderPlayer: Creating Teletext Receiver");
                        TeletextSubtitleDecoder ttxtDecoder = new TeletextSubtitleDecoder(_dvbSubRenderer);
                        _ttxtReceiver = new TeletextReceiver(_teletextSource, ttxtDecoder);
                        // regardless of whether dvb subs are enabled, the following call is okay
                        // if _subtitleStream is null the subtitle will just not setup for bitmap subs
                        _subSelector = new SubtitleSelector(_subtitleStream, _dvbSubRenderer, ttxtDecoder);
                    }
                    else if (enableDVBBitmapSubtitles)
                    {
                        // if only dvb subs are enabled, pass null for ttxtDecoder
                        _subSelector = new SubtitleSelector(_subtitleStream, _dvbSubRenderer, null);
                    }
                }
                if (_audioRendererFilter != null)
                {
                    //Log.Info("TSReaderPlayer:set reference clock");
                    IMediaFilter    mp    = (IMediaFilter)_graphBuilder;
                    IReferenceClock clock = (IReferenceClock)_audioRendererFilter;
                    hr = mp.SetSyncSource(null);
                    hr = mp.SetSyncSource(clock);
                    //Log.Info("TSReaderPlayer:set reference clock:{0:X}", hr);
                    _basicAudio = (IBasicAudio)_graphBuilder;
                }
                if (!_isRadio)
                {
                    IBaseFilter basefilter;
                    _graphBuilder.FindFilterByName("Line 21 Decoder", out basefilter);
                    if (basefilter == null)
                    {
                        _graphBuilder.FindFilterByName("Line21 Decoder", out basefilter);
                    }
                    if (basefilter == null)
                    {
                        _graphBuilder.FindFilterByName("Line 21 Decoder 2", out basefilter);
                    }
                    if (basefilter != null)
                    {
                        Log.Info("TSreaderPlayer: Line21 Decoder (Closed Captions), in use"); //: {0}", showClosedCaptions);
                        _line21Decoder = (IAMLine21Decoder)basefilter;
                        if (_line21Decoder != null)
                        {
                            AMLine21CCState state = AMLine21CCState.Off;
                            hr = _line21Decoder.SetServiceState(state);
                            if (hr == 0)
                            {
                                Log.Info("TSReaderPlayer: Closed Captions state change successful");
                            }
                            else
                            {
                                Log.Info("TSReaderPlayer: Failed to change Closed Captions state");
                            }
                        }
                    }
                    if (!_vmr9.IsVMR9Connected)
                    {
                        Log.Error("TSReaderPlayer: Failed vmr9 not connected");
                        Cleanup();
                        return(false);
                    }
                    DirectShowUtil.EnableDeInterlace(_graphBuilder);
                    _vmr9.SetDeinterlaceMode();
                }

                using (MPSettings xmlreader = new MPSettings())
                {
                    int lastSubIndex = xmlreader.GetValueAsInt("tvservice", "lastsubtitleindex", 0);
                    Log.Debug("TSReaderPlayer: Last subtitle index: {0}", lastSubIndex);
                    CurrentSubtitleStream = lastSubIndex;
                }
                return(true);
            }
            catch (Exception ex)
            {
                Log.Error("TSReaderPlayer: Exception while creating DShow graph {0}", ex.Message);
                Cleanup();
                return(false);
            }
        }