VideoHlsService.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.Dto;
  4. using MediaBrowser.Controller.Library;
  5. using MediaBrowser.Controller.LiveTv;
  6. using MediaBrowser.Controller.MediaInfo;
  7. using MediaBrowser.Controller.Persistence;
  8. using MediaBrowser.Model.IO;
  9. using ServiceStack;
  10. using System;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Threading.Tasks;
  14. namespace MediaBrowser.Api.Playback.Hls
  15. {
  16. /// <summary>
  17. /// Class GetHlsVideoStream
  18. /// </summary>
  19. [Route("/Videos/{Id}/stream.m3u8", "GET")]
  20. [Api(Description = "Gets a video stream using HTTP live streaming.")]
  21. public class GetHlsVideoStream : VideoStreamRequest
  22. {
  23. [ApiMember(Name = "BaselineStreamAudioBitRate", Description = "Optional. Specify the audio bitrate for the baseline stream.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
  24. public int? BaselineStreamAudioBitRate { get; set; }
  25. [ApiMember(Name = "AppendBaselineStream", Description = "Optional. Whether or not to include a baseline audio-only stream in the master playlist.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
  26. public bool AppendBaselineStream { get; set; }
  27. [ApiMember(Name = "TimeStampOffsetMs", Description = "Optional. Alter the timestamps in the playlist by a given amount, in ms. Default is 1000.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
  28. public int TimeStampOffsetMs { get; set; }
  29. }
  30. /// <summary>
  31. /// Class GetHlsVideoSegment
  32. /// </summary>
  33. [Route("/Videos/{Id}/hls/{PlaylistId}/{SegmentId}.ts", "GET")]
  34. [Api(Description = "Gets an Http live streaming segment file. Internal use only.")]
  35. public class GetHlsVideoSegment : VideoStreamRequest
  36. {
  37. /// <summary>
  38. /// Gets or sets the id.
  39. /// </summary>
  40. /// <value>The id.</value>
  41. public string Id { get; set; }
  42. public string PlaylistId { get; set; }
  43. /// <summary>
  44. /// Gets or sets the segment id.
  45. /// </summary>
  46. /// <value>The segment id.</value>
  47. public string SegmentId { get; set; }
  48. }
  49. /// <summary>
  50. /// Class VideoHlsService
  51. /// </summary>
  52. public class VideoHlsService : BaseHlsService
  53. {
  54. public VideoHlsService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IDtoService dtoService, IFileSystem fileSystem, IItemRepository itemRepository, ILiveTvManager liveTvManager)
  55. : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, dtoService, fileSystem, itemRepository, liveTvManager)
  56. {
  57. }
  58. /// <summary>
  59. /// Gets the specified request.
  60. /// </summary>
  61. /// <param name="request">The request.</param>
  62. /// <returns>System.Object.</returns>
  63. public object Get(GetHlsVideoSegment request)
  64. {
  65. var file = request.SegmentId + Path.GetExtension(Request.PathInfo);
  66. file = Path.Combine(ServerConfigurationManager.ApplicationPaths.TranscodingTempPath, file);
  67. OnBeginRequest(request.PlaylistId);
  68. return ResultFactory.GetStaticFileResult(Request, file);
  69. }
  70. /// <summary>
  71. /// Called when [begin request].
  72. /// </summary>
  73. /// <param name="playlistId">The playlist id.</param>
  74. protected void OnBeginRequest(string playlistId)
  75. {
  76. var normalizedPlaylistId = playlistId.Replace("-low", string.Empty);
  77. foreach (var playlist in Directory.EnumerateFiles(ServerConfigurationManager.ApplicationPaths.TranscodingTempPath, "*.m3u8")
  78. .Where(i => i.IndexOf(normalizedPlaylistId, StringComparison.OrdinalIgnoreCase) != -1)
  79. .ToList())
  80. {
  81. ExtendPlaylistTimer(playlist);
  82. }
  83. }
  84. private async void ExtendPlaylistTimer(string playlist)
  85. {
  86. ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlist, TranscodingJobType.Hls);
  87. await Task.Delay(20000).ConfigureAwait(false);
  88. ApiEntryPoint.Instance.OnTranscodeEndRequest(playlist, TranscodingJobType.Hls);
  89. }
  90. /// <summary>
  91. /// Gets the specified request.
  92. /// </summary>
  93. /// <param name="request">The request.</param>
  94. /// <returns>System.Object.</returns>
  95. public object Get(GetHlsVideoStream request)
  96. {
  97. return ProcessRequest(request);
  98. }
  99. /// <summary>
  100. /// Gets the audio arguments.
  101. /// </summary>
  102. /// <param name="state">The state.</param>
  103. /// <returns>System.String.</returns>
  104. protected override string GetAudioArguments(StreamState state)
  105. {
  106. var codec = GetAudioCodec(state.Request);
  107. if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
  108. {
  109. return "-codec:a:0 copy";
  110. }
  111. var args = "-codec:a:0 " + codec;
  112. if (state.AudioStream != null)
  113. {
  114. var channels = GetNumAudioChannelsParam(state.Request, state.AudioStream);
  115. if (channels.HasValue)
  116. {
  117. args += " -ac " + channels.Value;
  118. }
  119. var bitrate = GetAudioBitrateParam(state);
  120. if (bitrate.HasValue)
  121. {
  122. args += " -ab " + bitrate.Value.ToString(UsCulture);
  123. }
  124. args += " " + GetAudioFilterParam(state, true);
  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,.1),gte(t,prev_forced_t+5))";
  144. var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsExternal &&
  145. (state.SubtitleStream.Codec.IndexOf("pgs", StringComparison.OrdinalIgnoreCase) != -1 ||
  146. state.SubtitleStream.Codec.IndexOf("dvd", StringComparison.OrdinalIgnoreCase) != -1);
  147. var args = "-codec:v:0 " + codec + " " + GetVideoQualityParam(state, "libx264") + keyFrameArg;
  148. var bitrate = GetVideoBitrateParam(state);
  149. if (bitrate.HasValue)
  150. {
  151. args += string.Format(" -b:v {0} -maxrate ({0}*.80) -bufsize {0}", bitrate.Value.ToString(UsCulture));
  152. }
  153. // Add resolution params, if specified
  154. if (!hasGraphicalSubs)
  155. {
  156. if (state.VideoRequest.Width.HasValue || state.VideoRequest.Height.HasValue || state.VideoRequest.MaxHeight.HasValue || state.VideoRequest.MaxWidth.HasValue)
  157. {
  158. args += GetOutputSizeParam(state, codec, performSubtitleConversion);
  159. }
  160. }
  161. var framerate = GetFramerateParam(state);
  162. if (framerate.HasValue)
  163. {
  164. args += string.Format(" -r {0}", framerate.Value.ToString(UsCulture));
  165. }
  166. if (!string.IsNullOrEmpty(state.VideoSync))
  167. {
  168. args += " -vsync " + state.VideoSync;
  169. }
  170. if (!string.IsNullOrEmpty(state.VideoRequest.Profile))
  171. {
  172. args += " -profile:v " + state.VideoRequest.Profile;
  173. }
  174. if (!string.IsNullOrEmpty(state.VideoRequest.Level))
  175. {
  176. args += " -level " + state.VideoRequest.Level;
  177. }
  178. // This is for internal graphical subs
  179. if (hasGraphicalSubs)
  180. {
  181. args += GetInternalGraphicalSubtitleParam(state, codec);
  182. }
  183. return args;
  184. }
  185. /// <summary>
  186. /// Gets the segment file extension.
  187. /// </summary>
  188. /// <param name="state">The state.</param>
  189. /// <returns>System.String.</returns>
  190. protected override string GetSegmentFileExtension(StreamState state)
  191. {
  192. return ".ts";
  193. }
  194. }
  195. }