VideoHlsService.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. using MediaBrowser.Common.MediaInfo;
  2. using MediaBrowser.Controller;
  3. using MediaBrowser.Controller.Dto;
  4. using MediaBrowser.Controller.Library;
  5. using MediaBrowser.Model.IO;
  6. using ServiceStack.ServiceHost;
  7. using System;
  8. namespace MediaBrowser.Api.Playback.Hls
  9. {
  10. /// <summary>
  11. /// Class GetHlsVideoStream
  12. /// </summary>
  13. [Route("/Videos/{Id}/stream.m3u8", "GET")]
  14. [Api(Description = "Gets a video stream using HTTP live streaming.")]
  15. public class GetHlsVideoStream : VideoStreamRequest
  16. {
  17. [ApiMember(Name = "BaselineStreamAudioBitRate", Description = "Optional. Specify the audio bitrate for the baseline stream.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
  18. public int? BaselineStreamAudioBitRate { get; set; }
  19. [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")]
  20. public bool AppendBaselineStream { get; set; }
  21. [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")]
  22. public int TimeStampOffsetMs { get; set; }
  23. public GetHlsVideoStream()
  24. {
  25. TimeStampOffsetMs = 1000;
  26. }
  27. }
  28. /// <summary>
  29. /// Class VideoHlsService
  30. /// </summary>
  31. public class VideoHlsService : BaseHlsService
  32. {
  33. /// <summary>
  34. /// Initializes a new instance of the <see cref="BaseStreamingService" /> class.
  35. /// </summary>
  36. /// <param name="appPaths">The app paths.</param>
  37. /// <param name="userManager">The user manager.</param>
  38. /// <param name="libraryManager">The library manager.</param>
  39. /// <param name="isoManager">The iso manager.</param>
  40. /// <param name="mediaEncoder">The media encoder.</param>
  41. /// <param name="dtoService">The dto service.</param>
  42. public VideoHlsService(IServerApplicationPaths appPaths, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IDtoService dtoService)
  43. : base(appPaths, userManager, libraryManager, isoManager, mediaEncoder, dtoService)
  44. {
  45. }
  46. /// <summary>
  47. /// Gets the specified request.
  48. /// </summary>
  49. /// <param name="request">The request.</param>
  50. /// <returns>System.Object.</returns>
  51. public object Get(GetHlsVideoStream request)
  52. {
  53. return ProcessRequest(request);
  54. }
  55. /// <summary>
  56. /// Gets the audio arguments.
  57. /// </summary>
  58. /// <param name="state">The state.</param>
  59. /// <returns>System.String.</returns>
  60. protected override string GetAudioArguments(StreamState state)
  61. {
  62. var codec = GetAudioCodec(state.Request);
  63. if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
  64. {
  65. return "-codec:a:0 copy";
  66. }
  67. var args = "-codec:a:0 " + codec;
  68. if (state.AudioStream != null)
  69. {
  70. var channels = GetNumAudioChannelsParam(state.Request, state.AudioStream);
  71. if (channels.HasValue)
  72. {
  73. args += " -ac " + channels.Value;
  74. }
  75. if (state.Request.AudioSampleRate.HasValue)
  76. {
  77. args += " -ar " + state.Request.AudioSampleRate.Value;
  78. }
  79. var bitrate = GetAudioBitrateParam(state);
  80. if (bitrate.HasValue)
  81. {
  82. args += " -ab " + bitrate.Value.ToString(UsCulture);
  83. }
  84. var volParam = string.Empty;
  85. // Boost volume to 200% when downsampling from 6ch to 2ch
  86. if (channels.HasValue && channels.Value <= 2 && state.AudioStream.Channels.HasValue && state.AudioStream.Channels.Value > 5)
  87. {
  88. volParam = ",volume=2.000000";
  89. }
  90. args += string.Format(" -af \"aresample=async=1000{0}\"", volParam);
  91. return args;
  92. }
  93. return args;
  94. }
  95. /// <summary>
  96. /// Gets the video arguments.
  97. /// </summary>
  98. /// <param name="state">The state.</param>
  99. /// <param name="performSubtitleConversion">if set to <c>true</c> [perform subtitle conversion].</param>
  100. /// <returns>System.String.</returns>
  101. protected override string GetVideoArguments(StreamState state, bool performSubtitleConversion)
  102. {
  103. var codec = GetVideoCodec(state.VideoRequest);
  104. // See if we can save come cpu cycles by avoiding encoding
  105. if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
  106. {
  107. return IsH264(state.VideoStream) ? "-codec:v:0 copy -bsf h264_mp4toannexb" : "-codec:v:0 copy";
  108. }
  109. const string keyFrameArg = " -force_key_frames expr:if(isnan(prev_forced_t),gte(t,.1),gte(t,prev_forced_t+5))";
  110. var args = "-codec:v:0 " + codec + " -preset superfast" + keyFrameArg;
  111. var bitrate = GetVideoBitrateParam(state);
  112. if (bitrate.HasValue)
  113. {
  114. args += string.Format(" -b:v {0} -maxrate {0} -minrate {0} -bufsize ({0}/10)", bitrate.Value.ToString(UsCulture));
  115. }
  116. // Add resolution params, if specified
  117. if (state.VideoRequest.Width.HasValue || state.VideoRequest.Height.HasValue || state.VideoRequest.MaxHeight.HasValue || state.VideoRequest.MaxWidth.HasValue)
  118. {
  119. args += GetOutputSizeParam(state, codec, performSubtitleConversion);
  120. }
  121. // Get the output framerate based on the FrameRate param
  122. var framerate = state.VideoRequest.Framerate ?? 0;
  123. // We have to supply a framerate for hls, so if it's null, account for that here
  124. if (state.VideoStream != null)
  125. {
  126. if (framerate.Equals(0))
  127. {
  128. framerate = state.VideoStream.AverageFrameRate ?? 0;
  129. }
  130. if (framerate.Equals(0))
  131. {
  132. framerate = state.VideoStream.RealFrameRate ?? 0;
  133. }
  134. }
  135. if (framerate.Equals(0))
  136. {
  137. framerate = 23.976;
  138. }
  139. framerate = Math.Round(framerate);
  140. args += string.Format(" -r {0}", framerate);
  141. args += " -vsync vfr";
  142. if (!string.IsNullOrEmpty(state.VideoRequest.Profile))
  143. {
  144. args += " -profile:v " + state.VideoRequest.Profile;
  145. }
  146. if (!string.IsNullOrEmpty(state.VideoRequest.Level))
  147. {
  148. args += " -level " + state.VideoRequest.Level;
  149. }
  150. if (state.SubtitleStream != null)
  151. {
  152. // This is for internal graphical subs
  153. if (!state.SubtitleStream.IsExternal && (state.SubtitleStream.Codec.IndexOf("pgs", StringComparison.OrdinalIgnoreCase) != -1 || state.SubtitleStream.Codec.IndexOf("dvd", StringComparison.OrdinalIgnoreCase) != -1))
  154. {
  155. args += GetInternalGraphicalSubtitleParam(state, codec);
  156. }
  157. }
  158. return args;
  159. }
  160. /// <summary>
  161. /// Gets the segment file extension.
  162. /// </summary>
  163. /// <param name="state">The state.</param>
  164. /// <returns>System.String.</returns>
  165. protected override string GetSegmentFileExtension(StreamState state)
  166. {
  167. return ".ts";
  168. }
  169. }
  170. }