VideoHlsService.cs 7.8 KB

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