VideoHlsService.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. using MediaBrowser.Common.MediaInfo;
  2. using MediaBrowser.Controller;
  3. using MediaBrowser.Controller.Library;
  4. using MediaBrowser.Model.IO;
  5. using ServiceStack.ServiceHost;
  6. using System;
  7. using System.IO;
  8. namespace MediaBrowser.Api.Playback.Hls
  9. {
  10. /// <summary>
  11. /// Class GetHlsVideoStream
  12. /// </summary>
  13. [Route("/Videos/{Id}/stream.m3u8", "GET")]
  14. [Api(Description = "Gets a video stream using HTTP live streaming.")]
  15. public class GetHlsVideoStream : VideoStreamRequest
  16. {
  17. }
  18. /// <summary>
  19. /// Class GetHlsVideoSegment
  20. /// </summary>
  21. [Route("/Videos/{Id}/hls/{PlaylistId}/{SegmentId}.ts", "GET")]
  22. [Api(Description = "Gets an Http live streaming segment file. Internal use only.")]
  23. public class GetHlsVideoSegment
  24. {
  25. /// <summary>
  26. /// Gets or sets the id.
  27. /// </summary>
  28. /// <value>The id.</value>
  29. public string Id { get; set; }
  30. public string PlaylistId { get; set; }
  31. /// <summary>
  32. /// Gets or sets the segment id.
  33. /// </summary>
  34. /// <value>The segment id.</value>
  35. public string SegmentId { get; set; }
  36. }
  37. /// <summary>
  38. /// Class GetHlsVideoSegment
  39. /// </summary>
  40. [Route("/Videos/{Id}/hls/{PlaylistId}/stream.m3u8", "GET")]
  41. [Api(Description = "Gets an Http live streaming segment file. Internal use only.")]
  42. public class GetHlsPlaylist
  43. {
  44. /// <summary>
  45. /// Gets or sets the id.
  46. /// </summary>
  47. /// <value>The id.</value>
  48. public string Id { get; set; }
  49. public string PlaylistId { get; set; }
  50. }
  51. /// <summary>
  52. /// Class VideoHlsService
  53. /// </summary>
  54. public class VideoHlsService : BaseHlsService
  55. {
  56. /// <summary>
  57. /// Initializes a new instance of the <see cref="BaseStreamingService" /> class.
  58. /// </summary>
  59. /// <param name="appPaths">The app paths.</param>
  60. /// <param name="userManager">The user manager.</param>
  61. /// <param name="libraryManager">The library manager.</param>
  62. /// <param name="isoManager">The iso manager.</param>
  63. /// <param name="mediaEncoder">The media encoder.</param>
  64. public VideoHlsService(IServerApplicationPaths appPaths, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder)
  65. : base(appPaths, userManager, libraryManager, isoManager, mediaEncoder)
  66. {
  67. }
  68. /// <summary>
  69. /// Gets the specified request.
  70. /// </summary>
  71. /// <param name="request">The request.</param>
  72. /// <returns>System.Object.</returns>
  73. public object Get(GetHlsVideoSegment request)
  74. {
  75. ExtendHlsTimer(request.Id, request.PlaylistId);
  76. var file = request.SegmentId + Path.GetExtension(RequestContext.PathInfo);
  77. file = Path.Combine(ApplicationPaths.EncodedMediaCachePath, file);
  78. return ResultFactory.GetStaticFileResult(RequestContext, file);
  79. }
  80. public object Get(GetHlsPlaylist request)
  81. {
  82. ExtendHlsTimer(request.Id, request.PlaylistId);
  83. var file = request.PlaylistId + Path.GetExtension(RequestContext.PathInfo);
  84. file = Path.Combine(ApplicationPaths.EncodedMediaCachePath, file);
  85. return ResultFactory.GetStaticFileResult(RequestContext, file);
  86. }
  87. /// <summary>
  88. /// Gets the specified request.
  89. /// </summary>
  90. /// <param name="request">The request.</param>
  91. /// <returns>System.Object.</returns>
  92. public object Get(GetHlsVideoStream request)
  93. {
  94. return ProcessRequest(request);
  95. }
  96. /// <summary>
  97. /// Gets the audio arguments.
  98. /// </summary>
  99. /// <param name="state">The state.</param>
  100. /// <returns>System.String.</returns>
  101. protected override string GetAudioArguments(StreamState state)
  102. {
  103. var codec = GetAudioCodec(state.Request);
  104. if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
  105. {
  106. return "-codec:a:0 copy";
  107. }
  108. var args = "-codec:a:0 " + codec;
  109. if (state.AudioStream != null)
  110. {
  111. if (string.Equals(codec, "aac", StringComparison.OrdinalIgnoreCase))
  112. {
  113. args += " -strict experimental";
  114. }
  115. var channels = GetNumAudioChannelsParam(state.Request, state.AudioStream);
  116. if (channels.HasValue)
  117. {
  118. args += " -ac " + channels.Value;
  119. }
  120. if (state.Request.AudioSampleRate.HasValue)
  121. {
  122. args += " -ar " + state.Request.AudioSampleRate.Value;
  123. }
  124. if (state.Request.AudioBitRate.HasValue)
  125. {
  126. args += " -ab " + state.Request.AudioBitRate.Value;
  127. }
  128. var volParam = string.Empty;
  129. // Boost volume to 200% when downsampling from 6ch to 2ch
  130. if (channels.HasValue && channels.Value <= 2 && state.AudioStream.Channels.HasValue && state.AudioStream.Channels.Value > 5)
  131. {
  132. volParam = ",volume=2.000000";
  133. }
  134. args += string.Format(" -af \"aresample=async=1000{0}\"", volParam);
  135. return args;
  136. }
  137. return args;
  138. }
  139. /// <summary>
  140. /// Gets the video arguments.
  141. /// </summary>
  142. /// <param name="state">The state.</param>
  143. /// <param name="performSubtitleConversion">if set to <c>true</c> [perform subtitle conversion].</param>
  144. /// <returns>System.String.</returns>
  145. protected override string GetVideoArguments(StreamState state, bool performSubtitleConversion)
  146. {
  147. var codec = GetVideoCodec(state.VideoRequest);
  148. // See if we can save come cpu cycles by avoiding encoding
  149. if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
  150. {
  151. return IsH264(state.VideoStream) ? "-codec:v:0 copy -bsf h264_mp4toannexb" : "-codec:v:0 copy";
  152. }
  153. const string keyFrameArg = " -force_key_frames expr:if(isnan(prev_forced_t),gte(t,0),gte(t,prev_forced_t+5))";
  154. var args = "-codec:v:0 " + codec + " -preset superfast" + keyFrameArg;
  155. if (state.VideoRequest.VideoBitRate.HasValue)
  156. {
  157. // Make sure we don't request a bitrate higher than the source
  158. var currentBitrate = state.VideoStream == null ? state.VideoRequest.VideoBitRate.Value : state.VideoStream.BitRate ?? state.VideoRequest.VideoBitRate.Value;
  159. var bitrate = Math.Min(currentBitrate, state.VideoRequest.VideoBitRate.Value);
  160. args += string.Format(" -b:v {0}", bitrate);
  161. }
  162. // Add resolution params, if specified
  163. if (state.VideoRequest.Width.HasValue || state.VideoRequest.Height.HasValue || state.VideoRequest.MaxHeight.HasValue || state.VideoRequest.MaxWidth.HasValue)
  164. {
  165. args += GetOutputSizeParam(state, codec, performSubtitleConversion);
  166. }
  167. // Get the output framerate based on the FrameRate param
  168. var framerate = state.VideoRequest.Framerate ?? 0;
  169. // We have to supply a framerate for hls, so if it's null, account for that here
  170. if (framerate.Equals(0))
  171. {
  172. framerate = state.VideoStream.AverageFrameRate ?? 0;
  173. }
  174. if (framerate.Equals(0))
  175. {
  176. framerate = state.VideoStream.RealFrameRate ?? 0;
  177. }
  178. if (framerate.Equals(0))
  179. {
  180. framerate = 23.976;
  181. }
  182. framerate = Math.Round(framerate);
  183. args += string.Format(" -r {0}", framerate);
  184. args += " -vsync vfr";
  185. if (!string.IsNullOrEmpty(state.VideoRequest.Profile))
  186. {
  187. args += " -profile:v " + state.VideoRequest.Profile;
  188. }
  189. if (!string.IsNullOrEmpty(state.VideoRequest.Level))
  190. {
  191. args += " -level " + state.VideoRequest.Level;
  192. }
  193. if (state.SubtitleStream != null)
  194. {
  195. // This is for internal graphical subs
  196. if (!state.SubtitleStream.IsExternal && (state.SubtitleStream.Codec.IndexOf("pgs", StringComparison.OrdinalIgnoreCase) != -1 || state.SubtitleStream.Codec.IndexOf("dvd", StringComparison.OrdinalIgnoreCase) != -1))
  197. {
  198. args += GetInternalGraphicalSubtitleParam(state, codec);
  199. }
  200. }
  201. return args;
  202. }
  203. /// <summary>
  204. /// Gets the segment file extension.
  205. /// </summary>
  206. /// <param name="state">The state.</param>
  207. /// <returns>System.String.</returns>
  208. protected override string GetSegmentFileExtension(StreamState state)
  209. {
  210. return ".ts";
  211. }
  212. }
  213. }