VideoHlsService.cs 8.9 KB

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