VideoHlsService.cs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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. var bitrate = GetAudioBitrateParam(state);
  125. if (bitrate.HasValue)
  126. {
  127. args += " -ab " + bitrate.Value.ToString(UsCulture);
  128. }
  129. var volParam = string.Empty;
  130. // Boost volume to 200% when downsampling from 6ch to 2ch
  131. if (channels.HasValue && channels.Value <= 2 && state.AudioStream.Channels.HasValue && state.AudioStream.Channels.Value > 5)
  132. {
  133. volParam = ",volume=2.000000";
  134. }
  135. args += string.Format(" -af \"aresample=async=1000{0}\"", volParam);
  136. return args;
  137. }
  138. return args;
  139. }
  140. /// <summary>
  141. /// Gets the video arguments.
  142. /// </summary>
  143. /// <param name="state">The state.</param>
  144. /// <param name="performSubtitleConversion">if set to <c>true</c> [perform subtitle conversion].</param>
  145. /// <returns>System.String.</returns>
  146. protected override string GetVideoArguments(StreamState state, bool performSubtitleConversion)
  147. {
  148. var codec = GetVideoCodec(state.VideoRequest);
  149. // See if we can save come cpu cycles by avoiding encoding
  150. if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
  151. {
  152. return IsH264(state.VideoStream) ? "-codec:v:0 copy -bsf h264_mp4toannexb" : "-codec:v:0 copy";
  153. }
  154. const string keyFrameArg = " -force_key_frames expr:if(isnan(prev_forced_t),gte(t,0),gte(t,prev_forced_t+5))";
  155. var args = "-codec:v:0 " + codec + " -preset superfast" + keyFrameArg;
  156. var bitrate = GetVideoBitrateParam(state);
  157. if (bitrate.HasValue)
  158. {
  159. args += string.Format(" -b:v {0} -maxrate {0} -minrate {0} -bufsize ({0}/3)*2", bitrate.Value.ToString(UsCulture));
  160. }
  161. // Add resolution params, if specified
  162. if (state.VideoRequest.Width.HasValue || state.VideoRequest.Height.HasValue || state.VideoRequest.MaxHeight.HasValue || state.VideoRequest.MaxWidth.HasValue)
  163. {
  164. args += GetOutputSizeParam(state, codec, performSubtitleConversion);
  165. }
  166. // Get the output framerate based on the FrameRate param
  167. var framerate = state.VideoRequest.Framerate ?? 0;
  168. // We have to supply a framerate for hls, so if it's null, account for that here
  169. if (framerate.Equals(0))
  170. {
  171. framerate = state.VideoStream.AverageFrameRate ?? 0;
  172. }
  173. if (framerate.Equals(0))
  174. {
  175. framerate = state.VideoStream.RealFrameRate ?? 0;
  176. }
  177. if (framerate.Equals(0))
  178. {
  179. framerate = 23.976;
  180. }
  181. framerate = Math.Round(framerate);
  182. args += string.Format(" -r {0}", framerate);
  183. args += " -vsync vfr";
  184. if (!string.IsNullOrEmpty(state.VideoRequest.Profile))
  185. {
  186. args += " -profile:v " + state.VideoRequest.Profile;
  187. }
  188. if (!string.IsNullOrEmpty(state.VideoRequest.Level))
  189. {
  190. args += " -level " + state.VideoRequest.Level;
  191. }
  192. if (state.SubtitleStream != null)
  193. {
  194. // This is for internal graphical subs
  195. if (!state.SubtitleStream.IsExternal && (state.SubtitleStream.Codec.IndexOf("pgs", StringComparison.OrdinalIgnoreCase) != -1 || state.SubtitleStream.Codec.IndexOf("dvd", StringComparison.OrdinalIgnoreCase) != -1))
  196. {
  197. args += GetInternalGraphicalSubtitleParam(state, codec);
  198. }
  199. }
  200. return args;
  201. }
  202. /// <summary>
  203. /// Gets the segment file extension.
  204. /// </summary>
  205. /// <param name="state">The state.</param>
  206. /// <returns>System.String.</returns>
  207. protected override string GetSegmentFileExtension(StreamState state)
  208. {
  209. return ".ts";
  210. }
  211. }
  212. }