private void DownloadRequested(AdaptiveMediaSource sender, AdaptiveMediaSourceDownloadRequestedEventArgs args)
        {
            // rewrite key URIs to replace http:// with https://
            if (args.ResourceType == AdaptiveMediaSourceResourceType.Key)
            {
                string originalUri = args.ResourceUri.ToString();
                string secureUri = originalUri.Replace("http:", "https:");

                // override the URI by setting property on the result sub object
                args.Result.ResourceUri = new Uri(secureUri);
            }
        }
示例#2
0
        //<SnippetAMSDownloadCompleted>
        private void DownloadCompleted(AdaptiveMediaSource sender, AdaptiveMediaSourceDownloadCompletedEventArgs args)
        {
            var statistics = args.Statistics;

            MyLogMessageFunction("download completed for: " + args.ResourceType + " - " +
                                 args.ResourceUri +
                                 " – RequestId:" + args.RequestId +
                                 " – Position:" + args.Position +
                                 " - TimeToHeadersReceived:" + statistics.TimeToHeadersReceived +
                                 " - TimeToFirstByteReceived:" + statistics.TimeToFirstByteReceived +
                                 " - TimeToLastByteReceived:" + statistics.TimeToLastByteReceived +
                                 " - ContentBytesReceivedCount:" + statistics.ContentBytesReceivedCount);
        }
示例#3
0
        private async Task RefreshLeoPlayer()
        {
            if (_HLSUri == null)
            {
                return;
            }

            await ClearLeoPlayer();


            _UIScheduler.Schedule(async() =>
            {
                try
                {
                    // 視聴開始後にスタート時間に自動シーク
                    string hlsUri = _HLSUri;
                    if (IsWatchWithTimeshift && TimeshiftPosition != null)
                    {
                        hlsUri = MakeSeekedHLSUri(_HLSUri, TimeshiftPosition.Value);
#if DEBUG
                        Debug.WriteLine(hlsUri);
#endif
                    }

                    var amsCreateResult = await AdaptiveMediaSource.CreateFromUriAsync(new Uri(hlsUri), NiconicoSession.Context.HttpClient);
                    if (amsCreateResult.Status == AdaptiveMediaSourceCreationStatus.Success)
                    {
                        var ams              = amsCreateResult.MediaSource;
                        _MediaSource         = MediaSource.CreateFromAdaptiveMediaSource(ams);
                        _AdaptiveMediaSource = ams;


                        ams.Diagnostics.DiagnosticAvailable += Diagnostics_DiagnosticAvailable;
                    }

                    MediaPlayer.Source = _MediaSource;

                    // タイムシフトで見ている場合はコメントのシークも行う
                    if (IsWatchWithTimeshift)
                    {
                        await ClearCommentsCacheAsync();
                        _LiveComments.Clear();
                        _NicoLiveCommentClient.Seek(TimeshiftPosition.Value);
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.ToString());
                }
            });
        }
        async private void InitializeAdaptiveMediaSource(System.Uri uri, MediaElement m)
        {
            AdaptiveMediaSourceCreationResult result = await AdaptiveMediaSource.CreateFromUriAsync(uri);

            if (result.Status == AdaptiveMediaSourceCreationStatus.Success)
            {
                ams = result.MediaSource;
                SetUpProtectionManager(ref m);
                m.SetMediaStreamSource(ams);
            }
            else
            {
                rootPage.NotifyUser("Error creating the AdaptiveMediaSource\n\t" + result.Status, NotifyType.ErrorMessage);
            }
        }
 async private void InitializeAdaptiveMediaSource(System.Uri uri, MediaElement m)
 {
    
     AdaptiveMediaSourceCreationResult result = await AdaptiveMediaSource.CreateFromUriAsync(uri);
     if (result.Status == AdaptiveMediaSourceCreationStatus.Success)
     {
         ams = result.MediaSource;
         SetUpProtectionManager(ref m);
         m.SetMediaStreamSource(ams);
     }
     else
     {
         rootPage.NotifyUser("Error creating the AdaptiveMediaSource\n\t" + result.Status, NotifyType.ErrorMessage);
     }
 }
示例#6
0
        // <SnippetBinderBindingAMS>
        private async void Binder_Binding_AdaptiveMediaSource(MediaBinder sender, MediaBindingEventArgs args)
        {
            var deferral = args.GetDeferral();

            var contentUri = new Uri("http://contoso.com/media/" + args.MediaBinder.Token);
            AdaptiveMediaSourceCreationResult result = await AdaptiveMediaSource.CreateFromUriAsync(contentUri);

            if (result.MediaSource != null)
            {
                args.SetAdaptiveMediaSource(result.MediaSource);
            }
            args.SetUri(contentUri);

            deferral.Complete();
        }
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            var uri = new Uri("http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8");

            var source = await AdaptiveMediaSource.CreateFromUriAsync(uri);

            if (source.Status != AdaptiveMediaSourceCreationStatus.Success)
            {
                return;
            }

            MediaPlayer.SetMediaStreamSource(source.MediaSource);
        }
示例#8
0
        private void UpdateSeekableWindowControls(AdaptiveMediaSource adaptiveMediaSource)
        {
            if (adaptiveMediaSource == null)
            {
                return;
            }

            var task = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                MaxSeekableWindowSize.Text     = adaptiveMediaSource.MaxSeekableWindowSize.HasValue ? $"{adaptiveMediaSource.MaxSeekableWindowSize.Value.ToString("c")}" : "";
                DesiredSeekableWindowSize.Text = adaptiveMediaSource.DesiredSeekableWindowSize.HasValue ? $"{adaptiveMediaSource.DesiredSeekableWindowSize.Value.ToString("c")}" : "";
                DesiredLiveOffset.Text         = $"{adaptiveMediaSource.DesiredLiveOffset.ToString("c")}";
                MinLiveOffset.Text             = adaptiveMediaSource.MinLiveOffset.HasValue ? $"{adaptiveMediaSource.MinLiveOffset.Value.ToString("c")}" : "";
            });
        }
示例#9
0
        public async void InitEmsgCueScenario()
        {
            // <SnippetEmsgLoadContent>
            AdaptiveMediaSourceCreationResult result =
                await AdaptiveMediaSource.CreateFromUriAsync(new Uri("http://contoso.com/playlist.m3u"));

            if (result.Status != AdaptiveMediaSourceCreationStatus.Success)
            {
                // TODO: Handle adaptive media source creation errors.
                return;
            }
            var mediaSource       = MediaSource.CreateFromAdaptiveMediaSource(result.MediaSource);
            var mediaPlaybackItem = new MediaPlaybackItem(mediaSource);

            // </SnippetEmsgLoadContent>

            // <SnippetEmsgCueTracksChanged>
            mediaPlaybackItem.TimedMetadataTracksChanged += (MediaPlaybackItem sender, IVectorChangedEventArgs args) =>
            {
                if (args.CollectionChange == CollectionChange.ItemInserted)
                {
                    RegisterMetadataHandlerForEmsgCues(sender, (int)args.Index);
                }
                else if (args.CollectionChange == CollectionChange.Reset)
                {
                    for (int index = 0; index < sender.TimedMetadataTracks.Count; index++)
                    {
                        if (sender.TimedMetadataTracks[index].TimedMetadataKind == TimedMetadataKind.ImageSubtitle)
                        {
                            RegisterMetadataHandlerForEmsgCues(sender, index);
                        }
                    }
                }
            };

            for (int index = 0; index < mediaPlaybackItem.TimedMetadataTracks.Count; index++)
            {
                RegisterMetadataHandlerForEmsgCues(mediaPlaybackItem, index);
            }
            // </SnippetEmsgCueTracksChanged>

            // <SnippetEmsgCuePlay>
            _mediaPlayer = new MediaPlayer();
            mediaPlayerElement.SetMediaPlayer(_mediaPlayer);
            _mediaPlayer.Source = mediaPlaybackItem;
            _mediaPlayer.Play();
            // </SnippetEmsgCuePlay>
        }
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            try
            {
                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    player.Visibility   = Visibility.Collapsed;
                    progress.Visibility = Visibility.Visible;

                    string       videoId = String.Empty;
                    YoutubeVideo video   = e.Parameter as YoutubeVideo;
                    if (video != null && !video.Id.Equals(String.Empty))
                    {
                        if (video.IsLive)
                        {
                            var streamResponse = await AdaptiveMediaSource.CreateFromUriAsync(new Uri(video.YoutubeLink));

                            if (streamResponse.Status == AdaptiveMediaSourceCreationStatus.Success)
                            {
                                player.SetMediaStreamSource(streamResponse.MediaSource);
                            }
                        }
                        else
                        {
                            //-----Get The Video Uri and set it as a player source-------//
                            var url = await YouTube.GetVideoUriAsync(video.Id, YouTubeQuality.Quality480P);

                            player.Source = url.Uri;
                        }
                    }

                    player.Visibility   = Visibility.Visible;
                    progress.Visibility = Visibility.Collapsed;
                }
                else
                {
                    MessageDialog message = new MessageDialog("You're not connected to Internet!");
                    await message.ShowAsync();

                    this.Frame.GoBack();
                }
            }
            catch
            {
            }

            base.OnNavigatedTo(e);
        }
示例#11
0
        // </SnippetAMSDownloadCompleted>

        // <SnippetAMSDownloadFailed>
        private void DownloadFailed(AdaptiveMediaSource sender, AdaptiveMediaSourceDownloadFailedEventArgs args)
        {
            var statistics = args.Statistics;

            MyLogMessageFunction("download failed for: " + args.ResourceType +
                                 " - " + args.ResourceUri +
                                 " – Error:" + args.ExtendedError.HResult +
                                 " - RequestId" + args.RequestId +
                                 " – Position:" + args.Position +
                                 " - Duration:" + args.ResourceDuration +
                                 " - ContentType:" + args.ResourceContentType +
                                 " - TimeToHeadersReceived:" + statistics.TimeToHeadersReceived +
                                 " - TimeToFirstByteReceived:" + statistics.TimeToFirstByteReceived +
                                 " - TimeToLastByteReceived:" + statistics.TimeToLastByteReceived +
                                 " - ContentBytesReceivedCount:" + statistics.ContentBytesReceivedCount);
        }
        private async Task PlayHLS(Uri hsl)
        {
            AdaptiveMediaSourceCreationResult result = await AdaptiveMediaSource.CreateFromUriAsync(hsl);

            if (result.Status == AdaptiveMediaSourceCreationStatus.Success)
            {
                _source = result.MediaSource;
                _source.DownloadRequested      += _source_DownloadRequested;
                _source.DownloadCompleted      += _source_DownloadCompleted;
                _source.DownloadFailed         += _source_DownloadFailed;
                _source.DownloadBitrateChanged += _source_DownloadBitrateChanged;
                _source.PlaybackBitrateChanged += _source_PlaybackBitrateChanged;

                BackgroundMediaPlayer.Current.SetMediaSource(result.MediaSource);
            }
        }
示例#13
0
        private void InitializeBitrateLists(AdaptiveMediaSource aMS)
        {
            var sortedBitrates = aMS.AvailableBitrates.OrderByDescending(br => br).Select(br => new BitrateItem(br)).ToArray();

            InitialBitrateList.ItemsSource = sortedBitrates;
            var selected = sortedBitrates.First(item => item.Bitrate == aMS.InitialBitrate);

            InitialBitrateList.SelectedItem = sortedBitrates.FirstOrDefault(item => item.Bitrate == aMS.InitialBitrate);

            var nullableSortedBitrates = (new BitrateItem[] { new BitrateItem(null) }).Concat(sortedBitrates).ToArray();

            DesiredMaxBitrateList.ItemsSource = DesiredMinBitrateList.ItemsSource = nullableSortedBitrates;

            DesiredMaxBitrateList.SelectedItem = nullableSortedBitrates.First(item => item.Bitrate == aMS.DesiredMaxBitrate);
            DesiredMinBitrateList.SelectedItem = nullableSortedBitrates.First(item => item.Bitrate == aMS.DesiredMinBitrate);
        }
示例#14
0
        public AdaptiveMediaSourceLogger(LogView _logView, AdaptiveMediaSource _adaptiveMediaSource)
        {
            if (_logView == null)
            {
                throw new ArgumentNullException(nameof(_logView));
            }
            this.logView = _logView;

            if (_adaptiveMediaSource == null)
            {
                throw new ArgumentNullException(nameof(_adaptiveMediaSource));
            }
            this.adaptiveMediaSource = _adaptiveMediaSource;

            this.RegisterForAdaptiveMediaSourceEvents();
        }
        private async Task LoadSourceFromUriAsync(Uri uri, HttpClient httpClient = null)
        {
            mediaPlayerElement.MediaPlayer?.DisposeSource();

            AdaptiveMediaSourceCreationResult result = null;

            if (httpClient != null)
            {
                result = await AdaptiveMediaSource.CreateFromUriAsync(uri, httpClient);
            }
            else
            {
                result = await AdaptiveMediaSource.CreateFromUriAsync(uri);
            }
            if (result.Status == AdaptiveMediaSourceCreationStatus.Success)
            {
                adaptiveMS = result.MediaSource;

                bitrateHelper = new BitrateHelper(adaptiveMS.AvailableBitrates);
                InitializeBitrateLists(adaptiveMS);

                // At this point, we have read the manifest of the media source, and all bitrates are known.
                await UpdatePlaybackBitrate(adaptiveMS.CurrentPlaybackBitrate);
                await UpdateDownloadBitrate(adaptiveMS.CurrentDownloadBitrate);

                // Register for events before resolving the MediaSource.
                RegisterForAdaptiveMediaSourceEvents(adaptiveMS);

                MediaSource source = MediaSource.CreateFromAdaptiveMediaSource(adaptiveMS);

                // You can save additional information in the CustomPropertySet for future retrieval.
                // Note: MediaSource.CustomProperties is a ValueSet and therefore can store
                // only serializable types.

                // Save the original Uri.
                source.CustomProperties.Add("uri", uri.ToString());

                // You're likely to put a content tracking id into the CustomProperties.
                source.CustomProperties.Add("contentId", Guid.NewGuid());

                mpItem = new MediaPlaybackItem(source);
            }
            else
            {
                Log("Error creating the AdaptiveMediaSource: " + result.Status);
            }
        }
示例#16
0
        private async void PropChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == nameof(CurrentChannel))
            {
                if (!CurrentChannel.Channel.IsSpecial) // Normal channel
                {
                    OperateMediaStreamResult(await AdaptiveMediaSource.CreateFromUriAsync(new Uri(CurrentChannel.Channel.URL, UriKind.RelativeOrAbsolute)));
                }
                else // Special channel, request for a valid stream url.
                {
                }
            }
            else if (e.PropertyName == nameof(CurrentSource) && CurrentSource != null)
            {
                AvailableBitrates = new ObservableCollection <BitrateModelView>();
                foreach (var bitrate in CurrentSource.AvailableBitrates.Where(a => a != 0))
                {
                    AvailableBitrates.Add(new BitrateModelView()
                    {
                        Bitrate = bitrate
                    });
                }

                OnPropertyChanged("AvailableBitrates");
                if (CurrentSettings.PreferedQuality == QualityEnumModel.Düşük)
                {
                    SelectedBitrate = AvailableBitrates.OrderBy(b => b.Bitrate).FirstOrDefault(a => a.Bitrate == CurrentSource.CurrentPlaybackBitrate);
                }
                else if (CurrentSettings.PreferedQuality == QualityEnumModel.Yüksek)
                {
                    SelectedBitrate = AvailableBitrates.OrderByDescending(b => b.Bitrate).FirstOrDefault(a => a.Bitrate == CurrentSource.CurrentPlaybackBitrate);
                }
                else if (CurrentSettings.PreferedQuality == QualityEnumModel.Orta)
                {
                    SelectedBitrate = AvailableBitrates.OrderBy(b => b.Bitrate).FirstOrDefault(a => a.Bitrate == AvailableBitrates[AvailableBitrates.Count / 2].Bitrate);
                }
            }
            else if (e.PropertyName == nameof(SelectedBitrate) && SelectedBitrate != null && CurrentSource != null && SelectedBitrate.Bitrate != CurrentSource.CurrentPlaybackBitrate)
            {
                CurrentSource.DesiredMinBitrate = SelectedBitrate.Bitrate;
            }
            else if (e.PropertyName == nameof(AllChannels))
            {
                GroupedChannels = AllChannels.OrderBy(b => b.Channel.Name).GroupBy(a => a.Channel.Category);
            }
        }
示例#17
0
        private async Task OpenHlsAsync(DmcSessionResponse session)
        {
            Assert.IsTrue(HttpStatusCodeHelper.IsSuccessStatusCode(session.Meta.Status));
            Debug.WriteLineIf(session.Meta.Message is not null, session.Meta.Message);
            Assert.IsNotNull(session.Data.Session.ContentUri);
            Assert.AreEqual("mpeg2ts", session.Data.Session.Protocol.Parameters.HttpParameters.Parameters.HlsParameters.MediaSegmentFormat);

            // Try open media
            var ams = await AdaptiveMediaSource.CreateFromUriAsync(session.Data.Session.ContentUri, _context.HttpClient);

            Assert.AreEqual(ams.Status, AdaptiveMediaSourceCreationStatus.Success);

            using (var mediaSource = MediaSource.CreateFromAdaptiveMediaSource(ams.MediaSource))
            {
                await mediaSource.OpenAsync();
            }
        }
示例#18
0
        public void Media()
        {
            AdaptiveMediaSource mediaSource1 = new AdaptiveMediaSource
            {
                MimeType = "audio/mp4",
                Url      = "https://www.stuff.com/media.mp4"
            };

            Assert.AreEqual("audio/mp4", mediaSource1.MimeType);
            Assert.AreEqual("https://www.stuff.com/media.mp4", mediaSource1.Url);

            AdaptiveMediaSource mediaSource2 = new AdaptiveMediaSource
            {
                MimeType = "audio/mpeg",
                Url      = "https://www.stuff.com/media.mp3"
            };

            Assert.AreEqual("audio/mpeg", mediaSource2.MimeType);
            Assert.AreEqual("https://www.stuff.com/media.mp3", mediaSource2.Url);

            AdaptiveMedia media = new AdaptiveMedia
            {
                AltText   = "This is some audio",
                Height    = HeightType.Stretch,
                Id        = "MediaId",
                IsVisible = false,
                Poster    = "https://www.stuff.com/poster.jpg",
                Separator = true,
                Spacing   = Spacing.Large
            };

            ValidateBaseElementProperties(media, "MediaId", false, true, Spacing.Large, HeightType.Stretch);

            Assert.AreEqual("This is some audio", media.AltText);
            Assert.AreEqual("https://www.stuff.com/poster.jpg", media.Poster);

            media.Sources.Add(mediaSource1);
            media.Sources.Add(mediaSource2);

            Assert.AreEqual("https://www.stuff.com/media.mp4", media.Sources[0].Url);
            Assert.AreEqual("https://www.stuff.com/media.mp3", media.Sources[1].Url);

            var jsonString = media.ToJson().ToString();

            Assert.AreEqual("{\"altText\":\"This is some audio\",\"height\":\"Stretch\",\"id\":\"MediaId\",\"isVisible\":false,\"poster\":\"https://www.stuff.com/poster.jpg\",\"separator\":true,\"sources\":[{\"mimeType\":\"audio/mp4\",\"url\":\"https://www.stuff.com/media.mp4\"},{\"mimeType\":\"audio/mpeg\",\"url\":\"https://www.stuff.com/media.mp3\"}],\"spacing\":\"large\",\"type\":\"Media\"}", jsonString);
        }
        protected override async Task <MediaSource> GetPlyaingVideoMediaSource()
        {
            if (!NiconicoSession.Context.HttpClient.DefaultRequestHeaders.ContainsKey("Origin"))
            {
                NiconicoSession.Context.HttpClient.DefaultRequestHeaders.Add("Origin", "https://www.nicovideo.jp");
            }

            NiconicoSession.Context.HttpClient.DefaultRequestHeaders.Referer = new Uri($"https://www.nicovideo.jp/watch/{DmcWatchResponse.Video.Id}");


            var session = await GetDmcSessionAsync();

            if (session == null)
            {
                if (DmcWatchResponse.Video.SmileInfo != null)
                {
                    return(MediaSource.CreateFromUri(new Uri(DmcWatchResponse.Video.SmileInfo.Url)));
                }
                else
                {
                    throw new Exception();
                }
            }

            var uri = session != null ? new Uri(session.Data.Session.ContentUri) : null;

            if (session.Data.Session.Protocol.Parameters.HttpParameters.Parameters.HttpOutputDownloadParameters != null)
            {
                return(MediaSource.CreateFromUri(uri));
            }
            else if (session.Data.Session.Protocol.Parameters.HttpParameters.Parameters.HlsParameters != null)
            {
                var hlsParameters = session.Data.Session.Protocol.Parameters.HttpParameters.Parameters.HlsParameters;
                var amsResult     = await AdaptiveMediaSource.CreateFromUriAsync(uri, this.NiconicoSession.Context.HttpClient);

                if (amsResult.Status == AdaptiveMediaSourceCreationStatus.Success)
                {
                    await NiconicoSession.Context.Video.SendOfficialHlsWatchAsync(DmcWatchResponse.Video.Id, DmcWatchResponse.Video.DmcInfo.TrackingId);

                    return(MediaSource.CreateFromAdaptiveMediaSource(amsResult.MediaSource));
                }
            }

            throw new NotSupportedException("");
        }
示例#20
0
        private async Task ChangeChannel(string url, string title)
        {
            var result = await AdaptiveMediaSource.CreateFromUriAsync(new Uri(url, UriKind.Absolute));

            if (result.Status == AdaptiveMediaSourceCreationStatus.Success)
            {
                var astream = result.MediaSource;
                Player.SetMediaStreamSource(astream);
            }
            else
            {
                Player.Source = new Uri(url, UriKind.Absolute);
            }

            Title.Text = title;

            IconSb.Begin();
        }
示例#21
0
        private async void BtnPlay_Tapped(object sender, TappedRoutedEventArgs e)
        {
            _licenseOverride = txtLicenseOverride.Text;

            if (!String.IsNullOrWhiteSpace(txtStreamUrl.Text))
            {
                var adaptiveMediaSourceResult = await AdaptiveMediaSource.CreateFromUriAsync(new Uri(txtStreamUrl.Text.Trim()));

                if (adaptiveMediaSourceResult.Status == AdaptiveMediaSourceCreationStatus.Success)
                {
                    mediaPlayerElement.Source = MediaSource.CreateFromAdaptiveMediaSource(adaptiveMediaSourceResult.MediaSource);
                }
                else
                {
                    Debug.WriteLine("Error opening the stream");
                }
            }
        }
        private async Task <AdaptiveMediaSource> BuildHlsMediaSource()
        {
            var client = new HttpClient();
            // Might want custom headers
            //client.DefaultRequestHeaders.Add("Referer", "xyz");
            var result = await AdaptiveMediaSource.CreateFromUriAsync(_dashStreamUrl, client);

            if (result.Status == AdaptiveMediaSourceCreationStatus.Success)
            {
                Debug.WriteLine($"Success: got manifest");
                return(result.MediaSource);
            }
            else
            {
                Debug.WriteLine($"Error: {result.Status}");
                return(null);
            }
        }
        private async Task LoadSourceFromUriAsync(Uri uri, HttpClient httpClient = null)
        {
            mediaPlayerElement.MediaPlayer?.DisposeSource();

            AdaptiveMediaSourceCreationResult result = null;

            if (httpClient != null)
            {
                result = await AdaptiveMediaSource.CreateFromUriAsync(uri, httpClient);
            }
            else
            {
                result = await AdaptiveMediaSource.CreateFromUriAsync(uri);
            }
            if (result.Status == AdaptiveMediaSourceCreationStatus.Success)
            {
                var adaptiveMS = result.MediaSource;

                // Register for events before resolving the MediaSource.
                RegisterForAdaptiveMediaSourceEvents(adaptiveMS);

                MediaSource source = MediaSource.CreateFromAdaptiveMediaSource(adaptiveMS);

                // You can save additional information in the CustomPropertySet for future retrieval.
                // Note: MediaSource.CustomProperties is a ValueSet and therefore can store
                // only serializable types.

                // Save the original Uri.
                source.CustomProperties.Add("uri", uri.ToString());

                // You're likely to put a content tracking id into the CustomProperties.
                source.CustomProperties.Add("contentId", Guid.NewGuid());

                RegisterForMediaSourceEvents(source);

                // Register for events before resolving the MediaSource.
                mpItem = new MediaPlaybackItem(source);
                RegisterForMediaPlaybackItemEvents(mpItem);
            }
            else
            {
                Log($"Error creating the AdaptiveMediaSource: {result.Status}");
            }
        }
示例#24
0
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            string movieSource = e.Parameter as string;

            mediaPlayer.Source = new System.Uri(movieSource);
            AdaptiveMediaSourceCreationResult result = await AdaptiveMediaSource.CreateFromUriAsync(new System.Uri(movieSource, UriKind.Absolute));

            if (result.Status == AdaptiveMediaSourceCreationStatus.Success)
            {
                var astream     = result.MediaSource;
                var ttmSource   = TimedTextSource.CreateFromUri(new Uri(movieSource));
                var mediaSource = MediaSource.CreateFromAdaptiveMediaSource(astream);
                mediaSource.ExternalTimedTextSources.Add(ttmSource);
                var mediaElement = new MediaPlaybackItem(mediaSource);
                mediaPlayer.SetPlaybackSource(mediaElement);
                movieLoadingRing.IsActive = false;
            }
        }
示例#25
0
        private async void DownloadRequested(AdaptiveMediaSource sender, AdaptiveMediaSourceDownloadRequestedEventArgs args)
        {
            // rewrite key URIs to replace http:// with https://
            if (args.ResourceType == AdaptiveMediaSourceResourceType.Key)
            {
                string originalUri = args.ResourceUri.ToString();
                string secureUri   = originalUri.Replace("http:", "https:");

                // override the URI by setting property on the result sub object
                args.Result.ResourceUri = new Uri(secureUri);
            }

            if (args.ResourceType == AdaptiveMediaSourceResourceType.Manifest)
            {
                AdaptiveMediaSourceDownloadRequestedDeferral deferral = args.GetDeferral();
                // args.Result.Buffer = await CreateMyCustomManifest(args.ResourceUri);
                deferral.Complete();
            }
        }
示例#26
0
        private async Task ClearLeoPlayer()
        {
            await HohoemaApp.UIDispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =>
            {
                if (MediaPlayer.Source == _MediaSource)
                {
                    MediaPlayer.Source = null;

                    CloseLive?.Invoke(this);
                }

                _Mss?.Dispose();
                _Mss = null;
                _MediaSource?.Dispose();
                _MediaSource = null;
                _AdaptiveMediaSource?.Dispose();
                _AdaptiveMediaSource = null;
            });
        }
示例#27
0
        private async void BindMediaSource(MediaBinder sender, MediaBindingEventArgs args)
        {
            var deferal = args.GetDeferral();

            // Get the track data
            var track = JsonConvert.DeserializeObject <BaseTrack>(args.MediaBinder.Token);

            // Only run if the track exists
            if (track != null)
            {
                // Get the audio stream url for this track
                var audioStreamUri = await track.GetAudioStreamAsync(_youTubeClient);

                // If we are live and youtube, we get an adaptive stream url
                if (track.ServiceType == ServiceType.YouTube && track.IsLive)
                {
                    var source = await AdaptiveMediaSource.CreateFromUriAsync(audioStreamUri);

                    if (source.Status == AdaptiveMediaSourceCreationStatus.Success)
                    {
                        args.SetAdaptiveMediaSource(source.MediaSource);
                    }
                }
                else if (track.ServiceType == ServiceType.Local)
                {
                    var file = track.CustomProperties["File"] as StorageFile;

                    args.SetStorageFile(file);
                }
                else if (track.ServiceType == ServiceType.ITunesPodcast)
                {
                    args.SetUri(new Uri(track.AudioStreamUrl));
                }
                else
                {
                    // Set generic stream url.
                    args.SetUri(audioStreamUri);
                }
            }

            deferal.Complete();
        }
示例#28
0
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            ctsForInboundBitsPerSecondUiRefresh.Cancel(); // Cancel timer
            adaptiveMediaSource = null;                   // release app instance of AdaptiveMediaSource

            // Release handles on various media objects to ensure a quick clean-up
            ContentSelectorControl.MediaPlaybackItem = null;
            var mediaPlayer = mediaPlayerElement.MediaPlayer;

            if (mediaPlayer != null)
            {
                mediaPlayerLogger?.Dispose();
                mediaPlayerLogger = null;

                UnregisterHandlers(mediaPlayer);

                mediaPlayerElement.SetMediaPlayer(null);
                mediaPlayer.Dispose();
            }
        }
示例#29
0
        // </SnippetCreateFileOutputNode>



        // <SnippetCreateMediaSourceInputNode>
        private async Task CreateMediaSourceInputNode(System.Uri contentUri)
        {
            if (audioGraph == null)
            {
                return;
            }

            var adaptiveMediaSourceResult = await AdaptiveMediaSource.CreateFromUriAsync(contentUri);

            if (adaptiveMediaSourceResult.Status != AdaptiveMediaSourceCreationStatus.Success)
            {
                Debug.WriteLine("Failed to create AdaptiveMediaSource");
                return;
            }

            var mediaSource = MediaSource.CreateFromAdaptiveMediaSource(adaptiveMediaSourceResult.MediaSource);
            CreateMediaSourceAudioInputNodeResult mediaSourceAudioInputNodeResult =
                await audioGraph.CreateMediaSourceAudioInputNodeAsync(mediaSource);

            if (mediaSourceAudioInputNodeResult.Status != MediaSourceAudioInputNodeCreationStatus.Success)
            {
                switch (mediaSourceAudioInputNodeResult.Status)
                {
                case MediaSourceAudioInputNodeCreationStatus.FormatNotSupported:
                    Debug.WriteLine("The MediaSource uses an unsupported format");
                    break;

                case MediaSourceAudioInputNodeCreationStatus.NetworkError:
                    Debug.WriteLine("The MediaSource requires a network connection and a network-related error occurred");
                    break;

                case MediaSourceAudioInputNodeCreationStatus.UnknownFailure:
                default:
                    Debug.WriteLine("An unknown error occurred while opening the MediaSource");
                    break;
                }
                return;
            }

            mediaSourceInputNode = mediaSourceAudioInputNodeResult.Node;
        }
示例#30
0
        private async Task LoadSourceFromUriAsync(Uri uri, HttpClient httpClient = null)
        {
            mediaPlayerElement.MediaPlayer?.DisposeSource();

            AdaptiveMediaSourceCreationResult result = null;

            if (httpClient != null)
            {
                result = await AdaptiveMediaSource.CreateFromUriAsync(uri, httpClient);
            }
            else
            {
                result = await AdaptiveMediaSource.CreateFromUriAsync(uri);
            }

            if (result.Status == AdaptiveMediaSourceCreationStatus.Success)
            {
                adaptiveMS = result.MediaSource;

                // Register for events before setting the IMediaPlaybackSource
                RegisterForAdaptiveMediaSourceEvents(adaptiveMS);

                // Now that we have bitrates, attempt to cap them based on HdcpProtection.
                HdcpProtection?protection = hdcpSession.GetEffectiveProtection();
                SetMaxBitrateForProtectionLevel(protection, adaptiveMS);

                MediaSource source = MediaSource.CreateFromAdaptiveMediaSource(adaptiveMS);

                // Note that in this sample with very few event handlers, we are creating neither
                // a MediaPlayer nor a MediaPlaybackItem. The MediaPlayer will be created implicitly
                // by the mpElement, which will also manage its lifetime.

                mediaPlayerElement.Source = source;
                // You can now access mpElement.MediaPlayer, but it is too late to register
                // to handle its MediaOpened event.
            }
            else
            {
                Log($"Error creating the AdaptiveMediaSource: {result.Status}");
            }
        }
示例#31
0
        private async Task ClearLeoPlayer()
        {
            _UIScheduler.Schedule(() =>
            {
                if (MediaPlayer.Source == _MediaSource)
                {
                    MediaPlayer.Source = null;

                    CloseLive?.Invoke(this);
                }

                _Mss?.Dispose();
                _Mss = null;
                _MediaSource?.Dispose();
                _MediaSource = null;
                _AdaptiveMediaSource?.Dispose();
                _AdaptiveMediaSource = null;
            });

            await Task.CompletedTask;
        }
示例#32
0
        public async Task Media()
        {
            AdaptiveCard card = new AdaptiveCard
            {
                Version = "1.3"
            };

            AdaptiveMediaSource mediaSource = new AdaptiveMediaSource
            {
                MimeType = "audio/mp4",
                Url      = "https://www.stuff.com/media.mp4"
            };

            AdaptiveMedia media = new AdaptiveMedia();

            media.Sources.Add(mediaSource);

            card.Body.Add(media);

            await RenderInDispatcher(card);
        }
        async private void InitializeAdaptiveMediaSource(System.Uri uri, MediaElement m)
        {
            httpClient = new Windows.Web.Http.HttpClient();
            httpClient.DefaultRequestHeaders.TryAppendWithoutValidation("X-CustomHeader", "This is a custom header");

            AdaptiveMediaSourceCreationResult result = await AdaptiveMediaSource.CreateFromUriAsync(uri, httpClient);
            if (result.Status == AdaptiveMediaSourceCreationStatus.Success)
            {
                ams = result.MediaSource;
                m.SetMediaStreamSource(ams);

                //Register for download requested event
                ams.DownloadRequested += DownloadRequested;

                //Register for download success and failure events
                ams.DownloadCompleted += DownloadCompleted;
                ams.DownloadFailed += DownloadFailed;
            }
            else
            {
                rootPage.NotifyUser("Error creating the AdaptiveMediaSource\n\t" + result.Status, NotifyType.ErrorMessage);
            }
        }
        async private void InitializeAdaptiveMediaSource(System.Uri uri, MediaElement m)
        {
            AdaptiveMediaSourceCreationResult result = await AdaptiveMediaSource.CreateFromUriAsync(uri);
            if(result.Status == AdaptiveMediaSourceCreationStatus.Success)
            {
                ams = result.MediaSource;
                m.SetMediaStreamSource(ams);

                outputBitrates(); //query for available bitrates and output to the log
                txtDownloadBitrate.Text = ams.InitialBitrate.ToString();
                txtPlaybackBitrate.Text = ams.InitialBitrate.ToString();

                //Register for download requests
                ams.DownloadRequested += DownloadRequested;

                //Register for bitrate change events
                ams.DownloadBitrateChanged += DownloadBitrateChanged;
                ams.PlaybackBitrateChanged += PlaybackBitrateChanged;
            }
            else
            {
                rootPage.NotifyUser("Error creating the AdaptiveMediaSource\n\t" + result.Status, NotifyType.ErrorMessage);
            }
        }
 private void _source_DownloadRequested(AdaptiveMediaSource sender, AdaptiveMediaSourceDownloadRequestedEventArgs args)
 {
 }
        private void _source_DownloadBitrateChanged(AdaptiveMediaSource sender, AdaptiveMediaSourceDownloadBitrateChangedEventArgs args)
        {

        }
        /// <summary>
        /// Enforces a fictitious content publisher's rules for bandwidth maximums based on HDCP protection levels.
        /// </summary>
        /// <param name="protection">Protection level to use when imposing bandwidth restriction.</param>
        /// <param name="ams">AdaptiveMediaSource on which to impose restrictions</param>
        private void SetMaxBitrateForProtectionLevel(HdcpProtection? protection, AdaptiveMediaSource ams)
        {
            EffectiveHdcpProtectionText.Text = protection.ToString();

            if (ams != null && ams.AvailableBitrates.Count > 1)
            {
                // Get a sorted list of available bitrates.
                var bitrates = new List<uint>(ams.AvailableBitrates);
                bitrates.Sort();

                // Apply maximum bitrate policy based on a fictitious content publisher's rules.
                switch (protection)
                {
                    case HdcpProtection.OnWithTypeEnforcement:
                        // Allow full bitrate.
                        ams.DesiredMaxBitrate = bitrates[bitrates.Count - 1];
                        DesiredMaxBitrateText.Text = "full bitrate allowed";
                        break;
                    case HdcpProtection.On:
                        // When there is no HDCP Type 1, make the highest bitrate unavailable.
                        ams.DesiredMaxBitrate = bitrates[bitrates.Count - 2];
                        DesiredMaxBitrateText.Text = "highest bitrate is unavailable";
                        break;
                    case HdcpProtection.Off:
                    case null:
                    default:
                        // When there is no HDCP at all (Off), or the system is still trying to determine what
                        // HDCP protection level to apply (null), then make only the lowest bitrate available.
                        ams.DesiredMaxBitrate = bitrates[0];
                        DesiredMaxBitrateText.Text = "lowest bitrate only";
                        break;
                }
                Log($"Imposed DesiredMaxBitrate={ams.DesiredMaxBitrate} for HdcpProtection.{protection}");
            }
        }
 private async void PlaybackBitrateChanged(AdaptiveMediaSource sender, AdaptiveMediaSourcePlaybackBitrateChangedEventArgs args)
 {
     uint playbackBitrate = args.NewValue;
     await UpdatePlaybackBitrate(playbackBitrate);
 }
 private void DownloadCompleted(AdaptiveMediaSource sender, AdaptiveMediaSourceDownloadCompletedEventArgs args)
 {
     if (verbose)
     {
         Log($"DownloadCompleted: {args.ResourceType}, {args.ResourceUri}");
     }
     // You can get a copy of the http response bytes for additional processing.
     // Note that the AdaptiveMediaSource has already consumed these bytes. Modifying them has no effect.
     // If you need to modify the request or send specific bytes to AdaptiveMediaSource, do so in
     // DownloadRequested.  See the RequestModification scenario for more details.
     // var buffer = await args.HttpResponseMessage.Content.ReadAsBufferAsync();
 }
 private void DownloadFailed(AdaptiveMediaSource sender, AdaptiveMediaSourceDownloadFailedEventArgs args)
 {
     log("Download Failured. Resource Type: " + args.ResourceType + " Resource URI: " + args.ResourceUri + "\nHTTP Response:\n" + args.HttpResponseMessage);
 }
 private void DownloadBitrateChanged(AdaptiveMediaSource sender, AdaptiveMediaSourceDownloadBitrateChangedEventArgs args)
 {
     UpdateBitrateUI(txtDownloadBitrate, args.NewValue);
 }
 private void UnregisterForAdaptiveMediaSourceEvents(AdaptiveMediaSource adaptiveMediaSource)
 {
     adaptiveMediaSource.DownloadRequested -= DownloadRequested;
     adaptiveMediaSource.DownloadFailed -= DownloadFailed;
     adaptiveMediaSource.DownloadCompleted -= DownloadCompleted;
     adaptiveMediaSource.DownloadBitrateChanged -= DownloadBitrateChanged;
     adaptiveMediaSource.PlaybackBitrateChanged -= PlaybackBitrateChanged;
 }
        private async void OnPlayClick(object sender, RoutedEventArgs e)
        {
            String url = txtURL.Text;
            String tag = "ra000001";
            Uri hsl = await GetHitChannelHSL(url, tag);
            if (hsl != null)
            {
                // check is phone
                bool isHardwareButtonsAPIPresent =
        Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons");

                if (isHardwareButtonsAPIPresent)
                {
                    //Windows.Phone.UI.Input.HardwareButtons.CameraPressed +=
                    //    HardwareButtons_CameraPressed;
                    ValueSet msg = new ValueSet();
                    msg.Add("Play", hsl.OriginalString);
                    BackgroundMediaPlayer.SendMessageToBackground(msg);
                }

                AdaptiveMediaSourceCreationResult result = await AdaptiveMediaSource.CreateFromUriAsync(hsl);
                if (result.Status == AdaptiveMediaSourceCreationStatus.Success)
                {
                    _source = result.MediaSource;
                    _source.DownloadRequested += _source_DownloadRequested;
                    _source.DownloadCompleted += _source_DownloadCompleted;
                    _source.DownloadFailed += _source_DownloadFailed;
                    _source.DownloadBitrateChanged += _source_DownloadBitrateChanged;
                    _source.PlaybackBitrateChanged += _source_PlaybackBitrateChanged;

                    mediaPlayer.SetMediaStreamSource(result.MediaSource);
                }
            }
        }
 public AdaptiveMediaSourceEvents(AdaptiveMediaSource This)
 {
     this.This = This;
 }
 private void DownloadCompleted(AdaptiveMediaSource sender, AdaptiveMediaSourceDownloadCompletedEventArgs args)
     {
         log("Download Completed. Resource Type: " + args.ResourceType + " Resource URI: " + args.ResourceUri);
     }
        private async Task PlayHLS(Uri hsl)
        {
            AdaptiveMediaSourceCreationResult result = await AdaptiveMediaSource.CreateFromUriAsync(hsl);
            if (result.Status == AdaptiveMediaSourceCreationStatus.Success)
            {
                _source = result.MediaSource;
                _source.DownloadRequested += _source_DownloadRequested;
                _source.DownloadCompleted += _source_DownloadCompleted;
                _source.DownloadFailed += _source_DownloadFailed;
                _source.DownloadBitrateChanged += _source_DownloadBitrateChanged;
                _source.PlaybackBitrateChanged += _source_PlaybackBitrateChanged;

                BackgroundMediaPlayer.Current.SetMediaSource(result.MediaSource);
            }
        }
        private async Task LoadSourceFromUriAsync(Uri uri, HttpClient httpClient = null)
        {
            if (mediaPlayerElement.MediaPlayer?.Source != null)
            {
                UnregisterHandlers(mediaPlayerElement.MediaPlayer);
                mediaPlayerElement.MediaPlayer.DisposeSource();
            }

            AdaptiveMediaSourceCreationResult result = null;
            if (httpClient != null)
            {
                result = await AdaptiveMediaSource.CreateFromUriAsync(uri, httpClient);
            }
            else
            {
                result = await AdaptiveMediaSource.CreateFromUriAsync(uri);
            }

            // We don't need to save a reference to the MediaSource,
            // because we can obtain it from the MediaPlaybackItem.Source in event handlers.
            MediaSource source;

            if (result.Status == AdaptiveMediaSourceCreationStatus.Success)
            {
                adaptiveMediaSource = result.MediaSource;

                // At this point, we have read the manifest of the media source, and all bitrates are known.
                bitrateHelper = new BitrateHelper(adaptiveMediaSource.AvailableBitrates);

                // The AdaptiveMediaSource chooses initial playback and download bitrates.
                // See the Tuning scenario for examples of customizing these bitrates.
                await UpdatePlaybackBitrate(adaptiveMediaSource.CurrentPlaybackBitrate);
                await UpdateDownloadBitrateAsync(adaptiveMediaSource.CurrentDownloadBitrate);

                // Register for events before resolving the MediaSource.
                RegisterForAdaptiveMediaSourceEvents(adaptiveMediaSource);

                source = MediaSource.CreateFromAdaptiveMediaSource(adaptiveMediaSource);
            }
            else
            {
                Log($"Error creating the AdaptiveMediaSource: {result.Status}");

                // Try to load the URI as a progressive download URI.
                Log($"Attempting to create a MediaSource from uri: {uri}");
                source = MediaSource.CreateFromUri(uri);
            }

            // You can save additional information in the CustomPropertySet for future retrieval.
            // Note: MediaSource.CustomProperties is a ValueSet and therefore can store
            // only serializable types.

            // Save the original Uri.
            source.CustomProperties.Add("uri", uri.ToString());

            // You're likely to put a content tracking id into the CustomProperties.
            source.CustomProperties.Add("contentId", Guid.NewGuid());

            RegisterForMediaSourceEvents(source);

            // Register for events before resolving the MediaSource.
            var mpItem = new MediaPlaybackItem(source);
            RegisterForMediaPlaybackItemEvents(mpItem);

            // It is at this point that the MediaSource (within a MediaPlaybackItem) will be fully resolved.
            // It gets opened, and events start being raised.

            // Since we are in an async function, the user may have user navigated away, which will null the MediaPlayer.
            if (mediaPlayerElement.MediaPlayer != null)
            {
                mediaPlayerElement.MediaPlayer.Source = mpItem;
            }
        }
        private void _source_PlaybackBitrateChanged(AdaptiveMediaSource sender, AdaptiveMediaSourcePlaybackBitrateChangedEventArgs args)
        {

        }
 private async void DownloadRequested(AdaptiveMediaSource sender, AdaptiveMediaSourceDownloadRequestedEventArgs args)
 {
     if (args.ResourceType == AdaptiveMediaSourceResourceType.Key)
     {
         switch (tokenMethod)
         {
             case AzureKeyAcquisitionMethod.None:
                 break;
             case AzureKeyAcquisitionMethod.AuthorizationHeader:
                 // By updating the IHttpFilter KeyHost property here, we ensure it's up to date
                 // before the network request is made.  It is the IHttpFilter that will insert
                 // the Authorization header.
                 if (httpClientFilter != null)
                 {
                     httpClientFilter.KeyHost = args.ResourceUri.Host;
                 }
                 break;
             case AzureKeyAcquisitionMethod.UrlQueryParameter:
                 ModifyKeyRequestUri(args);
                 break;
             case AzureKeyAcquisitionMethod.ApplicationDownloaded:
                 await AppDownloadedKeyRequest(args);
                 break;
             default:
                 break;
         }
     }
 }
        private async Task LoadSourceFromUriAsync(Uri uri, HttpClient httpClient = null)
        {
            mediaPlayerElement.MediaPlayer?.DisposeSource();

            AdaptiveMediaSourceCreationResult result = null;
            if (httpClient != null)
            {
                result = await AdaptiveMediaSource.CreateFromUriAsync(uri, httpClient);
            }
            else
            {
                result = await AdaptiveMediaSource.CreateFromUriAsync(uri);
            }

            if (result.Status == AdaptiveMediaSourceCreationStatus.Success)
            {
                adaptiveMS = result.MediaSource;

                // Register for events before setting the IMediaPlaybackSource
                RegisterForAdaptiveMediaSourceEvents(adaptiveMS);

                // Now that we have bitrates, attempt to cap them based on HdcpProtection.
                HdcpProtection? protection = hdcpSession.GetEffectiveProtection();
                SetMaxBitrateForProtectionLevel(protection, adaptiveMS);

                MediaSource source = MediaSource.CreateFromAdaptiveMediaSource(adaptiveMS);

                // Note that in this sample with very few event handlers, we are creating neither
                // a MediaPlayer nor a MediaPlaybackItem. The MediaPlayer will be created implicitly
                // by the mpElement, which will also manage its lifetime.

                mediaPlayerElement.Source = source;
                // You can now access mpElement.MediaPlayer, but it is too late to register
                // to handle its MediaOpened event.
            }
            else
            {
                Log($"Error creating the AdaptiveMediaSource: {result.Status}");
            }
        }
 private void DownloadRequested(AdaptiveMediaSource sender, AdaptiveMediaSourceDownloadRequestedEventArgs args)
 {
     if (verbose)
     {
         Log($"DownloadRequested: {args.ResourceType}, {args.ResourceUri}");
     }
 }
        private void InitializeBitrateLists(AdaptiveMediaSource aMS)
        {
            var sortedBitrates = aMS.AvailableBitrates.OrderByDescending(br => br).Select(br => new BitrateItem(br)).ToArray();
            InitialBitrateList.ItemsSource = sortedBitrates;
            var selected = sortedBitrates.First(item => item.Bitrate == aMS.InitialBitrate);
            InitialBitrateList.SelectedItem = sortedBitrates.FirstOrDefault(item => item.Bitrate == aMS.InitialBitrate);

            var nullableSortedBitrates = (new BitrateItem[] { new BitrateItem(null) }).Concat(sortedBitrates).ToArray();
            DesiredMaxBitrateList.ItemsSource = DesiredMinBitrateList.ItemsSource = nullableSortedBitrates;

            DesiredMaxBitrateList.SelectedItem = nullableSortedBitrates.First(item => item.Bitrate == aMS.DesiredMaxBitrate);
            DesiredMinBitrateList.SelectedItem = nullableSortedBitrates.First(item => item.Bitrate == aMS.DesiredMinBitrate);
        }
 private void RegisterForAdaptiveMediaSourceEvents(AdaptiveMediaSource aMS)
 {
     aMS.DownloadFailed += DownloadFailed;
     aMS.DownloadBitrateChanged += DownloadBitrateChanged;
     aMS.PlaybackBitrateChanged += PlaybackBitrateChanged;
 }
 private void DownloadRequested(AdaptiveMediaSource sender, AdaptiveMediaSourceDownloadRequestedEventArgs args)
 {
     UpdateBitrateUI(txtMeasuredBandwidth, (uint)ams.InboundBitsPerSecond);
 }
 private void DownloadFailed(AdaptiveMediaSource sender, AdaptiveMediaSourceDownloadFailedEventArgs args)
 {
     Log($"DownloadFailed: {args.HttpResponseMessage}, {args.ResourceType}, {args.ResourceUri}");
 }
 private void PlaybackBitrateChanged(AdaptiveMediaSource sender, AdaptiveMediaSourcePlaybackBitrateChangedEventArgs args)
 {
     UpdateBitrateUI(txtPlaybackBitrate, args.NewValue);
 }
 private async void DownloadBitrateChanged(AdaptiveMediaSource sender, AdaptiveMediaSourceDownloadBitrateChangedEventArgs args)
 {
     uint downloadBitrate = args.NewValue;
     await UpdateDownloadBitrate(downloadBitrate);
 }
        private async Task LoadSourceFromUriAsync(Uri uri, HttpClient httpClient = null)
        {
            mediaPlayerElement.MediaPlayer?.DisposeSource();

            AdaptiveMediaSourceCreationResult result = null;
            if (httpClient != null)
            {
                result = await AdaptiveMediaSource.CreateFromUriAsync(uri, httpClient);
            }
            else
            {
                result = await AdaptiveMediaSource.CreateFromUriAsync(uri);
            }
            if (result.Status == AdaptiveMediaSourceCreationStatus.Success)
            {
                adaptiveMS = result.MediaSource;

                bitrateHelper = new BitrateHelper(adaptiveMS.AvailableBitrates);
                InitializeBitrateLists(adaptiveMS);

                // At this point, we have read the manifest of the media source, and all bitrates are known.
                await UpdatePlaybackBitrate(adaptiveMS.CurrentPlaybackBitrate);
                await UpdateDownloadBitrate(adaptiveMS.CurrentDownloadBitrate);

                // Register for events before resolving the MediaSource.
                RegisterForAdaptiveMediaSourceEvents(adaptiveMS);

                MediaSource source = MediaSource.CreateFromAdaptiveMediaSource(adaptiveMS);

                // You can save additional information in the CustomPropertySet for future retrieval.
                // Note: MediaSource.CustomProperties is a ValueSet and therefore can store
                // only serializable types.

                // Save the original Uri.
                source.CustomProperties.Add("uri", uri.ToString());

                // You're likely to put a content tracking id into the CustomProperties.
                source.CustomProperties.Add("contentId", Guid.NewGuid());

                mpItem = new MediaPlaybackItem(source);
            }
            else
            {
                Log("Error creating the AdaptiveMediaSource: " + result.Status);
            }
        }
 private void RegisterForAdaptiveMediaSourceEvents(AdaptiveMediaSource aMS)
 {
     aMS.DownloadRequested += DownloadRequested;
     aMS.DownloadFailed += DownloadFailed;
 }