DynamicHlsService.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Controller.Channels;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Dlna;
  6. using MediaBrowser.Controller.Dto;
  7. using MediaBrowser.Controller.Library;
  8. using MediaBrowser.Controller.LiveTv;
  9. using MediaBrowser.Controller.MediaEncoding;
  10. using MediaBrowser.Controller.Persistence;
  11. using MediaBrowser.Model.IO;
  12. using ServiceStack;
  13. using System;
  14. using System.Collections.Generic;
  15. using System.Globalization;
  16. using System.IO;
  17. using System.Text;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  20. using MimeTypes = ServiceStack.MimeTypes;
  21. namespace MediaBrowser.Api.Playback.Hls
  22. {
  23. [Route("/Videos/{Id}/master.m3u8", "GET")]
  24. [Api(Description = "Gets a video stream using HTTP live streaming.")]
  25. public class GetMasterHlsVideoStream : VideoStreamRequest
  26. {
  27. [ApiMember(Name = "BaselineStreamAudioBitRate", Description = "Optional. Specify the audio bitrate for the baseline stream.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
  28. public int? BaselineStreamAudioBitRate { get; set; }
  29. [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")]
  30. public bool AppendBaselineStream { get; set; }
  31. }
  32. [Route("/Videos/{Id}/main.m3u8", "GET")]
  33. [Api(Description = "Gets a video stream using HTTP live streaming.")]
  34. public class GetMainHlsVideoStream : VideoStreamRequest
  35. {
  36. }
  37. [Route("/Videos/{Id}/baseline.m3u8", "GET")]
  38. [Api(Description = "Gets a video stream using HTTP live streaming.")]
  39. public class GetBaselineHlsVideoStream : VideoStreamRequest
  40. {
  41. }
  42. /// <summary>
  43. /// Class GetHlsVideoSegment
  44. /// </summary>
  45. [Route("/Videos/{Id}/hlsdynamic/{PlaylistId}/{SegmentId}.ts", "GET")]
  46. [Api(Description = "Gets an Http live streaming segment file. Internal use only.")]
  47. public class GetDynamicHlsVideoSegment : VideoStreamRequest
  48. {
  49. public string PlaylistId { get; set; }
  50. /// <summary>
  51. /// Gets or sets the segment id.
  52. /// </summary>
  53. /// <value>The segment id.</value>
  54. public string SegmentId { get; set; }
  55. }
  56. public class DynamicHlsService : BaseHlsService
  57. {
  58. public DynamicHlsService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IDtoService dtoService, IFileSystem fileSystem, IItemRepository itemRepository, ILiveTvManager liveTvManager, IEncodingManager encodingManager, IDlnaManager dlnaManager, IChannelManager channelManager, IHttpClient httpClient) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, dtoService, fileSystem, itemRepository, liveTvManager, encodingManager, dlnaManager, channelManager, httpClient)
  59. {
  60. }
  61. public object Get(GetMasterHlsVideoStream request)
  62. {
  63. var result = GetAsync(request).Result;
  64. return result;
  65. }
  66. public object Get(GetDynamicHlsVideoSegment request)
  67. {
  68. if (string.Equals("baseline", request.PlaylistId, StringComparison.OrdinalIgnoreCase))
  69. {
  70. return GetDynamicSegment(request, false).Result;
  71. }
  72. return GetDynamicSegment(request, true).Result;
  73. }
  74. private async Task<object> GetDynamicSegment(GetDynamicHlsVideoSegment request, bool isMain)
  75. {
  76. var index = int.Parse(request.SegmentId, NumberStyles.Integer, UsCulture);
  77. var state = await GetState(request, CancellationToken.None).ConfigureAwait(false);
  78. var playlistPath = Path.ChangeExtension(state.OutputFilePath, ".m3u8");
  79. var path = GetSegmentPath(playlistPath, index);
  80. if (File.Exists(path))
  81. {
  82. return GetSegementResult(path);
  83. }
  84. if (!File.Exists(playlistPath))
  85. {
  86. await StartFfMpeg(state, playlistPath, new CancellationTokenSource()).ConfigureAwait(false);
  87. await WaitForMinimumSegmentCount(playlistPath, GetSegmentWait(), CancellationToken.None).ConfigureAwait(false);
  88. }
  89. return GetSegementResult(path);
  90. }
  91. private string GetSegmentPath(string playlist, int index)
  92. {
  93. var folder = Path.GetDirectoryName(playlist);
  94. var filename = Path.GetFileNameWithoutExtension(playlist);
  95. return Path.Combine(folder, filename + index.ToString(UsCulture) + ".ts");
  96. }
  97. private object GetSegementResult(string path)
  98. {
  99. // TODO: Handle if it's currently being written to
  100. return ResultFactory.GetStaticFileResult(Request, path);
  101. }
  102. private async Task<object> GetAsync(GetMasterHlsVideoStream request)
  103. {
  104. var state = await GetState(request, CancellationToken.None).ConfigureAwait(false);
  105. int audioBitrate;
  106. int videoBitrate;
  107. GetPlaylistBitrates(state, out audioBitrate, out videoBitrate);
  108. var appendBaselineStream = false;
  109. var baselineStreamBitrate = 64000;
  110. var hlsVideoRequest = state.VideoRequest as GetMasterHlsVideoStream;
  111. if (hlsVideoRequest != null)
  112. {
  113. appendBaselineStream = hlsVideoRequest.AppendBaselineStream;
  114. baselineStreamBitrate = hlsVideoRequest.BaselineStreamAudioBitRate ?? baselineStreamBitrate;
  115. }
  116. var playlistText = GetMasterPlaylistFileText(videoBitrate + audioBitrate, appendBaselineStream, baselineStreamBitrate);
  117. return ResultFactory.GetResult(playlistText, MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary<string, string>());
  118. }
  119. private string GetMasterPlaylistFileText(int bitrate, bool includeBaselineStream, int baselineStreamBitrate)
  120. {
  121. var builder = new StringBuilder();
  122. builder.AppendLine("#EXTM3U");
  123. // Pad a little to satisfy the apple hls validator
  124. var paddedBitrate = Convert.ToInt32(bitrate * 1.05);
  125. var queryStringIndex = Request.RawUrl.IndexOf('?');
  126. var queryString = queryStringIndex == -1 ? string.Empty : Request.RawUrl.Substring(queryStringIndex);
  127. // Main stream
  128. builder.AppendLine("#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=" + paddedBitrate.ToString(UsCulture));
  129. var playlistUrl = "main.m3u8" + queryString;
  130. builder.AppendLine(playlistUrl);
  131. // Low bitrate stream
  132. if (includeBaselineStream)
  133. {
  134. builder.AppendLine("#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=" + baselineStreamBitrate.ToString(UsCulture));
  135. playlistUrl = "baseline.m3u8" + queryString;
  136. builder.AppendLine(playlistUrl);
  137. }
  138. return builder.ToString();
  139. }
  140. public object Get(GetMainHlsVideoStream request)
  141. {
  142. var result = GetPlaylistAsync(request, "main").Result;
  143. return result;
  144. }
  145. public object Get(GetBaselineHlsVideoStream request)
  146. {
  147. var result = GetPlaylistAsync(request, "baseline").Result;
  148. return result;
  149. }
  150. private async Task<object> GetPlaylistAsync(VideoStreamRequest request, string name)
  151. {
  152. var state = await GetState(request, CancellationToken.None).ConfigureAwait(false);
  153. var builder = new StringBuilder();
  154. builder.AppendLine("#EXTM3U");
  155. builder.AppendLine("#EXT-X-VERSION:3");
  156. builder.AppendLine("#EXT-X-TARGETDURATION:" + state.SegmentLength.ToString(UsCulture));
  157. builder.AppendLine("#EXT-X-MEDIA-SEQUENCE:0");
  158. var queryStringIndex = Request.RawUrl.IndexOf('?');
  159. var queryString = queryStringIndex == -1 ? string.Empty : Request.RawUrl.Substring(queryStringIndex);
  160. var seconds = TimeSpan.FromTicks(state.RunTimeTicks ?? 0).TotalSeconds;
  161. var index = 0;
  162. while (seconds > 0)
  163. {
  164. var length = seconds >= state.SegmentLength ? state.SegmentLength : seconds;
  165. builder.AppendLine("#EXTINF:" + length.ToString(UsCulture));
  166. builder.AppendLine(string.Format("hlsdynamic/{0}/{1}.ts{2}",
  167. name,
  168. index.ToString(UsCulture),
  169. queryString));
  170. seconds -= state.SegmentLength;
  171. index++;
  172. }
  173. builder.AppendLine("#EXT-X-ENDLIST");
  174. var playlistText = builder.ToString();
  175. return ResultFactory.GetResult(playlistText, MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary<string, string>());
  176. }
  177. protected override string GetAudioArguments(StreamState state)
  178. {
  179. var codec = state.OutputAudioCodec;
  180. if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
  181. {
  182. return "-codec:a:0 copy";
  183. }
  184. var args = "-codec:a:0 " + codec;
  185. if (state.AudioStream != null)
  186. {
  187. var channels = state.OutputAudioChannels;
  188. if (channels.HasValue)
  189. {
  190. args += " -ac " + channels.Value;
  191. }
  192. var bitrate = state.OutputAudioBitrate;
  193. if (bitrate.HasValue)
  194. {
  195. args += " -ab " + bitrate.Value.ToString(UsCulture);
  196. }
  197. args += " " + GetAudioFilterParam(state, true);
  198. return args;
  199. }
  200. return args;
  201. }
  202. protected override string GetVideoArguments(StreamState state, bool performSubtitleConversion)
  203. {
  204. var codec = state.OutputVideoCodec;
  205. // See if we can save come cpu cycles by avoiding encoding
  206. if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
  207. {
  208. return IsH264(state.VideoStream) ? "-codec:v:0 copy -bsf h264_mp4toannexb" : "-codec:v:0 copy";
  209. }
  210. const string keyFrameArg = " -force_key_frames expr:if(isnan(prev_forced_t),gte(t,.1),gte(t,prev_forced_t+5))";
  211. var hasGraphicalSubs = state.SubtitleStream != null && state.SubtitleStream.IsGraphicalSubtitleStream;
  212. var args = "-codec:v:0 " + codec + " " + GetVideoQualityParam(state, "libx264", true) + keyFrameArg;
  213. // Add resolution params, if specified
  214. if (!hasGraphicalSubs)
  215. {
  216. if (state.VideoRequest.Width.HasValue || state.VideoRequest.Height.HasValue || state.VideoRequest.MaxHeight.HasValue || state.VideoRequest.MaxWidth.HasValue)
  217. {
  218. args += GetOutputSizeParam(state, codec, performSubtitleConversion, CancellationToken.None);
  219. }
  220. }
  221. // This is for internal graphical subs
  222. if (hasGraphicalSubs)
  223. {
  224. args += GetInternalGraphicalSubtitleParam(state, codec);
  225. }
  226. return args;
  227. }
  228. /// <summary>
  229. /// Gets the segment file extension.
  230. /// </summary>
  231. /// <param name="state">The state.</param>
  232. /// <returns>System.String.</returns>
  233. protected override string GetSegmentFileExtension(StreamState state)
  234. {
  235. return ".ts";
  236. }
  237. }
  238. }