2
0

VideoHlsService.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. using System.IO;
  2. using System.Linq;
  3. using System.Threading.Tasks;
  4. using MediaBrowser.Common.IO;
  5. using MediaBrowser.Common.MediaInfo;
  6. using MediaBrowser.Controller;
  7. using MediaBrowser.Controller.Library;
  8. using System;
  9. using ServiceStack.ServiceHost;
  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. await Task.Delay(2000).ConfigureAwait(false);
  70. ApiEntryPoint.Instance.OnTranscodeEndRequest(playlist1, TranscodingJobType.Hls);
  71. });
  72. }
  73. var file = SegmentFilePrefix + request.SegmentId + Path.GetExtension(RequestContext.PathInfo);
  74. file = Path.Combine(ApplicationPaths.EncodedMediaCachePath, file);
  75. return ResultFactory.GetStaticFileResult(RequestContext, file);
  76. }
  77. /// <summary>
  78. /// Gets the specified request.
  79. /// </summary>
  80. /// <param name="request">The request.</param>
  81. /// <returns>System.Object.</returns>
  82. public object Get(GetHlsVideoStream request)
  83. {
  84. return ProcessRequest(request);
  85. }
  86. /// <summary>
  87. /// Gets the audio arguments.
  88. /// </summary>
  89. /// <param name="state">The state.</param>
  90. /// <returns>System.String.</returns>
  91. protected override string GetAudioArguments(StreamState state)
  92. {
  93. var codec = GetAudioCodec(state.Request);
  94. if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
  95. {
  96. return "-codec:a:0 copy";
  97. }
  98. var args = "-codec:a:0 " + codec;
  99. if (state.AudioStream != null)
  100. {
  101. if (string.Equals(codec, "aac", StringComparison.OrdinalIgnoreCase))
  102. {
  103. args += " -strict experimental";
  104. }
  105. var channels = GetNumAudioChannelsParam(state.Request, state.AudioStream);
  106. if (channels.HasValue)
  107. {
  108. args += " -ac " + channels.Value;
  109. }
  110. if (state.Request.AudioSampleRate.HasValue)
  111. {
  112. args += " -ar " + state.Request.AudioSampleRate.Value;
  113. }
  114. if (state.Request.AudioBitRate.HasValue)
  115. {
  116. args += " -ab " + state.Request.AudioBitRate.Value;
  117. }
  118. var volParam = string.Empty;
  119. // Boost volume to 200% when downsampling from 6ch to 2ch
  120. if (channels.HasValue && channels.Value <= 2 && state.AudioStream.Channels.HasValue && state.AudioStream.Channels.Value > 5)
  121. {
  122. volParam = ",volume=2.000000";
  123. }
  124. args += string.Format(" -af \"aresample=async=1000{0}\"", volParam);
  125. return args;
  126. }
  127. return args;
  128. }
  129. /// <summary>
  130. /// Gets the video arguments.
  131. /// </summary>
  132. /// <param name="state">The state.</param>
  133. /// <param name="performSubtitleConversion">if set to <c>true</c> [perform subtitle conversion].</param>
  134. /// <returns>System.String.</returns>
  135. protected override string GetVideoArguments(StreamState state, bool performSubtitleConversion)
  136. {
  137. var codec = GetVideoCodec(state.VideoRequest);
  138. // See if we can save come cpu cycles by avoiding encoding
  139. if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
  140. {
  141. return IsH264(state.VideoStream) ? "-codec:v:0 copy -bsf h264_mp4toannexb" : "-codec:v:0 copy";
  142. }
  143. const string keyFrameArg = " -force_key_frames expr:if(isnan(prev_forced_t),gte(t,0),gte(t,prev_forced_t+5))";
  144. var args = "-codec:v:0 " + codec + " -preset superfast" + keyFrameArg;
  145. if (state.VideoRequest.VideoBitRate.HasValue)
  146. {
  147. // Make sure we don't request a bitrate higher than the source
  148. var currentBitrate = state.VideoStream == null ? state.VideoRequest.VideoBitRate.Value : state.VideoStream.BitRate ?? state.VideoRequest.VideoBitRate.Value;
  149. var bitrate = Math.Min(currentBitrate, state.VideoRequest.VideoBitRate.Value);
  150. args += string.Format(" -b:v {0}", bitrate);
  151. }
  152. // Add resolution params, if specified
  153. if (state.VideoRequest.Width.HasValue || state.VideoRequest.Height.HasValue || state.VideoRequest.MaxHeight.HasValue || state.VideoRequest.MaxWidth.HasValue)
  154. {
  155. args += GetOutputSizeParam(state, codec, performSubtitleConversion);
  156. }
  157. // Get the output framerate based on the FrameRate param
  158. var framerate = state.VideoRequest.Framerate ?? 0;
  159. // We have to supply a framerate for hls, so if it's null, account for that here
  160. if (framerate.Equals(0))
  161. {
  162. framerate = state.VideoStream.AverageFrameRate ?? 0;
  163. }
  164. if (framerate.Equals(0))
  165. {
  166. framerate = state.VideoStream.RealFrameRate ?? 0;
  167. }
  168. if (framerate.Equals(0))
  169. {
  170. framerate = 23.976;
  171. }
  172. framerate = Math.Round(framerate);
  173. args += string.Format(" -r {0}", framerate);
  174. args += " -vsync vfr";
  175. if (!string.IsNullOrEmpty(state.VideoRequest.Profile))
  176. {
  177. args += " -profile:v " + state.VideoRequest.Profile;
  178. }
  179. if (!string.IsNullOrEmpty(state.VideoRequest.Level))
  180. {
  181. args += " -level " + state.VideoRequest.Level;
  182. }
  183. if (state.SubtitleStream != null)
  184. {
  185. // This is for internal graphical subs
  186. if (!state.SubtitleStream.IsExternal && (state.SubtitleStream.Codec.IndexOf("pgs", StringComparison.OrdinalIgnoreCase) != -1 || state.SubtitleStream.Codec.IndexOf("dvd", StringComparison.OrdinalIgnoreCase) != -1))
  187. {
  188. args += GetInternalGraphicalSubtitleParam(state, codec);
  189. }
  190. }
  191. return args;
  192. }
  193. /// <summary>
  194. /// Gets the segment file extension.
  195. /// </summary>
  196. /// <param name="state">The state.</param>
  197. /// <returns>System.String.</returns>
  198. protected override string GetSegmentFileExtension(StreamState state)
  199. {
  200. return ".ts";
  201. }
  202. }
  203. }