VideoHlsService.cs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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.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. [Route("/Videos/{Id}/live.m3u8", "GET")]
  31. [Api(Description = "Gets a video stream using HTTP live streaming.")]
  32. public class GetLiveHlsStream : VideoStreamRequest
  33. {
  34. }
  35. /// <summary>
  36. /// Class GetHlsVideoSegment
  37. /// </summary>
  38. [Route("/Videos/{Id}/hls/{PlaylistId}/{SegmentId}.ts", "GET")]
  39. [Api(Description = "Gets an Http live streaming segment file. Internal use only.")]
  40. public class GetHlsVideoSegment : VideoStreamRequest
  41. {
  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, IFileSystem fileSystem, ILiveTvManager liveTvManager, IDlnaManager dlnaManager, IChannelManager channelManager, ISubtitleEncoder subtitleEncoder) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, liveTvManager, dlnaManager, channelManager, subtitleEncoder)
  55. {
  56. }
  57. /// <summary>
  58. /// Gets the specified request.
  59. /// </summary>
  60. /// <param name="request">The request.</param>
  61. /// <returns>System.Object.</returns>
  62. public object Get(GetHlsVideoSegment request)
  63. {
  64. var file = request.SegmentId + Path.GetExtension(Request.PathInfo);
  65. file = Path.Combine(ServerConfigurationManager.ApplicationPaths.TranscodingTempPath, file);
  66. OnBeginRequest(request.PlaylistId);
  67. return ResultFactory.GetStaticFileResult(Request, file);
  68. }
  69. /// <summary>
  70. /// Called when [begin request].
  71. /// </summary>
  72. /// <param name="playlistId">The playlist id.</param>
  73. protected void OnBeginRequest(string playlistId)
  74. {
  75. var normalizedPlaylistId = playlistId.Replace("-low", string.Empty);
  76. foreach (var playlist in Directory.EnumerateFiles(ServerConfigurationManager.ApplicationPaths.TranscodingTempPath, "*.m3u8")
  77. .Where(i => i.IndexOf(normalizedPlaylistId, StringComparison.OrdinalIgnoreCase) != -1)
  78. .ToList())
  79. {
  80. ExtendPlaylistTimer(playlist);
  81. }
  82. }
  83. private async void ExtendPlaylistTimer(string playlist)
  84. {
  85. ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlist, TranscodingJobType.Hls);
  86. await Task.Delay(20000).ConfigureAwait(false);
  87. ApiEntryPoint.Instance.OnTranscodeEndRequest(playlist, TranscodingJobType.Hls);
  88. }
  89. /// <summary>
  90. /// Gets the specified request.
  91. /// </summary>
  92. /// <param name="request">The request.</param>
  93. /// <returns>System.Object.</returns>
  94. public object Get(GetHlsVideoStream request)
  95. {
  96. return ProcessRequest(request, false);
  97. }
  98. public object Get(GetLiveHlsStream request)
  99. {
  100. return ProcessRequest(request, true);
  101. }
  102. /// <summary>
  103. /// Gets the audio arguments.
  104. /// </summary>
  105. /// <param name="state">The state.</param>
  106. /// <returns>System.String.</returns>
  107. protected override string GetAudioArguments(StreamState state)
  108. {
  109. var codec = state.OutputAudioCodec;
  110. if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
  111. {
  112. return "-codec:a:0 copy";
  113. }
  114. var args = "-codec:a:0 " + codec;
  115. var channels = state.OutputAudioChannels;
  116. if (channels.HasValue)
  117. {
  118. args += " -ac " + channels.Value;
  119. }
  120. var bitrate = state.OutputAudioBitrate;
  121. if (bitrate.HasValue)
  122. {
  123. args += " -ab " + bitrate.Value.ToString(UsCulture);
  124. }
  125. args += " " + GetAudioFilterParam(state, true);
  126. return args;
  127. }
  128. /// <summary>
  129. /// Gets the video arguments.
  130. /// </summary>
  131. /// <param name="state">The state.</param>
  132. /// <returns>System.String.</returns>
  133. protected override string GetVideoArguments(StreamState state)
  134. {
  135. var codec = state.OutputVideoCodec;
  136. // See if we can save come cpu cycles by avoiding encoding
  137. if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
  138. {
  139. // TOOD: Switch to -bsf dump_extra?
  140. return IsH264(state.VideoStream) ? "-codec:v:0 copy -bsf h264_mp4toannexb" : "-codec:v:0 copy";
  141. }
  142. var keyFrameArg = string.Format(" -force_key_frames expr:gte(t,n_forced*{0})",
  143. state.SegmentLength.ToString(UsCulture));
  144. var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream;
  145. var args = "-codec:v:0 " + codec + " " + GetVideoQualityParam(state, "libx264", true) + keyFrameArg;
  146. // Add resolution params, if specified
  147. if (!hasGraphicalSubs)
  148. {
  149. args += GetOutputSizeParam(state, codec);
  150. }
  151. // This is for internal graphical subs
  152. if (hasGraphicalSubs)
  153. {
  154. args += GetGraphicalSubtitleParam(state, codec);
  155. }
  156. return args;
  157. }
  158. /// <summary>
  159. /// Gets the segment file extension.
  160. /// </summary>
  161. /// <param name="state">The state.</param>
  162. /// <returns>System.String.</returns>
  163. protected override string GetSegmentFileExtension(StreamState state)
  164. {
  165. return ".ts";
  166. }
  167. }
  168. }