public async Task<IDictionary<long, Program>> LoadAsync(ContentType contentType, CancellationToken cancellationToken) { var playlists = Playlists; foreach (var playlist in playlists) { try { var parser = new M3U8Parser(); if (null != _playlistWebReader) _playlistWebReader.Dispose(); _playlistWebReader = _webReaderManager.CreateReader(playlist, ContentKind.Playlist, contentType: contentType); var actualPlaylist = await parser.ParseAsync(_playlistWebReader, _retryManager, playlist, cancellationToken) .ConfigureAwait(false); return await LoadAsync(_playlistWebReader, parser, contentType, cancellationToken).ConfigureAwait(false); } catch (StatusCodeWebException e) { // This one didn't work, so try the next playlist url. Debug.WriteLine("HlsProgramManager.LoadAsync: " + e.Message); } } return NoPrograms; }
internal virtual HttpWebRequest CreateRequest(Uri url, Uri referrer, IWebReader parent, ContentType contentType, string method = null, bool allowBuffering = false, long?fromBytes = null, long?toBytes = null) { referrer = referrer ?? HttpWebRequestWebReaderManager.GetReferrer(parent); if ((Uri)null == url && null != parent) { url = parent.RequestUri ?? parent.BaseAddress; } if ((Uri)null != referrer && ((Uri)null == url || !url.IsAbsoluteUri)) { url = new Uri(referrer, url); } HttpWebRequest webRequest = this._httpWebRequests.CreateWebRequest(url, referrer, method, contentType, allowBuffering, fromBytes, toBytes); if (null != this._webReaderManagerParameters.DefaultHeaders) { foreach (KeyValuePair <string, string> keyValuePair in this._webReaderManagerParameters.DefaultHeaders) { try { webRequest.Headers[keyValuePair.Key] = keyValuePair.Value; } catch (ArgumentException ex) { Debug.WriteLine("HttpWebRequestWebReaderManager.CreateRequest({0}) header {1}={2} failed: {3}", (object)url, (object)keyValuePair.Key, (object)keyValuePair.Value, (object)ExceptionExtensions.ExtendedMessage((Exception)ex)); } } } return(webRequest); }
public HlsProgramStream(IWebReader webReader, ICollection <Uri> urls, IHlsSegmentsFactory segmentsFactory, IWebMetadataFactory webMetadataFactory, IPlatformServices platformServices, IRetryManager retryManager) { if (null == segmentsFactory) { throw new ArgumentNullException("segmentsFactory"); } if (null == webMetadataFactory) { throw new ArgumentNullException("webMetadataFactory"); } if (null == webReader) { throw new ArgumentNullException("webReader"); } if (null == platformServices) { throw new ArgumentNullException("platformServices"); } if (null == retryManager) { throw new ArgumentNullException("retryManager"); } this._webReader = webReader; this._segmentsFactory = segmentsFactory; this._webMetadataFactory = webMetadataFactory; this.Urls = urls; }
public SegmentReader(ISegment segment, IWebReader webReader, IWebMetadataFactory webMetadataFactory, IRetryManager retryManager, IPlatformServices platformServices) { if (null == segment) throw new ArgumentNullException(nameof(segment)); if (null == webReader) throw new ArgumentNullException(nameof(webReader)); if (null == webMetadataFactory) throw new ArgumentNullException(nameof(webMetadataFactory)); if (null == retryManager) throw new ArgumentNullException(nameof(retryManager)); if (null == platformServices) throw new ArgumentNullException(nameof(platformServices)); _segment = segment; _webReader = webReader; _webMetadataFactory = webMetadataFactory; _retryManager = retryManager; _platformServices = platformServices; if ((segment.Offset >= 0) && (segment.Length > 0)) { _startOffset = segment.Offset; _endOffset = segment.Offset + segment.Length - 1; } }
public async Task <IDictionary <long, Program> > LoadAsync(CancellationToken cancellationToken) { ICollection <Uri> playlists = this.Playlists; IDictionary <long, Program> dictionary; foreach (Uri uri in (IEnumerable <Uri>)playlists) { try { M3U8Parser parser = new M3U8Parser(); if (null != this._playlistWebReader) { this._playlistWebReader.Dispose(); } this._playlistWebReader = this._webReaderManager.CreateReader(uri, ContentKind.Playlist, (IWebReader)null, (ContentType)null); Uri actualPlaylist = await M3U8ParserExtensions.ParseAsync(parser, this._playlistWebReader, this._retryManager, uri, cancellationToken).ConfigureAwait(false); dictionary = await this.LoadAsync(this._playlistWebReader, parser, cancellationToken); goto label_14; } catch (WebException ex) { Debug.WriteLine("HlsProgramManager.LoadAsync: " + ex.Message); } } dictionary = HlsProgramManager.NoPrograms; label_14: return(dictionary); }
public SegmentReader(ISegment segment, IWebReader webReader, IWebMetadataFactory webMetadataFactory, IRetryManager retryManager, IPlatformServices platformServices) { if (null == segment) { throw new ArgumentNullException("segment"); } if (null == webReader) { throw new ArgumentNullException("webReader"); } if (null == webMetadataFactory) { throw new ArgumentNullException("webMetadataFactory"); } if (null == retryManager) { throw new ArgumentNullException("retryManager"); } if (null == platformServices) { throw new ArgumentNullException("platformServices"); } this._segment = segment; this._webReader = webReader; this._webMetadataFactory = webMetadataFactory; this._retryManager = retryManager; this._platformServices = platformServices; if (segment.Offset < 0L || segment.Length <= 0L) { return; } this._startOffset = new long?(segment.Offset); this._endOffset = new long?(segment.Offset + segment.Length - 1L); }
public HlsProgramStream(IWebReader webReader, ICollection <Uri> urls, IHlsSegmentsFactory segmentsFactory, IWebMetadataFactory webMetadataFactory, IPlatformServices platformServices, IRetryManager retryManager) { if (null == segmentsFactory) { throw new ArgumentNullException(nameof(segmentsFactory)); } if (null == webMetadataFactory) { throw new ArgumentNullException(nameof(webMetadataFactory)); } if (null == webReader) { throw new ArgumentNullException(nameof(webReader)); } if (null == platformServices) { throw new ArgumentNullException(nameof(platformServices)); } if (null == retryManager) { throw new ArgumentNullException(nameof(retryManager)); } _webReader = webReader; _segmentsFactory = segmentsFactory; _webMetadataFactory = webMetadataFactory; Urls = urls; }
public static async Task <TReturn> ReadStreamAsync <TReturn>(this IWebReader webReader, Uri url, Retry retry, Func <Uri, Stream, CancellationToken, Task <TReturn> > reader, CancellationToken cancellationToken) { TReturn @return; while (true) { using (IWebStreamResponse webStreamAsync = await webReader.GetWebStreamAsync(url, false, cancellationToken, (Uri)null, new long?(), new long?(), (WebResponse)null)) { if (webStreamAsync.IsSuccessStatusCode) { Uri actualUrl = webStreamAsync.ActualUrl; using (Stream stream = await webStreamAsync.GetStreamAsync(cancellationToken).ConfigureAwait(false)) { @return = await reader(actualUrl, stream, cancellationToken).ConfigureAwait(false); break; } } else { if (!RetryPolicy.IsRetryable((HttpStatusCode)webStreamAsync.HttpStatusCode)) { webStreamAsync.EnsureSuccessStatusCode(); } bool canRetry = await retry.CanRetryAfterDelayAsync(cancellationToken).ConfigureAwait(false); if (!canRetry) { webStreamAsync.EnsureSuccessStatusCode(); } } } } return(@return); }
public WebCacheManager(IWebReader webReader) { if (null == webReader) { throw new ArgumentNullException("webReader"); } this._webReader = webReader; }
protected static Uri GetUrl(Uri url, IWebReader parent) { if ((Uri)null == url && null != parent) { url = parent.RequestUri ?? parent.BaseAddress; } return(url); }
public static Task <Uri> ParseAsync(this M3U8Parser parser, IWebReader webReader, IRetryManager retryManager, Uri playlist, CancellationToken cancellationToken) { IRetry retry = RetryManagerExtensions.CreateWebRetry(retryManager, 2, 250); return(retry.CallAsync <Uri>((Func <Task <Uri> >)(() => WebReaderExtensions.ReadStreamAsync <Uri>(webReader, playlist, retry, (Func <Uri, Stream, Uri>)((actualPlaylist, stream) => { M3U8ParserExtensions.Parse(parser, actualPlaylist, stream, (Encoding)null); return actualPlaylist; }), cancellationToken)), cancellationToken)); }
protected virtual WinRtHttpClientWebReader CreateHttpClientWebReader(Uri url, ContentKind requiredKind, IWebReader parent = null, ContentType contentType = null) { url = GetUrl(url, parent); if (null == contentType) contentType = _contentTypeDetector.GetContentType(url, requiredKind).SingleOrDefaultSafe(); var httpClient = CreateHttpClient(url, parent, contentType); return new WinRtHttpClientWebReader(this, url, httpClient, contentType, _contentTypeDetector); }
protected virtual HttpClient CreateHttpClient(Uri url, IWebReader parent, ContentKind contentKind, ContentType contentType) { url = HttpClientWebReaderManager.GetUrl(url, parent); Uri referrer = HttpClientWebReaderManager.GetReferrer(parent); if ((Uri)null != referrer) { url = new Uri(referrer, url); } return(this._httpClientFactory.CreateClient(url, referrer, contentKind, contentType)); }
protected virtual HttpClient CreateHttpClient(Uri url, IWebReader parent, ContentType contentType) { url = GetUrl(url, parent); var referrer = GetReferrer(parent); if (null != referrer) url = new Uri(referrer, url); var httpClient = _httpClientFactory.CreateClient(url, referrer, contentType); return httpClient; }
/// <summary> /// </summary> /// <param name="parser"></param> /// <param name="webReader"></param> /// <param name="retryManager"></param> /// <param name="playlist"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public static Task<Uri> ParseAsync(this M3U8Parser parser, IWebReader webReader, IRetryManager retryManager, Uri playlist, CancellationToken cancellationToken) { var retry = retryManager.CreateWebRetry(2, 250); return retry.CallAsync(() => webReader.ReadStreamAsync(playlist, retry, (actualPlaylist, stream) => { parser.Parse(actualPlaylist, stream); return actualPlaylist; }, cancellationToken), cancellationToken); }
internal virtual HttpConnectionRequest CreateRequest(Uri url, Uri referrer, IWebReader parent, ContentType contentType, string method = null, bool allowBuffering = false, long?fromBytes = null, long?toBytes = null) { referrer = referrer ?? HttpConnectionWebReaderManager.GetReferrer(parent); if ((Uri)null == url && null != parent) { url = parent.RequestUri ?? parent.BaseAddress; } if ((Uri)null != referrer && ((Uri)null == url || !url.IsAbsoluteUri)) { url = new Uri(referrer, url); } return(this._httpConnectionRequestFactory.CreateRequest(url, referrer, contentType, fromBytes, toBytes, this._webReaderManagerParameters.DefaultHeaders)); }
protected SimpleSegmentManagerBase(IWebReader webReader, ICollection <ISegment> segments, ContentType contentType) { if (null == webReader) { throw new ArgumentNullException("webReader"); } if (null == segments) { throw new ArgumentNullException("segments"); } this._webReader = webReader; this._contentType = contentType; this._segments = segments; }
protected virtual async Task <ISegmentManager> ReadPlaylistAsync(IWebReader webReader, Uri url, Stream stream, CancellationToken cancellationToken) { var pls = new PlsParser(url); using (var streamReader = new StreamReader(stream)) { var ret = await pls.ParseAsync(streamReader); if (!ret) { return(null); } } var segmentManager = await CreateManagerAsync(pls, webReader, cancellationToken); return(segmentManager); }
public virtual async Task <ISegmentManager> CreateAsync(ISegmentManagerParameters parameters, ContentType contentType, CancellationToken cancellationToken) { ISegmentManager segmentManager1; foreach (Uri uri in (IEnumerable <Uri>)parameters.Source) { Uri localUrl = uri; IRetry retry = RetryManagerExtensions.CreateWebRetry(this._retryManager, 3, 333); ISegmentManager segmentManager = await retry.CallAsync <ISegmentManager>((Func <Task <ISegmentManager> >)(async() => { IWebReader webReader = this._webReaderManager.CreateReader(localUrl, ContentTypes.Pls.Kind, (IWebReader)null, ContentTypes.Pls); ISegmentManager segmentManager2; try { using (IWebStreamResponse webStreamResponse = await webReader.GetWebStreamAsync(localUrl, false, cancellationToken, (Uri)null, new long?(), new long?(), (WebResponse)null).ConfigureAwait(false)) { if (!webStreamResponse.IsSuccessStatusCode) { webReader.Dispose(); segmentManager2 = (ISegmentManager)null; } else { using (Stream stream = await webStreamResponse.GetStreamAsync(cancellationToken).ConfigureAwait(false)) segmentManager2 = await this.ReadPlaylistAsync(webReader, webStreamResponse.ActualUrl, stream, cancellationToken).ConfigureAwait(false); } } } catch (Exception ex) { webReader.Dispose(); throw; } return(segmentManager2); }), cancellationToken); if (null != segmentManager) { segmentManager1 = segmentManager; goto label_10; } } segmentManager1 = (ISegmentManager)null; label_10: return(segmentManager1); }
public HlsStreamSegments(M3U8Parser parser, IWebReader webReader, IRetryManager retryManager, IPlatformServices platformServices) { if (null == parser) throw new ArgumentNullException(nameof(parser)); if (null == webReader) throw new ArgumentNullException(nameof(webReader)); if (null == retryManager) throw new ArgumentNullException(nameof(retryManager)); if (null == platformServices) throw new ArgumentNullException(nameof(platformServices)); _parser = parser; _webReader = webReader; _retryManager = retryManager; _platformServices = platformServices; _mediaSequence = M3U8Tags.ExtXMediaSequence.GetValue<long>(parser.GlobalTags); }
public ScrapingReportJob(IScrapingDataAnalyzer dataAnalyzer, IWebReader webReader, IOutputWriter iOutputWriter) { if (webReader == null) { throw new ArgumentNullException(nameof(webReader)); } if (dataAnalyzer == null) { throw new ArgumentNullException(nameof(dataAnalyzer)); } if (iOutputWriter == null) { throw new ArgumentNullException(nameof(iOutputWriter)); } _webReader = webReader; _dataAnalyzer = dataAnalyzer; _outputWriter = iOutputWriter; //_webReader = webReader ?? throw new ArgumentNullException(nameof(webReader)); //_dataAnalyzer = dataAnalyzer ?? throw new ArgumentNullException(nameof(dataAnalyzer)); }
public HlsProgramStream(IWebReader webReader, ICollection<Uri> urls, ContentType contentType, ContentType streamContentType, IHlsSegmentsFactory segmentsFactory, IWebMetadataFactory webMetadataFactory, IPlatformServices platformServices, IRetryManager retryManager) { if (null == segmentsFactory) throw new ArgumentNullException(nameof(segmentsFactory)); if (null == webMetadataFactory) throw new ArgumentNullException(nameof(webMetadataFactory)); if (null == webReader) throw new ArgumentNullException(nameof(webReader)); if (null == platformServices) throw new ArgumentNullException(nameof(platformServices)); if (null == retryManager) throw new ArgumentNullException(nameof(retryManager)); _webReader = webReader; _segmentsFactory = segmentsFactory; _webMetadataFactory = webMetadataFactory; Urls = urls; ContentType = contentType; StreamContentType = streamContentType; }
protected virtual async Task<ISegmentManager> CreateManagerAsync(PlsParser pls, IWebReader webReader, ContentType contentType, ContentType streamContentType, CancellationToken cancellationToken) { var trackUrl = await _plsSegmentManagerPolicy.GetTrackAsync(pls, webReader.ContentType, cancellationToken); if (null == trackUrl) return null; if (null == streamContentType) streamContentType = await webReader.DetectContentTypeAsync(trackUrl, ContentKind.AnyMedia, cancellationToken).ConfigureAwait(false); //DumpIcy(headers.ResponseHeaders); if (null == streamContentType) { Debug.WriteLine("PlsSegmentManagerFactory.CreateManagerAsync() unable to detect type for " + trackUrl); return null; } return new SimpleSegmentManager(webReader, new[] { trackUrl }, contentType, streamContentType); }
protected virtual async Task <ISegmentManager> ReadPlaylistAsync(IWebReader webReader, Uri url, Stream stream, CancellationToken cancellationToken) { PlsParser pls = new PlsParser(url); ISegmentManager segmentManager; using (StreamReader streamReader = new StreamReader(stream)) { bool ret = await pls.ParseAsync((TextReader)streamReader).ConfigureAwait(false); if (!ret) { segmentManager = (ISegmentManager)null; goto label_8; } } segmentManager = await this.CreateManagerAsync(pls, webReader, cancellationToken).ConfigureAwait(false); label_8: return(segmentManager); }
public static async Task <TReturn> ReadStreamAsync <TReturn>(this IWebReader webReader, Uri url, IRetry retry, Func <Uri, Stream, TReturn> reader, CancellationToken cancellationToken) { TReturn @return; while (true) { using (IWebStreamResponse webStreamResponse = await webReader.GetWebStreamAsync(url, true, cancellationToken, (Uri)null, new long?(), new long?(), (WebResponse)null).ConfigureAwait(false)) { if (webStreamResponse.IsSuccessStatusCode) { Uri actualUrl = webStreamResponse.ActualUrl; using (Stream stream = await webStreamResponse.GetStreamAsync(cancellationToken).ConfigureAwait(false)) { using (MemoryStream memoryStream = new MemoryStream((int)(webStreamResponse.ContentLength ?? 4096L))) { await stream.CopyToAsync((Stream)memoryStream, 4096, cancellationToken).ConfigureAwait(false); memoryStream.Position = 0L; @return = reader(actualUrl, (Stream)memoryStream); break; } } } else { if (!RetryPolicy.IsRetryable((HttpStatusCode)webStreamResponse.HttpStatusCode)) { webStreamResponse.EnsureSuccessStatusCode(); } bool canRetry = await retry.CanRetryAfterDelayAsync(cancellationToken).ConfigureAwait(false); if (!canRetry) { webStreamResponse.EnsureSuccessStatusCode(); } } } } return(@return); }
public SegmentReaderEnumerator(ISegmentManager segmentManager, IWebMetadataFactory webMetadataFactory, IRetryManager retryManager, IPlatformServices platformServices) { if (null == segmentManager) { throw new ArgumentNullException("segmentManager"); } if (null == webMetadataFactory) { throw new ArgumentNullException("webMetadataFactory"); } if (null == retryManager) { throw new ArgumentNullException("retryManager"); } if (null == platformServices) { throw new ArgumentNullException("platformServices"); } this._segmentEnumerator = segmentManager.Playlist.GetEnumerator(); this._webReader = segmentManager.WebReader; this._webMetadataFactory = webMetadataFactory; this._retryManager = retryManager; this._platformServices = platformServices; }
public HlsStreamSegments(M3U8Parser parser, IWebReader webReader, IRetryManager retryManager, IPlatformServices platformServices) { if (null == parser) { throw new ArgumentNullException("parser"); } if (null == webReader) { throw new ArgumentNullException("webReader"); } if (null == retryManager) { throw new ArgumentNullException("retryManager"); } if (null == platformServices) { throw new ArgumentNullException("platformServices"); } this._parser = parser; this._webReader = webReader; this._retryManager = retryManager; this._platformServices = platformServices; this._mediaSequence = M3U8Tags.ExtXMediaSequence.GetValue <long>(parser.GlobalTags); }
public async Task <IDictionary <long, Program.Program> > LoadAsync(CancellationToken cancellationToken) { var playlists = Playlists; foreach (var uri in playlists) { try { var parser = new M3U8Parser(); _playlistWebReader?.Dispose(); _playlistWebReader = _webReaderManager.CreateReader(uri, ContentKind.Playlist); var actualPlaylist = await parser.ParseAsync(_playlistWebReader, _retryManager, uri, cancellationToken).ConfigureAwait(false); var dictionary = await LoadAsync(_playlistWebReader, parser, cancellationToken); return(dictionary); } catch (WebException ex) { Debug.WriteLine("HlsProgramManager.LoadAsync: " + ex.Message); } } return(_noPrograms); }
public IHlsStreamSegments Create(M3U8Parser parser, IWebReader webReader) { return((IHlsStreamSegments) new HlsStreamSegments(parser, webReader, this._retryManager, this._platformServices)); }
public IHlsStreamSegments Create(M3U8Parser parser, IWebReader webReader) { return new HlsStreamSegments(parser, webReader, _retryManager, _platformServices); }
public virtual IWebCache CreateWebCache(Uri url, ContentKind contentKind, IWebReader parent = null, ContentType contentType = null) { return((IWebCache) new HttpConnectionWebCache(this.CreateHttpConnectionWebReader(url, parent, contentType), this._retryManager)); }
public virtual async Task <ContentType> DetectContentTypeAsync(Uri url, ContentKind contentKind, CancellationToken cancellationToken, IWebReader parent = null) { ContentType contentType = EnumerableExtensions.SingleOrDefaultSafe <ContentType>((IEnumerable <ContentType>) this._contentTypeDetector.GetContentType(url, (string)null, (string)null)); ContentType contentType1; if ((ContentType)null != contentType) { Debug.WriteLine("HttpConnectionWebReaderManager.DetectContentTypeAsync() url ext \"{0}\" type {1}", (object)url, (object)contentType); contentType1 = contentType; } else { try { using (IHttpConnectionResponse connectionResponse = await this.SendAsync(url, parent, cancellationToken, "HEAD", (ContentType)null, false, (Uri)null, new long?(), new long?()).ConfigureAwait(false)) { contentType = EnumerableExtensions.SingleOrDefaultSafe <ContentType>((IEnumerable <ContentType>) this._contentTypeDetector.GetContentType(connectionResponse.ResponseUri, Enumerable.FirstOrDefault <string>(connectionResponse.Headers["Content-Type"]), (string)null)); if ((ContentType)null != contentType) { Debug.WriteLine("HttpConnectionWebReaderManager.DetectContentTypeAsync() url HEAD \"{0}\" type {1}", (object)url, (object)contentType); contentType1 = contentType; goto label_29; } } } catch (WebException ex) { } try { using (IHttpConnectionResponse connectionResponse = await this.SendAsync(url, parent, cancellationToken, (string)null, (ContentType)null, false, (Uri)null, new long?(0L), new long?(0L)).ConfigureAwait(false)) { contentType = EnumerableExtensions.SingleOrDefaultSafe <ContentType>((IEnumerable <ContentType>) this._contentTypeDetector.GetContentType(connectionResponse.ResponseUri, Enumerable.FirstOrDefault <string>(connectionResponse.Headers["Content-Type"]), (string)null)); if ((ContentType)null != contentType) { Debug.WriteLine("HttpConnectionWebReaderManager.DetectContentTypeAsync() url range GET \"{0}\" type {1}", (object)url, (object)contentType); contentType1 = contentType; goto label_29; } } } catch (WebException ex) { } try { using (IHttpConnectionResponse connectionResponse = await this.SendAsync(url, parent, cancellationToken, (string)null, (ContentType)null, false, (Uri)null, new long?(), new long?()).ConfigureAwait(false)) { contentType = EnumerableExtensions.SingleOrDefaultSafe <ContentType>((IEnumerable <ContentType>) this._contentTypeDetector.GetContentType(connectionResponse.ResponseUri, Enumerable.FirstOrDefault <string>(connectionResponse.Headers["Content-Type"]), (string)null)); if ((ContentType)null != contentType) { Debug.WriteLine("HttpConnectionWebReaderManager.DetectContentTypeAsync() url GET \"{0}\" type {1}", (object)url, (object)contentType); contentType1 = contentType; goto label_29; } } } catch (WebException ex) { } Debug.WriteLine("HttpConnectionWebReaderManager.DetectContentTypeAsync() url header \"{0}\" unknown type", (object)url); contentType1 = (ContentType)null; } label_29: return(contentType1); }
async Task<IDictionary<long, Program>> LoadAsync(IWebReader webReader, M3U8Parser parser, ContentType contentType, CancellationToken cancellationToken) { var audioStreams = new Dictionary<string, MediaGroup>(); foreach (var gt in parser.GlobalTags) { if (M3U8Tags.ExtXMedia == gt.Tag) { try { var audioAttribute = gt.Attribute(ExtMediaSupport.AttrType, "AUDIO"); if (null != audioAttribute) AddMedia(parser.BaseUrl, gt, audioStreams); } catch (NullReferenceException) { // DynamicObject isn't welcome on the phone or this would be a binding exception. } } } var programs = new Dictionary<long, Program>(); var hasSegments = false; foreach (var p in parser.Playlist) { if (null == p.Tags || p.Tags.Length < 1) { hasSegments = true; continue; } var streamInf = M3U8Tags.ExtXStreamInf.Find(p.Tags); var programId = long.MinValue; MediaGroup audioGroup = null; if (null != streamInf) { var programIdAttribute = streamInf.Attribute(ExtStreamInfSupport.AttrProgramId); if (null != programIdAttribute) programId = programIdAttribute.Value; var audioAttribute = streamInf.AttributeObject(ExtStreamInfSupport.AttrAudio); if (null != audioAttribute) audioStreams.TryGetValue(audioAttribute, out audioGroup); var playlistUrl = parser.ResolveUrl(p.Uri); var bandwidth = streamInf.Attribute(ExtStreamInfSupport.AttrBandwidth); var resolution = streamInf.AttributeInstance<ResolutionAttributeInstance>(ExtStreamInfSupport.AttrResolution); var programUrl = parser.BaseUrl; var program = GetProgram(programs, programId, programUrl); var hlsProgramStream = _programStreamFactory.Create(new[] { playlistUrl }, webReader, ContentType, StreamContentType); var subProgram = new PlaylistSubProgram(program, hlsProgramStream) { Bandwidth = null == bandwidth ? 0 : bandwidth.Value, Playlist = playlistUrl, AudioGroup = audioGroup }; if (null != resolution) { subProgram.Width = resolution.X; subProgram.Height = resolution.Y; } program.SubPrograms.Add(subProgram); } else hasSegments = true; } if (hasSegments) { var program = GetProgram(programs, long.MinValue, parser.BaseUrl); var hlsProgramStream = _programStreamFactory.Create(new[] { webReader.RequestUri }, webReader, ContentType, StreamContentType); await hlsProgramStream.SetParserAsync(parser, cancellationToken).ConfigureAwait(false); var subProgram = new PlaylistSubProgram(program, hlsProgramStream); program.SubPrograms.Add(subProgram); } return programs; }
public SimpleSegmentManager(IWebReader webReader, IEnumerable <Uri> urls, ContentType contentType) : base(webReader, (ICollection <ISegment>)Enumerable.ToArray <ISegment>(Enumerable.Select <Uri, ISegment>(urls, (Func <Uri, ISegment>)(url => (ISegment) new SimpleSegment(url, webReader == null ? (Uri)null : webReader.RequestUri ?? webReader.BaseAddress)))), contentType) { }
public virtual async Task<ContentType> DetectContentTypeAsync(Uri url, ContentKind requiredKind, CancellationToken cancellationToken, IWebReader parent = null) { var contentType = _contentTypeDetector.GetContentType(url, requiredKind).SingleOrDefaultSafe(); if (null != contentType) { Debug.WriteLine("WinRtHttpClientWebReaderManager.DetectContentTypeAsync() url ext \"{0}\" type {1}", url, contentType); return contentType; } var referrer = GetReferrer(parent); using (var httpClient = _httpClientFactory.CreateClient(url, referrer)) { try { using (var request = new HttpRequestMessage(HttpMethod.Head, url)) using (var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken, referrer, null, null).ConfigureAwait(false)) { if (response.IsSuccessStatusCode) { contentType = _contentTypeDetector.GetContentType(request.RequestUri, requiredKind, response.Content.Headers, response.Content.FileName()).SingleOrDefaultSafe(); if (null != contentType) { Debug.WriteLine("WinRtHttpClientWebReaderManager.DetectContentTypeAsync() url HEAD \"{0}\" type {1}", url, contentType); return contentType; } } } } catch (Exception) { // Well, HEAD didn't work... } try { using (var request = new HttpRequestMessage(HttpMethod.Get, url)) using (var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken, referrer, 0, 0).ConfigureAwait(false)) { if (response.IsSuccessStatusCode) { contentType = _contentTypeDetector.GetContentType(request.RequestUri, requiredKind, response.Content.Headers, response.Content.FileName()).SingleOrDefaultSafe(); if (null != contentType) { Debug.WriteLine("WinRtHttpClientWebReaderManager.DetectContentTypeAsync() url range GET \"{0}\" type {1}", url, contentType); return contentType; } } } } catch (Exception) { // Well, a ranged GET didn't work either. } try { using (var request = new HttpRequestMessage(HttpMethod.Get, url)) using (var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken, referrer, null, null).ConfigureAwait(false)) { if (response.IsSuccessStatusCode) { contentType = _contentTypeDetector.GetContentType(request.RequestUri, requiredKind, response.Content.Headers, response.Content.FileName()).SingleOrDefaultSafe(); if (null != contentType) { Debug.WriteLine("WinRtHttpClientWebReaderManager.DetectContentTypeAsync() url GET \"{0}\" type {1}", url, contentType); return contentType; } } } } catch (Exception) { // This just isn't going to work. } } Debug.WriteLine("WinRtHttpClientWebReaderManager.DetectContentTypeAsync() url header \"{0}\" unknown type", url); return null; }
public virtual IWebReader CreateReader(Uri url, ContentKind requiredKind, IWebReader parent = null, ContentType contentType = null) { return CreateHttpConnectionWebReader(url, requiredKind, parent, contentType); }
protected static Uri GetReferrer(Uri url, IWebReader parent) { if (null == parent || null == url) return null; var parentUrl = parent.RequestUri ?? parent.BaseAddress; if (parentUrl == url) return null; return parentUrl; }
internal virtual HttpConnectionRequest CreateRequest(Uri url, Uri referrer, IWebReader parent, ContentType contentType, string method = null, bool allowBuffering = false, long? fromBytes = null, long? toBytes = null) { referrer = referrer ?? GetReferrer(url, parent); if (null == url && null != parent) url = parent.RequestUri ?? parent.BaseAddress; if (null != referrer && (null == url || !url.IsAbsoluteUri)) url = new Uri(referrer, url); var request = _httpConnectionRequestFactory.CreateRequest(url, referrer, contentType, fromBytes, toBytes, _webReaderManagerParameters.DefaultHeaders); return request; }
public IHlsProgramStream Create(ICollection <Uri> urls, IWebReader webReader) { return((IHlsProgramStream) new HlsProgramStream(webReader, urls, this._segmentsFactory, this._webMetadataFactory, this._platformServices, this._retryManager)); }
protected static Uri GetUrl(Uri url, IWebReader parent) { if (null == url && null != parent) url = parent.RequestUri ?? parent.BaseAddress; return url; }
public async Task <IMediaStreamConfigurator> OpenMediaAsync(ICollection <Uri> source, CancellationToken cancellationToken) { this.State = MediaManagerState.OpenMedia; WebResponse response = new WebResponse(); IMediaStreamConfigurator streamConfigurator; using (IWebReader rootReader = WebReaderManagerExtensions.CreateRootReader(this._webReaderManager, (ContentType)null)) { using (IEnumerator <Uri> enumerator = source.GetEnumerator()) { label_25: if (enumerator.MoveNext()) { Uri url = enumerator.Current; IWebReader webReader = (IWebReader)null; IWebStreamResponse webStream = (IWebStreamResponse)null; CancellationTokenSource playCancellationTokenSource = (CancellationTokenSource)null; Task playTask = (Task)null; try { webReader = WebReaderExtensions.CreateChild(rootReader, url, ContentKind.Unknown, this.ContentType); webStream = await webReader.GetWebStreamAsync((Uri)null, false, cancellationToken, (Uri)null, new long?(), new long?(), response).ConfigureAwait(false); if (webStream.IsSuccessStatusCode) { ContentType contentType = response.ContentType; if (!((ContentType)null == contentType)) { if ((ContentType)null == contentType || ContentKind.Playlist == contentType.Kind) { throw new FileNotFoundException("Content not supported with this media manager"); } TaskCompletionSource <bool> configurationTaskCompletionSource = new TaskCompletionSource <bool>(); playCancellationTokenSource = new CancellationTokenSource(); CancellationTokenSource localPlayCancellationTokenSource = playCancellationTokenSource; Task cancelPlayTask = configurationTaskCompletionSource.Task.ContinueWith((Action <Task <bool> >)(t => { if (!t.IsFaulted && !t.IsCanceled) { return; } localPlayCancellationTokenSource.Cancel(); })); TaskCollector.Default.Add(cancelPlayTask, "SingleStreamMediaManager play cancellation"); IWebReader localWebReader = webReader; IWebStreamResponse localWebStream = webStream; CancellationToken playCancellationToken = playCancellationTokenSource.Token; playTask = TaskEx.Run((Func <Task>)(() => this.SimplePlayAsync(contentType, localWebReader, localWebStream, response, configurationTaskCompletionSource, playCancellationToken)), playCancellationToken); bool lockTaken = false; object obj; try { Monitor.Enter(obj = this._lock, ref lockTaken); this._playCancellationTokenSource = playCancellationTokenSource; playCancellationTokenSource = (CancellationTokenSource)null; this._playTask = playTask; playTask = (Task)null; } finally { if (lockTaken) { Monitor.Exit(obj); } } bool isConfigured = await configurationTaskCompletionSource.Task.ConfigureAwait(false); if (isConfigured) { webReader = (IWebReader)null; webStream = (IWebStreamResponse)null; streamConfigurator = this._mediaStreamConfigurator; goto label_33; } else { goto label_25; } } else { goto label_25; } } else { goto label_25; } } finally { if (null != webStream) { webStream.Dispose(); } if (null != webReader) { webReader.Dispose(); } if (null != playCancellationTokenSource) { playCancellationTokenSource.Cancel(); } if (null != playTask) { TaskCollector.Default.Add(playTask, "SingleStreamMediaManager play task"); } } } } } throw new FileNotFoundException(); label_33: return(streamConfigurator); }
public virtual async Task<ContentType> DetectContentTypeAsync(Uri url, ContentKind requiredKind, CancellationToken cancellationToken, IWebReader parent = null) { var contentType = _contentTypeDetector.GetContentType(url, requiredKind).SingleOrDefaultSafe(); if (null != contentType) { Debug.WriteLine("HttpConnectionWebReaderManager.DetectContentTypeAsync() url ext \"{0}\" type {1}", url, contentType); return contentType; } try { using (var response = await SendAsync(url, parent, cancellationToken, "HEAD", allowBuffering: false).ConfigureAwait(false)) { if (response.IsSuccessStatusCode) contentType = _contentTypeDetector.GetContentType(response.ResponseUri, requiredKind, response.Headers["Content-Type"].FirstOrDefault()).SingleOrDefaultSafe(); if (null != contentType) { Debug.WriteLine("HttpConnectionWebReaderManager.DetectContentTypeAsync() url HEAD \"{0}\" type {1}", url, contentType); return contentType; } } } catch (StatusCodeWebException) { // Well, HEAD didn't work... } try { using (var response = await SendAsync(url, parent, cancellationToken, allowBuffering: false, fromBytes: 0, toBytes: 0).ConfigureAwait(false)) { if (response.IsSuccessStatusCode) contentType = _contentTypeDetector.GetContentType(response.ResponseUri, requiredKind, response.Headers["Content-Type"].FirstOrDefault()).SingleOrDefaultSafe(); if (null != contentType) { Debug.WriteLine("HttpConnectionWebReaderManager.DetectContentTypeAsync() url range GET \"{0}\" type {1}", url, contentType); return contentType; } } } catch (StatusCodeWebException) { // Well, a ranged GET didn't work either. } try { using (var response = await SendAsync(url, parent, cancellationToken, allowBuffering: false).ConfigureAwait(false)) { if (response.IsSuccessStatusCode) contentType = _contentTypeDetector.GetContentType(response.ResponseUri, requiredKind, response.Headers["Content-Type"].FirstOrDefault()).SingleOrDefaultSafe(); if (null != contentType) { Debug.WriteLine("HttpConnectionWebReaderManager.DetectContentTypeAsync() url GET \"{0}\" type {1}", url, contentType); return contentType; } } } catch (StatusCodeWebException) { // This just isn't going to work. } Debug.WriteLine("HttpConnectionWebReaderManager.DetectContentTypeAsync() url header \"{0}\" unknown type", url); return null; }
private async Task SimplePlayAsync(ContentType contentType, IWebReader webReader, IWebStreamResponse webStreamResponse, WebResponse webResponse, TaskCompletionSource <bool> configurationTaskCompletionSource, CancellationToken cancellationToken) { try { this._mediaStreamConfigurator.Initialize(); this._mediaStreamConfigurator.MediaManager = (IMediaManager)this; IMediaParser mediaParser = await this._mediaParserFactory.CreateAsync((IMediaParserParameters) new MediaParserParameters(), contentType, cancellationToken).ConfigureAwait(false); if (null == mediaParser) { throw new NotSupportedException("Unsupported content type: " + (object)contentType); } this.State = MediaManagerState.Opening; EventHandler configurationComplete = (EventHandler)null; configurationComplete = (EventHandler)((sender, args) => { mediaParser.ConfigurationComplete -= configurationComplete; configurationTaskCompletionSource.TrySetResult(true); }); mediaParser.ConfigurationComplete += configurationComplete; using (IBufferingManager bufferingManager = this._bufferingManagerFactory()) { SingleStreamMediaManager.QueueThrottle throttle = new SingleStreamMediaManager.QueueThrottle(); bufferingManager.Initialize((IQueueThrottling)throttle, new Action(this._mediaStreamConfigurator.CheckForSamples)); mediaParser.Initialize(bufferingManager, (Action <IProgramStreams>)null); IStreamMetadata streamMetadata = this._webMetadataFactory.CreateStreamMetadata(webResponse, (ContentType)null); mediaParser.InitializeStream(streamMetadata); Task reader = (Task)null; try { using (webReader) { try { if (null == webStreamResponse) { webStreamResponse = await webReader.GetWebStreamAsync((Uri)null, false, cancellationToken, (Uri)null, new long?(), new long?(), webResponse).ConfigureAwait(false); } reader = this.ReadResponseAsync(mediaParser, webStreamResponse, webResponse, throttle, cancellationToken); Task task = await TaskEx.WhenAny((Task)configurationTaskCompletionSource.Task, CancellationTokenExtensions.AsTask(cancellationToken)).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); await MediaStreamSourceExtensions.PlayAsync(this._mediaStreamConfigurator, (IEnumerable <IMediaParserMediaStream>) mediaParser.MediaStreams, new TimeSpan?(), cancellationToken).ConfigureAwait(false); this.State = MediaManagerState.Playing; await reader.ConfigureAwait(false); reader = (Task)null; } finally { if (null != webStreamResponse) { webStreamResponse.Dispose(); } } } } catch (OperationCanceledException ex) { } catch (Exception ex) { string message = ExceptionExtensions.ExtendedMessage(ex); Debug.WriteLine("SingleStreamMediaManager.SimplePlayAsync() failed: " + message); this.SetMediaState(MediaManagerState.Error, message); } this.State = MediaManagerState.Closing; if (null != reader) { try { await reader.ConfigureAwait(false); } catch (OperationCanceledException ex) { } catch (Exception ex) { Debug.WriteLine("SingleStreamMediaManager.SimplePlayAsync() reader failed: " + ExceptionExtensions.ExtendedMessage(ex)); } } mediaParser.ConfigurationComplete -= configurationComplete; mediaParser.EnableProcessing = false; mediaParser.FlushBuffers(); bufferingManager.Flush(); bufferingManager.Shutdown((IQueueThrottling)throttle); await this._mediaStreamConfigurator.CloseAsync().ConfigureAwait(false); } } catch (Exception ex) { Debug.WriteLine("SingleStreamMediaManager.SimplePlayAsync() cleanup failed: " + ExceptionExtensions.ExtendedMessage(ex)); } this._mediaStreamConfigurator.MediaManager = (IMediaManager)null; if (!configurationTaskCompletionSource.Task.IsCompleted) { configurationTaskCompletionSource.TrySetCanceled(); } this.State = MediaManagerState.Closed; await this._reportStateTask.WaitAsync().ConfigureAwait(false); }
internal Task<IHttpConnectionResponse> SendAsync(Uri url, IWebReader parent, CancellationToken cancellationToken, string method = null, ContentType contentType = null, bool allowBuffering = true, Uri referrer = null, long? fromBytes = null, long? toBytes = null) { var request = CreateRequest(url, referrer, parent, contentType, method, allowBuffering, fromBytes, toBytes); return GetAsync(request, cancellationToken); }
protected virtual async Task<ISegmentManager> ReadPlaylistAsync(IWebReader webReader, Uri url, Stream stream, ContentType contentType, ContentType streamContentType, CancellationToken cancellationToken) { var pls = new PlsParser(url); using (var tr = new StreamReader(stream)) { var ret = await pls.ParseAsync(tr).ConfigureAwait(false); if (!ret) return null; } return await CreateManagerAsync(pls, webReader, contentType, streamContentType, cancellationToken).ConfigureAwait(false); }
protected virtual HttpConnectionWebReader CreateHttpConnectionWebReader(Uri url, ContentKind requiredKind, IWebReader parent = null, ContentType contentType = null) { if (null == contentType && null != url) contentType = _contentTypeDetector.GetContentType(url, requiredKind).SingleOrDefaultSafe(); return new HttpConnectionWebReader(this, url, parent?.BaseAddress, contentType, _contentTypeDetector); }
public Task<ICollection<ISegment>> CreateSegmentsAsync(M3U8Parser parser, IWebReader webReader, CancellationToken cancellationToken) { var streamSegments = _streamSegmentsFactory.Create(parser, webReader); return streamSegments.CreateSegmentsAsync(cancellationToken); }
public StooqRepository(IWebReader reader) { Reader = reader; }
protected virtual async Task <ISegmentManager> CreateManagerAsync(PlsParser pls, IWebReader webReader, CancellationToken cancellationToken) { Uri trackUrl = await this._plsSegmentManagerPolicy.GetTrackAsync(pls, webReader.ContentType, cancellationToken); ISegmentManager segmentManager; if ((Uri)null == trackUrl) { segmentManager = (ISegmentManager)null; } else { ContentType contentType = await WebReaderExtensions.DetectContentTypeAsync(webReader, trackUrl, ContentKind.AnyMedia, cancellationToken).ConfigureAwait(false); if ((ContentType)null == contentType) { Debug.WriteLine("PlsSegmentManagerFactory.CreateSegmentManager() unable to detect type for " + (object)trackUrl); segmentManager = (ISegmentManager)null; } else { segmentManager = (ISegmentManager) new SimpleSegmentManager(webReader, (IEnumerable <Uri>) new Uri[1] { trackUrl }, contentType); } } return(segmentManager); }
protected static Uri GetReferrer(IWebReader parent) { return null == parent ? null : parent.RequestUri ?? parent.BaseAddress; }
async Task SimplePlayAsync(ContentType contentType, IWebReader webReader, IWebStreamResponse webStreamResponse, WebResponse webResponse, TaskCompletionSource<bool> configurationTaskCompletionSource, CancellationToken cancellationToken) { try { _mediaStreamConfigurator.Initialize(); _mediaStreamConfigurator.MediaManager = this; var mediaParser = await _mediaParserFactory.CreateAsync(new MediaParserParameters(), contentType, cancellationToken).ConfigureAwait(false); if (null == mediaParser) throw new NotSupportedException("Unsupported content type: " + contentType); State = MediaManagerState.Opening; EventHandler configurationComplete = null; configurationComplete = (sender, args) => { // ReSharper disable once AccessToModifiedClosure mediaParser.ConfigurationComplete -= configurationComplete; configurationTaskCompletionSource.TrySetResult(true); }; mediaParser.ConfigurationComplete += configurationComplete; using (var bufferingManager = _bufferingManagerFactory()) { var throttle = new QueueThrottle(); bufferingManager.Initialize(throttle, _mediaStreamConfigurator.CheckForSamples); mediaParser.Initialize(bufferingManager); var streamMetadata = _webMetadataFactory.CreateStreamMetadata(webResponse); mediaParser.InitializeStream(streamMetadata); Task reader = null; try { using (webReader) { try { if (null == webStreamResponse) webStreamResponse = await webReader.GetWebStreamAsync(null, false, cancellationToken, response: webResponse).ConfigureAwait(false); reader = ReadResponseAsync(mediaParser, webStreamResponse, webResponse, throttle, cancellationToken); await Task.WhenAny(configurationTaskCompletionSource.Task, cancellationToken.AsTask()).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); await _mediaStreamConfigurator.PlayAsync(mediaParser.MediaStreams, null, cancellationToken).ConfigureAwait(false); State = MediaManagerState.Playing; await reader.ConfigureAwait(false); reader = null; } finally { if (null != webStreamResponse) webStreamResponse.Dispose(); } } } catch (OperationCanceledException) { } catch (Exception ex) { var message = ex.ExtendedMessage(); Debug.WriteLine("SingleStreamMediaManager.SimplePlayAsync() failed: " + message); SetMediaState(MediaManagerState.Error, message); } State = MediaManagerState.Closing; if (null != reader) { try { await reader.ConfigureAwait(false); } catch (OperationCanceledException) { } catch (Exception ex) { Debug.WriteLine("SingleStreamMediaManager.SimplePlayAsync() reader failed: " + ex.ExtendedMessage()); } } mediaParser.ConfigurationComplete -= configurationComplete; mediaParser.EnableProcessing = false; mediaParser.FlushBuffers(); bufferingManager.Flush(); bufferingManager.Shutdown(throttle); await _mediaStreamConfigurator.CloseAsync().ConfigureAwait(false); } } catch (Exception ex) { Debug.WriteLine("SingleStreamMediaManager.SimplePlayAsync() cleanup failed: " + ex.ExtendedMessage()); } _mediaStreamConfigurator.MediaManager = null; if (!configurationTaskCompletionSource.Task.IsCompleted) configurationTaskCompletionSource.TrySetCanceled(); State = MediaManagerState.Closed; await _reportStateTask.WaitAsync().ConfigureAwait(false); }
protected virtual async Task <ISegmentManager> CreateManagerAsync(PlsParser pls, IWebReader webReader, CancellationToken cancellationToken) { var trackUrl = await _plsSegmentManagerPolicy.GetTrackAsync(pls, webReader.ContentType, cancellationToken); ISegmentManager segmentManager; if (null == trackUrl) { segmentManager = null; } else { var contentType = await webReader.DetectContentTypeAsync(trackUrl, ContentKind.AnyMedia, cancellationToken); if (null == contentType) { Debug.WriteLine("PlsSegmentManagerFactory.CreateSegmentManager() unable to detect type for " + trackUrl); segmentManager = null; } else { segmentManager = new SimpleSegmentManager(webReader, new[] { trackUrl }, contentType); } } return(segmentManager); }
public virtual IWebCache CreateWebCache(Uri url, ContentKind requiredKind, IWebReader parent = null, ContentType contentType = null) { var webReader = CreateHttpConnectionWebReader(url, requiredKind, parent, contentType); return new HttpConnectionWebCache(webReader, _retryManager); }
public SimpleSegmentManager(IWebReader webReader, IEnumerable<Uri> urls, ContentType contentType, ContentType streamContentType) : base(webReader, urls.Select<Uri, ISegment>(url => new SimpleSegment(url, null == webReader ? null : webReader.RequestUri ?? webReader.BaseAddress)).ToArray(), contentType, streamContentType) { }