VideoHlsService.cs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Controller.Channels;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Dlna;
  5. using MediaBrowser.Controller.Library;
  6. using MediaBrowser.Controller.LiveTv;
  7. using MediaBrowser.Controller.MediaEncoding;
  8. using MediaBrowser.Model.IO;
  9. using ServiceStack;
  10. using System;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Threading;
  14. using System.Threading.Tasks;
  15. namespace MediaBrowser.Api.Playback.Hls
  16. {
  17. /// <summary>
  18. /// Class GetHlsVideoStream
  19. /// </summary>
  20. [Route("/Videos/{Id}/stream.m3u8", "GET")]
  21. [Api(Description = "Gets a video stream using HTTP live streaming.")]
  22. public class GetHlsVideoStream : VideoStreamRequest
  23. {
  24. [ApiMember(Name = "BaselineStreamAudioBitRate", Description = "Optional. Specify the audio bitrate for the baseline stream.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
  25. public int? BaselineStreamAudioBitRate { get; set; }
  26. [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")]
  27. public bool AppendBaselineStream { get; set; }
  28. [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")]
  29. public int TimeStampOffsetMs { get; set; }
  30. }
  31. [Route("/Videos/{Id}/live.m3u8", "GET")]
  32. [Api(Description = "Gets a video stream using HTTP live streaming.")]
  33. public class GetLiveHlsStream : VideoStreamRequest
  34. {
  35. }
  36. /// <summary>
  37. /// Class GetHlsVideoSegment
  38. /// </summary>
  39. [Route("/Videos/{Id}/hls/{PlaylistId}/{SegmentId}.ts", "GET")]
  40. [Api(Description = "Gets an Http live streaming segment file. Internal use only.")]
  41. public class GetHlsVideoSegment : VideoStreamRequest
  42. {
  43. public string PlaylistId { get; set; }
  44. /// <summary>
  45. /// Gets or sets the segment id.
  46. /// </summary>
  47. /// <value>The segment id.</value>
  48. public string SegmentId { get; set; }
  49. }
  50. /// <summary>
  51. /// Class VideoHlsService
  52. /// </summary>
  53. public class VideoHlsService : BaseHlsService
  54. {
  55. public VideoHlsService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, ILiveTvManager liveTvManager, IDlnaManager dlnaManager, IChannelManager channelManager, ISubtitleEncoder subtitleEncoder) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, liveTvManager, dlnaManager, channelManager, subtitleEncoder)
  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. protected override bool SupportsThrottling
  71. {
  72. get
  73. {
  74. return false;
  75. }
  76. }
  77. /// <summary>
  78. /// Called when [begin request].
  79. /// </summary>
  80. /// <param name="playlistId">The playlist id.</param>
  81. protected void OnBeginRequest(string playlistId)
  82. {
  83. var normalizedPlaylistId = playlistId.Replace("-low", string.Empty);
  84. foreach (var playlist in Directory.EnumerateFiles(ServerConfigurationManager.ApplicationPaths.TranscodingTempPath, "*.m3u8")
  85. .Where(i => i.IndexOf(normalizedPlaylistId, StringComparison.OrdinalIgnoreCase) != -1)
  86. .ToList())
  87. {
  88. ExtendPlaylistTimer(playlist);
  89. }
  90. }
  91. private async void ExtendPlaylistTimer(string playlist)
  92. {
  93. ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlist, TranscodingJobType.Hls);
  94. await Task.Delay(20000).ConfigureAwait(false);
  95. ApiEntryPoint.Instance.OnTranscodeEndRequest(playlist, TranscodingJobType.Hls);
  96. }
  97. /// <summary>
  98. /// Gets the specified request.
  99. /// </summary>
  100. /// <param name="request">The request.</param>
  101. /// <returns>System.Object.</returns>
  102. public object Get(GetHlsVideoStream request)
  103. {
  104. return ProcessRequest(request, false);
  105. }
  106. public object Get(GetLiveHlsStream request)
  107. {
  108. return ProcessRequest(request, true);
  109. }
  110. /// <summary>
  111. /// Gets the audio arguments.
  112. /// </summary>
  113. /// <param name="state">The state.</param>
  114. /// <returns>System.String.</returns>
  115. protected override string GetAudioArguments(StreamState state)
  116. {
  117. var codec = state.OutputAudioCodec;
  118. if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
  119. {
  120. return "-codec:a:0 copy";
  121. }
  122. var args = "-codec:a:0 " + codec;
  123. var channels = state.OutputAudioChannels;
  124. if (channels.HasValue)
  125. {
  126. args += " -ac " + channels.Value;
  127. }
  128. var bitrate = state.OutputAudioBitrate;
  129. if (bitrate.HasValue)
  130. {
  131. args += " -ab " + bitrate.Value.ToString(UsCulture);
  132. }
  133. args += " " + GetAudioFilterParam(state, true);
  134. return args;
  135. }
  136. /// <summary>
  137. /// Gets the video arguments.
  138. /// </summary>
  139. /// <param name="state">The state.</param>
  140. /// <returns>System.String.</returns>
  141. protected override string GetVideoArguments(StreamState state)
  142. {
  143. var codec = state.OutputVideoCodec;
  144. // See if we can save come cpu cycles by avoiding encoding
  145. if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
  146. {
  147. // TOOD: Switch to -bsf dump_extra?
  148. return IsH264(state.VideoStream) ? "-codec:v:0 copy -bsf h264_mp4toannexb" : "-codec:v:0 copy";
  149. }
  150. var keyFrameArg = string.Format(" -force_key_frames expr:gte(t,n_forced*{0})",
  151. state.SegmentLength.ToString(UsCulture));
  152. var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream;
  153. var args = "-codec:v:0 " + codec + " " + GetVideoQualityParam(state, "libx264", true) + keyFrameArg;
  154. // Add resolution params, if specified
  155. if (!hasGraphicalSubs)
  156. {
  157. args += GetOutputSizeParam(state, codec);
  158. }
  159. // This is for internal graphical subs
  160. if (hasGraphicalSubs)
  161. {
  162. args += GetGraphicalSubtitleParam(state, codec);
  163. }
  164. return args;
  165. }
  166. /// <summary>
  167. /// Gets the segment file extension.
  168. /// </summary>
  169. /// <param name="state">The state.</param>
  170. /// <returns>System.String.</returns>
  171. protected override string GetSegmentFileExtension(StreamState state)
  172. {
  173. return ".ts";
  174. }
  175. }
  176. }