void CastVideo(object sender, EventArgs e)
        {
            // Show Alert if not connected
            if (DeviceManager == null || !DeviceManager.IsConnected)
            {
                new UIAlertView("Not Connected", "Please connect to a cast device", null, "Ok", null).Show();
                return;
            }

            // Define Media metadata
            var metadata = new MediaMetadata();

            metadata.SetString("Big Buck Bunny (2008)", MetadataKey.Title);
            metadata.SetString("Big Buck Bunny tells the story of a giant rabbit with a heart bigger than " +
                               "himself. When one sunny day three rodents rudely harass him, something " +
                               "snaps... and the rabbit ain't no bunny anymore! In the typical cartoon " +
                               "tradition he prepares the nasty rodents a comical revenge.",
                               MetadataKey.Subtitle);
            metadata.AddImage(new Image(new NSUrl("http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/images/BigBuckBunny.jpg"), 480, 360));

            // define Media information
            var mediaInformation = new MediaInformation("http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4",
                                                        MediaStreamType.None, "video/mp4", metadata, 0, null);

            // cast video
            MediaControlChannel.LoadMedia(mediaInformation, true, 0);
        }
Ejemplo n.º 2
0
        public static async Task play(string url, string title, string subtitle, string image)
        {
            mediaChannel = sender.GetChannel <IMediaChannel>();
            await sender.LaunchAsync(mediaChannel);

            var mediaInfo = new MediaInformation()
            {
                ContentId = url
            };

            mediaInfo.Metadata = new GenericMediaMetadata();
            if (title != null)
            {
                mediaInfo.Metadata.Title = title;
            }
            if (subtitle != null)
            {
                mediaInfo.Metadata.Subtitle = subtitle;
            }
            if (image != null)
            {
                mediaInfo.Metadata.Images    = new GoogleCast.Models.Image[1];
                mediaInfo.Metadata.Images[0] = new GoogleCast.Models.Image()
                {
                    Url = image
                };
            }
            mediastatus = await mediaChannel.LoadAsync(mediaInfo);
        }
        // Builds all the information to be sent to Cast device.
        MediaInformation BuildMediaInformation(int categoryIndexSelected, int videoIndexSelected)
        {
            var category = categories [categoryIndexSelected];
            var video    = category.Videos [videoIndexSelected];

            var metadata = new MediaMetadata(MediaMetadataType.Movie);

            metadata.SetString(video.Title, MetadataKey.Title);
            metadata.SetString(video.Subtitle, MetadataKey.Subtitle);
            metadata.SetString(video.Studio, MetadataKey.Studio);

            var imageUrl = new NSUrl($"{category.ImagesBaseUrl}{video.ImageUrl}");

            metadata.AddImage(new Image(imageUrl, 480, 720));

            var posterUrl = new NSUrl($"{category.ImagesBaseUrl}{video.PosterUrl}");

            metadata.AddImage(new Image(posterUrl, 780, 1200));

            string videoUrl = string.Empty;

            var tracks = new List <MediaTrack> ();

            video.Tracks = video.Tracks ?? new List <Track> ();

            foreach (var track in video.Tracks)
            {
                tracks.Add(new MediaTrack(
                               int.Parse(track.Id),
                               $"{category.TracksBaseUrl}{track.ContentId}",
                               track.Type,
                               MediaTrackType.Text,
                               MediaTextTrackSubtype.Captions,
                               track.Name,
                               track.Language,
                               null));
            }

            foreach (var source in video.Sources)
            {
                if (!source.Type.Equals("mp4"))
                {
                    continue;
                }

                videoUrl = $"{category.Mp4BaseUrl}{source.Url}";
            }

            var mediaInformation = new MediaInformation(videoUrl,
                                                        MediaStreamType.Buffered,
                                                        "video/mp4", metadata,
                                                        video.Duration,
                                                        tracks.ToArray(),
                                                        null,
                                                        null);

            return(mediaInformation);
        }
Ejemplo n.º 4
0
 /// <summary>
 /// Loads a media
 /// </summary>
 /// <param name="media">media to load</param>
 /// <param name="autoPlay">true to play the media directly, false otherwise</param>
 /// <param name="activeTrackIds">track identifiers that should be active</param>
 /// <returns>media status</returns>
 public async Task <MediaStatus> LoadAsync(MediaInformation media, bool autoPlay = true, params int[] activeTrackIds)
 {
     return(await SendAsync(new LoadMessage()
     {
         Media = media,
         AutoPlay = autoPlay,
         ActiveTrackIds = activeTrackIds
     }));
 }
        public MediaQueueItem(MediaInformation mediaInformation, bool autoplay, double startTime, double playbackDuration, double preloadTime, nuint [] activeTrackIDs, NSObject customData)
        {
            if (mediaInformation == null)
            {
                throw new ArgumentNullException(nameof(mediaInformation));
            }

            var activeTracksIdsObjC = NSArray.FromObjects(activeTrackIDs);

            Handle = _InitWithMediaInformation(mediaInformation, autoplay, startTime, playbackDuration, preloadTime, activeTracksIdsObjC, customData);
        }
        public nint LoadMedia(MediaInformation mediaInfo, bool autoplay, double playPosition, nuint [] activeTrackIDs, NSObject customData)
        {
            NSArray activeTrackIDsArray = null;

            if (activeTrackIDs != null)
            {
                activeTrackIDsArray = NSArray.FromObjects(activeTrackIDs.Length, activeTrackIDs);
            }

            return(_LoadMedia(mediaInfo, autoplay, playPosition, activeTrackIDsArray, customData));
        }
Ejemplo n.º 7
0
        public MediaQueueItem(MediaInformation mediaInformation, bool autoplay, double startTime, double playbackDuration, double preloadTime, nuint [] activeTrackIds, NSObject customData) : base(NSObjectFlag.Empty)
        {
            if (mediaInformation == null)
            {
                throw new ArgumentNullException(nameof(mediaInformation));
            }

            var activeTracksIdsObjC = NSArray.FromNSObjects((arg) => NSNumber.FromNUInt(arg), activeTrackIds);

            Handle = _InitWithMediaInformation(mediaInformation, autoplay, startTime, playbackDuration, preloadTime, activeTracksIdsObjC, customData);
        }
        // C# 7 YOLO, I <3 One liners
        //public nint LoadMedia (MediaInformation mediaInfo, bool autoplay, double playPosition, nuint [] activeTrackIDs)
        //=> _LoadMedia (mediaInfo, autoplay, playPosition, activeTrackIDs is null ? null : NSArray.FromNSObjects ((arg) => NSNumber.FromNUInt (arg), activeTrackIDs);

        public nint LoadMedia(MediaInformation mediaInfo, bool autoplay, double playPosition, nuint [] activeTrackIDs)
        {
            NSArray activeTrackIDsArray = null;

            if (activeTrackIDs != null)
            {
                activeTrackIDsArray = NSArray.FromNSObjects((arg) => NSNumber.FromNUInt(arg), activeTrackIDs);
            }

            return(_LoadMedia(mediaInfo, autoplay, playPosition, activeTrackIDsArray));
        }
Ejemplo n.º 9
0
        public async Task <bool> Play(string contentLink)
        {
            MediaInformation mediaInformation = new MediaInformation();

            mediaInformation.ContentId   = contentLink;
            mediaInformation.ContentType = "audio/x-wav";
            await mediaChannel.LoadAsync(mediaInformation);

            await mediaChannel.PlayAsync();

            return(true);
        }
        public Request LoadMedia(MediaInformation mediaInfo, bool autoplay, double playPosition, nuint [] activeTrackIDs)
        {
            if (mediaInfo == null)
            {
                throw new ArgumentNullException(nameof(mediaInfo));
            }

            NSArray activeTrackIDsArray = null;

            if (activeTrackIDs != null)
            {
                activeTrackIDsArray = NSArray.FromObjects(activeTrackIDs.Length, activeTrackIDs);
            }

            return(_LoadMedia(mediaInfo, autoplay, playPosition, activeTrackIDsArray));
        }
Ejemplo n.º 11
0
        public SampleReader(TrackMetadata track)
        {
            MediaInformation mi = track.info.mediaInformation;

            sampleCount         = mi.sampleTable.sampleSize.sampleCount;
            sampleSize          = mi.sampleTable.sampleSize;
            timeToSampleEntries = mi.sampleTable.timeToSample;
            sampleToChunk       = mi.sampleTable.sampleToChunk;
            chunkOffset         = mi.sampleTable.chunkOffset;
            timeScale           = track.info.timeScale;
            duration            = track.info.duration;
            sampleTable         = mi.sampleTable;
            timeDeltas          = mi.sampleTable.compositionToSample;
            editList            = track.editList;
            rewind();
        }
Ejemplo n.º 12
0
        public Request LoadMedia(MediaInformation mediaInfo, bool autoplay, double playPosition, nuint [] activeTrackIds, NSObject customData)
        {
            if (mediaInfo == null)
            {
                throw new ArgumentNullException(nameof(mediaInfo));
            }

            NSArray activeTrackIdsArray = null;

            if (activeTrackIds != null)
            {
                activeTrackIdsArray = NSArray.FromNSObjects((arg) => NSNumber.FromNUInt(arg), activeTrackIds);
            }

            return(_LoadMedia(mediaInfo, autoplay, playPosition, activeTrackIdsArray, customData));
        }
Ejemplo n.º 13
0
        public async Task <MediaStatus> LoadAsync(
            ISender sender,
            string sessionId,
            MediaInformation media,
            bool autoPlay = true,
            params int[] activeTrackIds)
        {
            var msg = new LoadMessage()
            {
                Media          = media,
                AutoPlay       = autoPlay,
                ActiveTrackIds = activeTrackIds.ToList(),
                SessionId      = sessionId
            };

            return(await SendAsync(sender, msg));
        }
Ejemplo n.º 14
0
        public async Task LoadSongs(List <SongInfo> songs)
        {
            try
            {
                MediaInformation[] info = new MediaInformation[songs.Count];

                for (int i = 0; i < info.Count(); i++)
                {
                    string[] res = null;
                    mbApiInterface.Library_GetFileTags(songs[i].FileURL, new[] { MetaDataType.Artist, MetaDataType.TrackTitle, MetaDataType.Album }, ref res);
                    info[i] = new MediaInformation
                    {
                        ContentId  = HttpUtility.UrlPathEncode(mediaContentURL + songs[i].Hashed + songs[i].SongFileExt),
                        StreamType = StreamType.Buffered,
                        Duration   = mbApiInterface.NowPlaying_GetDuration() / 1000,
                        Metadata   = new MusicTrackMediaMetadata
                        {
                            Artist    = res[0],
                            Title     = res[1],
                            AlbumName = res[2],
                            Images    = new[] {
                                new GoogleCast.Models.Image
                                {
                                    Url = mediaContentURL + songs[i].Hashed + ".jpg"
                                }
                            },
                        }
                    };
                    filenameStack.Push(songs[i].Hashed.ToString());
                }


                await mediaChannel.QueueLoadAsync(GoogleCast.Models.Media.RepeatMode.RepeatOff, info);
            }
            catch (OperationCanceledException)
            {
                Debug.WriteLine("Requested to close");
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }
        }
Ejemplo n.º 15
0
 private async Task PlayAsync()
 {
     await SendChannelCommandAsync <IMediaChannel>(!IsInitialized || IsStopped,
                                                   async c =>
     {
         var link = Link;
         if (!string.IsNullOrWhiteSpace(link) && await ConnectAsync())
         {
             var sender       = Sender;
             var mediaChannel = sender.GetChannel <IMediaChannel>();
             await sender.LaunchAsync(mediaChannel);
             var mediaInfo = new MediaInformation()
             {
                 ContentId = link
             };
             var subtitle = Subtitle;
             if (!string.IsNullOrWhiteSpace(subtitle))
             {
                 mediaInfo.Tracks = new Track[]
                 {
                     new Track()
                     {
                         TrackId = 1, Language = "en-US", Name = "English", TrackContentId = subtitle
                     }
                 };
                 mediaInfo.TextTrackStyle = new TextTrackStyle()
                 {
                     BackgroundColor = Color.Transparent,
                     EdgeColor       = Color.Black,
                     EdgeType        = TextTrackEdgeType.DropShadow
                 };
                 await mediaChannel.LoadAsync(mediaInfo, true, 1);
             }
             else
             {
                 await mediaChannel.LoadAsync(mediaInfo);
             }
             IsInitialized = true;
         }
     }, c => c.PlayAsync());
 }
Ejemplo n.º 16
0
        //CreateCastMedia
        public void CreateMediaInfo()
        {
            var videoUrl = mediaInfo.SourceURL;
            var vname    = mediaInfo.DisplayName;
            var extra    = new string[] { "{", "}" };


            var metaData = new MediaMetadata(MediaMetadataType.Generic);

            metaData.SetString(mediaInfo.DisplayName, MetadataKey.Title);
            metaData.SetString("Hello World on Fridays!", MetadataKey.Subtitle);


            var builder = new MediaInformationBuilder();

            builder.ContentId  = videoUrl;
            builder.StreamType = MediaStreamType.Buffered;
            builder.Metadata   = metaData;

            castMediaInfo = builder.Build();
        }
Ejemplo n.º 17
0
        public async Task <MediaStatus> LoadAsync(
            MediaInformation media,
            bool autoPlay        = true,
            double seekedSeconds = 0,
            params int[] activeTrackIds)
        {
            _logger.LogInfo($"{nameof(LoadAsync)}: Trying to load media = {media.ContentId}");
            CurrentContentId = null;
            CancelAndSetListenerToken();

            FileLoading?.Invoke(this, EventArgs.Empty);

            var app = await _receiverChannel.GetApplication(_sender, _connectionChannel, _mediaChannel.Namespace);

            var status = await _mediaChannel.LoadAsync(_sender, app.SessionId, media, autoPlay, activeTrackIds);

            if (status is null)
            {
                LoadFailed?.Invoke(this, EventArgs.Empty);
                _logger.LogWarn($"{nameof(LoadAsync)}: Couldn't load media {media.ContentId}");
                return(null);
            }

            CurrentContentId     = media.ContentId;
            CurrentMediaDuration = media.Duration ?? status?.Media?.Duration ?? 0;
            CurrentVolumeLevel   = status?.Volume?.Level ?? 0;
            IsMuted        = status?.Volume?.IsMuted ?? false;
            ElapsedSeconds = 0;
            _seekedSeconds = seekedSeconds;

            TriggerTimeEvents();
            IsPlaying = true;
            IsPaused  = false;
            ListenForMediaChanges(_listenerToken.Token);
            ListenForReceiverChanges(_listenerToken.Token);

            FileLoaded?.Invoke(this, EventArgs.Empty);
            _logger.LogInfo($"{nameof(LoadAsync)}: Media = {media.ContentId} was loaded. Duration = {CurrentMediaDuration} - SeekSeconds = {_seekedSeconds}");
            return(status);
        }
Ejemplo n.º 18
0
        public MediaExtractorBase(int type, string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new Exception("path can't be null");
            }

            _path            = path;
            MediaType        = type;
            MediaInformation = new MediaInformation();

            try
            {
                //DOC = 0, AUDIO = 2, IMAGE = 1, VIDEO = 3,
                switch (MediaType)
                {
                case 2:
                    Extract2();
                    break;

                case 1:
                    Extract();
                    break;

                case 3:
                    Extract();
                    break;

                case 0:
                    break;

                default:
                    break;
                }
            }
            catch (Exception ex)
            {
            }
        }
        // Reproduces the video on Cast device.
        void PlayVideoRemotely(MediaInformation mediaInformation)
        {
            var castSession = CastContext.SharedInstance.SessionManager.CurrentCastSession;

            // Make sure that we are connected to a Cast device.
            if (castSession == null)
            {
                ShowMessage("Connect to a device", "Tap the upper-right button to cast your media to your TV and Speakers.\n" +
                            "If the button doesn't appear, it means that there is no Cast device to connect.");
                return;
            }

            // Play video on Cast device.
            castSession.RemoteMediaClient.LoadMedia(mediaInformation, true);

            // Allow the app to manage every manageable aspect of a
            // cast session, with the exception of receiver volume control
            // and session lifecycle (connect/stop casting).
            // It also provides all the status information about the
            // media session (artwork, title, subtitle, and so forth).
            CastContext.SharedInstance.PresentDefaultExpandedMediaControls();
        }
Ejemplo n.º 20
0
        public MediaExtractorBase(int type, Stream stream)
        {
            if (stream == null)
            {
                throw new Exception("stream can't be null");
            }

            this.Stream      = stream;
            MediaType        = type;
            MediaInformation = new MediaInformation();

            try
            {
                switch (MediaType)
                {
                case 2:
                    Extract2();
                    break;

                case 1:
                    Extract();
                    break;

                case 3:
                    Extract();
                    break;

                case 0:
                    break;

                default:
                    break;
                }
            }
            catch (Exception ex)
            {
            }
        }
        public void CreateMediaInfo(BCOVVideo video)
        {
            BCOVSource source = null;

            // Don't restart the current video
            if (currentVideo != null)
            {
                didContinueCurrentVideo = currentVideo.IsEqual(video);
                if (didContinueCurrentVideo)
                {
                    return;
                }
            }

            suitableSourceNotFound = false;

            // Try to find an HTTPS source first
            source = FindDashSource(video.Sources, true);

            if (source == null)
            {
                source = FindDashSource(video.Sources, false);
            }

            // If no source was able to be found, let the delegate know
            // and do not continue
            if (source == null)
            {
                suitableSourceNotFound = true;
                gcmDelegate.SuitableSourceNotFound();
                return;
            }

            currentVideo = video;

            var videoUrl       = source.Url.AbsoluteString;
            var vname          = video.Properties["name"];
            var durationNumber = video.Properties["duration"];

            var metaData = new MediaMetadata(MediaMetadataType.Generic);

            metaData.SetString(vname.ToString(), "kGCKMetadataKeyTitle");

            var poster    = video.Properties["poster"].ToString();
            var posterUrl = new NSUrl(poster);

            metaData.AddImage(new Image(posterUrl, (nint)posterImageSize.Width, (nint)posterImageSize.Height));

            //TODO Implement this logic for closed caption cast
            //var mediaTracks = new List<MediaTrack>();
            //var textTracks = video.Properties["text_tracks"];
            //var trackIndentifier = 0;
            //foreach (var text in textTracks)
            //{
            //    trackIndentifier += 1;
            //    string src, lang, name, contentType, kind;
            //    if (text.Key.ToString() == "src")
            //        src = text.
            //    //string lang = text["srclang"] as string;
            //    //var name = text["label"] as string;
            //    //var contentType = text["mime_type"] as string;
            //}


            var builder = new MediaInformationBuilder();

            builder.ContentId      = videoUrl;
            builder.StreamType     = MediaStreamType.Unknown;
            builder.ContentType    = source?.DeliveryMethod;
            builder.Metadata       = metaData;
            builder.StreamDuration = (double)(durationNumber as NSNumber);
            //TODO uncomment this for closed caption cast
            //builder.MediaTracks = mediaTracks;

            castMediaInfo = builder.Build();
        }
        public MediaQueueItem(MediaInformation mediaInformation, bool autoplay, double startTime, double playbackDuration, double preloadTime, nuint [] activeTrackIDs, NSObject customData)
        {
            var activeTracksIdsObjC = NSArray.FromObjects(activeTrackIDs);

            Handle = _InitWithMediaInformation(mediaInformation, autoplay, startTime, playbackDuration, preloadTime, activeTracksIdsObjC, customData);
        }
Ejemplo n.º 23
0
        public async Task StartPlay(
            string mrl,
            int videoStreamIndex,
            int audioStreamIndex,
            int subtitleStreamIndex,
            int quality,
            FFProbeFileInfo fileInfo,
            double seconds = 0)
        {
            if (fileInfo == null)
            {
                _logger.LogWarning($"{nameof(StartPlay)}: No file info was provided for mrl = {mrl}");
                throw new ArgumentNullException(nameof(fileInfo), "A file info must be provided");
            }
            _ffmpegService.KillTranscodeProcess();
            bool isLocal     = _fileService.IsLocalFile(mrl);
            bool isUrlFile   = _fileService.IsUrlFile(mrl);
            bool isVideoFile = _fileService.IsVideoFile(mrl);
            bool isMusicFile = _fileService.IsMusicFile(mrl);

            if (!isLocal && !isUrlFile)
            {
                var msg = "Invalid = {mrl}. Its not a local file and its not a url file";
                _logger.LogWarning($"{nameof(StartPlay)}: {msg}");
                throw new NotSupportedException(msg);
            }

            if (AvailableDevices.Count == 0)
            {
                _logger.LogWarning($"{nameof(StartPlay)}: No renders were found, file = {mrl}");
                throw new NoDevicesException();
            }

            if (_connecting)
            {
                _logger.LogWarning($"{nameof(StartPlay)}: We are in the middle of connecting to a device, can't play file = {mrl} right now");
                throw new ConnectingException();
            }

            if (!_renderWasSet && AvailableDevices.Count > 0)
            {
                await SetCastRenderer(AvailableDevices.First()).ConfigureAwait(false);
            }
            // create new media
            bool videoNeedsTranscode = isVideoFile && _ffmpegService.VideoNeedsTranscode(videoStreamIndex, _appSettings.ForceVideoTranscode, _appSettings.VideoScale, fileInfo);
            bool audioNeedsTranscode = _ffmpegService.AudioNeedsTranscode(audioStreamIndex, _appSettings.ForceAudioTranscode, fileInfo, isMusicFile);
            var  hwAccelToUse        = isVideoFile ? _ffmpegService.GetHwAccelToUse(videoStreamIndex, fileInfo, _appSettings.EnableHardwareAcceleration) : HwAccelDeviceType.None;

            _currentFilePath = mrl;
            string title = isLocal ? Path.GetFileName(mrl) : mrl;
            string url   = isLocal
                ? _appWebServer.GetMediaUrl(
                mrl,
                videoStreamIndex,
                audioStreamIndex,
                seconds,
                videoNeedsTranscode,
                audioNeedsTranscode,
                hwAccelToUse,
                _appSettings.VideoScale,
                fileInfo.Videos.Find(f => f.Index == videoStreamIndex)?.WidthAndHeightText)
                : mrl;

            var metadata = isVideoFile ? new MovieMetadata
            {
                Title = title,
            } : new GenericMediaMetadata
            {
                Title = title,
            };
            var media = new MediaInformation
            {
                ContentId = url,
                Metadata  = metadata,
                //You have to set the contenttype before hand, with that, the album art of a music file will be shown
                ContentType = _ffmpegService.GetOutputTranscodeMimeType(mrl)
            };

            var  activeTrackIds    = new List <int>();
            bool useSubTitleStream = subtitleStreamIndex >= 0;

            if (useSubTitleStream || !string.IsNullOrEmpty(GetSubTitles?.Invoke()))
            {
                _logger.LogInformation($"{nameof(StartPlay)}: Subtitles were specified, generating a compatible one...");
                string subtitleLocation = useSubTitleStream ? mrl : GetSubTitles.Invoke();
                string subTitleFilePath = _fileService.GetSubTitleFilePath();
                await _ffmpegService.GenerateSubTitles(
                    subtitleLocation,
                    subTitleFilePath,
                    seconds,
                    useSubTitleStream?subtitleStreamIndex : 0,
                    _appSettings.SubtitleDelayInSeconds,
                    default);

                _subtitle.TrackContentId = _appWebServer.GetSubTitlePath(subTitleFilePath);
                _logger.LogInformation($"{nameof(StartPlay)}: Subtitles were generated");
                media.Tracks.Add(_subtitle);
                media.TextTrackStyle = GetSubtitleStyle();
                activeTrackIds.Add(SubTitleDefaultTrackId);
            }

            string firstThumbnail = await GetFirstThumbnail().ConfigureAwait(false);

            string imgUrl = string.Empty;

            if (isLocal)
            {
                _logger.LogInformation($"{nameof(StartPlay)}: File is a local one, generating metadata...");
                imgUrl = _appWebServer.GetPreviewPath(firstThumbnail);

                if (isVideoFile)
                {
                    media.StreamType = StreamType.Live;
                }
                media.Duration = fileInfo.Format.Duration;
                if (isMusicFile)
                {
                    media.Metadata = new MusicTrackMediaMetadata
                    {
                        Title     = title,
                        AlbumName = fileInfo.Format.Tag?.Album,
                        Artist    = fileInfo.Format.Tag?.Artist,
                    };
                }
            }
            else if (_youtubeUrlDecoder.IsYoutubeUrl(media.ContentId))
            {
                _logger.LogInformation($"{nameof(StartPlay)}: File is a youtube link, parsing it...");
                var ytMedia = await _youtubeUrlDecoder.Parse(media.ContentId, quality);

                QualitiesChanged?.Invoke(ytMedia.SelectedQuality, ytMedia.Qualities);

                imgUrl                  = ytMedia.ThumbnailUrl;
                media.ContentId         = ytMedia.Url;
                media.Metadata.Title    = ytMedia.Title;
                media.Metadata.Subtitle = ytMedia.Description;
                if (ytMedia.IsHls)
                {
                    fileInfo = await _ffmpegService.GetFileInfo(ytMedia.Url, default);

                    if (fileInfo == null)
                    {
                        _logger.LogWarning($"{nameof(StartPlay)}: Couldn't get the file info for url = {ytMedia.Url}");
                        throw new Exception($"File info is null for yt hls = {ytMedia.Url}");
                    }

                    var closestQuality = fileInfo.Videos
                                         .Select(v => v.Height)
                                         .GetClosest(quality);
                    var videoInfo = fileInfo.Videos.First(v => v.Height == closestQuality);
                    videoStreamIndex = videoInfo.Index;
                    audioStreamIndex = fileInfo.Audios.Any()
                        ? fileInfo.Audios.Select(a => a.Index).GetClosest(videoStreamIndex)
                        : -1;

                    videoNeedsTranscode = _ffmpegService.VideoNeedsTranscode(videoStreamIndex, _appSettings.ForceVideoTranscode, _appSettings.VideoScale, fileInfo);
                    audioNeedsTranscode = _ffmpegService.AudioNeedsTranscode(audioStreamIndex, _appSettings.ForceAudioTranscode, fileInfo);

                    media.Duration   = -1;
                    media.StreamType = StreamType.Live;
                    media.ContentId  = _appWebServer.GetMediaUrl(
                        ytMedia.Url,
                        videoStreamIndex,
                        audioStreamIndex,
                        seconds,
                        videoNeedsTranscode,
                        audioNeedsTranscode,
                        HwAccelDeviceType.None,
                        VideoScaleType.Original,
                        videoInfo.WidthAndHeightText);
                    media.ContentType = _ffmpegService.GetOutputTranscodeMimeType(media.ContentId);
                }
            }

            if (!string.IsNullOrEmpty(imgUrl))
            {
                media.Metadata.Images.Add(new GoogleCast.Models.Image
                {
                    Url = imgUrl
                });
            }

            _logger.LogInformation($"{nameof(StartPlay)}: Trying to load url = {media.ContentId}");
            var status = await _player.LoadAsync(media, true, seconds, activeTrackIds.ToArray());

            if (status is null)
            {
                var msg = $"Couldn't load url = {media.ContentId}";
                _logger.LogWarning($"{nameof(StartPlay)}: {msg}");
                throw new Exception(msg);
            }
            _logger.LogInformation($"{nameof(StartPlay)}: Url was successfully loaded");

            FileLoaded(metadata.Title, imgUrl, _player.CurrentMediaDuration, _player.CurrentVolumeLevel, _player.IsMuted);
        }
        void SimpleCastBtn_TouchUpInside(object sender, EventArgs e)
        {
            //Show Alert if not connected
             if (DeviceManager == null || DeviceManager.ConnectionState != ConnectionState.Connected)
             {
                new UIAlertView ("Not Connected", "Please connect to a cast device", null, "Ok", null).Show ();
                return;
             }

             // Define Media metadata
             var metadata = new MediaMetadata ();
             metadata.SetString ("Big Buck Bunny (2008)", MetadataKey.Title);
             metadata.SetString ("Big Buck Bunny tells the story of a giant rabbit with a heart bigger than " +
                "himself. When one sunny day three rodents rudely harass him, something " +
                "snaps... and the rabbit ain't no bunny anymore! In the typical cartoon " +
                "tradition he prepares the nasty rodents a comical revenge.",
                MetadataKey.Subtitle);

             metadata.AddImage (new Image (new NSUrl ("http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/images/BigBuckBunny.jpg"), 480, 360));

             // define Media information
             var mediaInformation = new MediaInformation ("http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4",
                MediaStreamType.None, "video/mp4", metadata, 0, null);
             // cast video
             MediaControlChannel.LoadMedia (mediaInformation, true, 0);
        }
Ejemplo n.º 25
0
 public async Task LoadAsync(MediaInformation media, (bool hasSubtitle, int trackId) subtitle)