VideoHlsService.cs 8.7 KB

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