/// <summary>
 /// Handler for Close command
 /// </summary>
 private void DoCloseMedia()
 {
     lock (_workQueueThreadLock)
     {
         HLSTrace.WriteLine("DoCloseMedia");
         _bwHistory.Close();
         _playback.AbortStreamDownloads();
         _isWorkQueueThreadStarted = false;
         _workQueueThread = null;
         _workQueue = null;
         _audioBuffer = null;
         _videoBuffer = null;
         _playlist = null;
         _playback = null;
         _program = null;
         if (_demux != null)
         {
             _demux.Dispose();
             _demux = null;
         }
     }
 }
        /// <summary>
        /// Called when playlist file has been loaded and parsed. This implementation selects a program,
        /// creates a playback wrapper and asynchronously requests first stream to play.
        /// </summary>
        private void Playlist_PlaylistReady(object sender)
        {
            // DoCloseMedia may happend before the PlaylistReady event fired.
            if (_playlist == null) return;

            if (_program == null)
                _program = _playlist.Programs[0];

            if (_playback == null)
                _playback = new HLSPlayback(_program, (IVariantSelector)this);

            lock (_playback)
            {
                if (_openParam.isDownloadAllSubPlayList || null != _playlistOverrideEvent)
                {
                    _playback.OnStartLoadingSubPlayList(_program.Variants.Count);
                    _playback.AllSubPlayListEvent += OnAllSubPlayListLoaded;
                    foreach (HLSVariant hlsVariant in _program.Variants)
                    {
                        hlsVariant.Playback = _playback;
                        hlsVariant.Load();
                    }
                }
                else
                {
                    OnAllSubPlayListLoaded();
                }
            }
        }
        /// <summary>
        /// Asynchronous callback for dealing with media file opening
        /// </summary>
        /// <param name="asyncResult"></param>
        private void AsyncStreamCallback(IAsyncResult asyncResult)
        {
            EncryptedStream stream = null;

            if (_playback == null)
                _playback = new HLSPlayback(_program, (IVariantSelector)this);

            lock (_playback)
            {
                if (_playback.Program == null)
                    _playback.Program = _program;

                stream = _playback.EndGetNextStream(asyncResult);
            }

            if (_state != State.Seeking)
            {
                _workQueue.Enqueue(new WorkQueueElement(WorkQueueElement.Command.NextStream, stream));
            }
            else
            {
                UpdateDemux(stream);

                _playback.EndPendingWebRequest();
            }
        }