using MediaBrowser.Common.IO; using MediaBrowser.Controller.Channels; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Dlna; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Model.IO; using ServiceStack; using System; using System.IO; using System.Linq; using System.Threading.Tasks; namespace MediaBrowser.Api.Playback.Hls { /// /// Class GetHlsVideoStream /// [Route("/Videos/{Id}/stream.m3u8", "GET")] [Api(Description = "Gets a video stream using HTTP live streaming.")] public class GetHlsVideoStream : VideoStreamRequest { [ApiMember(Name = "BaselineStreamAudioBitRate", Description = "Optional. Specify the audio bitrate for the baseline stream.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")] public int? BaselineStreamAudioBitRate { get; set; } [ApiMember(Name = "AppendBaselineStream", Description = "Optional. Whether or not to include a baseline audio-only stream in the master playlist.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")] public bool AppendBaselineStream { get; set; } [ApiMember(Name = "TimeStampOffsetMs", Description = "Optional. Alter the timestamps in the playlist by a given amount, in ms. Default is 1000.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")] public int TimeStampOffsetMs { get; set; } } [Route("/Videos/{Id}/live.m3u8", "GET")] [Api(Description = "Gets a video stream using HTTP live streaming.")] public class GetLiveHlsStream : VideoStreamRequest { } /// /// Class GetHlsVideoSegment /// [Route("/Videos/{Id}/hls/{PlaylistId}/{SegmentId}.ts", "GET")] [Api(Description = "Gets an Http live streaming segment file. Internal use only.")] public class GetHlsVideoSegment : VideoStreamRequest { public string PlaylistId { get; set; } /// /// Gets or sets the segment id. /// /// The segment id. public string SegmentId { get; set; } } /// /// Class VideoHlsService /// public class VideoHlsService : BaseHlsService { public VideoHlsService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, ILiveTvManager liveTvManager, IDlnaManager dlnaManager, IChannelManager channelManager, ISubtitleEncoder subtitleEncoder) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, liveTvManager, dlnaManager, channelManager, subtitleEncoder) { } /// /// Gets the specified request. /// /// The request. /// System.Object. public object Get(GetHlsVideoSegment request) { var file = request.SegmentId + Path.GetExtension(Request.PathInfo); file = Path.Combine(ServerConfigurationManager.ApplicationPaths.TranscodingTempPath, file); OnBeginRequest(request.PlaylistId); return ResultFactory.GetStaticFileResult(Request, file); } /// /// Called when [begin request]. /// /// The playlist id. protected void OnBeginRequest(string playlistId) { var normalizedPlaylistId = playlistId.Replace("-low", string.Empty); foreach (var playlist in Directory.EnumerateFiles(ServerConfigurationManager.ApplicationPaths.TranscodingTempPath, "*.m3u8") .Where(i => i.IndexOf(normalizedPlaylistId, StringComparison.OrdinalIgnoreCase) != -1) .ToList()) { ExtendPlaylistTimer(playlist); } } private async void ExtendPlaylistTimer(string playlist) { ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlist, TranscodingJobType.Hls); await Task.Delay(20000).ConfigureAwait(false); ApiEntryPoint.Instance.OnTranscodeEndRequest(playlist, TranscodingJobType.Hls); } /// /// Gets the specified request. /// /// The request. /// System.Object. public object Get(GetHlsVideoStream request) { return ProcessRequest(request, false); } public object Get(GetLiveHlsStream request) { return ProcessRequest(request, true); } /// /// Gets the audio arguments. /// /// The state. /// System.String. protected override string GetAudioArguments(StreamState state) { var codec = state.OutputAudioCodec; if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase)) { return "-codec:a:0 copy"; } var args = "-codec:a:0 " + codec; var channels = state.OutputAudioChannels; if (channels.HasValue) { args += " -ac " + channels.Value; } var bitrate = state.OutputAudioBitrate; if (bitrate.HasValue) { args += " -ab " + bitrate.Value.ToString(UsCulture); } args += " " + GetAudioFilterParam(state, true); return args; } /// /// Gets the video arguments. /// /// The state. /// System.String. protected override string GetVideoArguments(StreamState state) { var codec = state.OutputVideoCodec; // See if we can save come cpu cycles by avoiding encoding if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase)) { // TOOD: Switch to -bsf dump_extra? return IsH264(state.VideoStream) ? "-codec:v:0 copy -bsf h264_mp4toannexb" : "-codec:v:0 copy"; } var keyFrameArg = string.Format(" -force_key_frames expr:gte(t,n_forced*{0})", state.SegmentLength.ToString(UsCulture)); var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream; var args = "-codec:v:0 " + codec + " " + GetVideoQualityParam(state, "libx264", true) + keyFrameArg; // Add resolution params, if specified if (!hasGraphicalSubs) { args += GetOutputSizeParam(state, codec); } // This is for internal graphical subs if (hasGraphicalSubs) { args += GetGraphicalSubtitleParam(state, codec); } return args; } /// /// Gets the segment file extension. /// /// The state. /// System.String. protected override string GetSegmentFileExtension(StreamState state) { return ".ts"; } } }