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