VideoHlsService.cs 7.8 KB

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