BaseHlsService.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Common.MediaInfo;
  4. using MediaBrowser.Common.Net;
  5. using MediaBrowser.Controller.Configuration;
  6. using MediaBrowser.Controller.Dto;
  7. using MediaBrowser.Controller.Library;
  8. using MediaBrowser.Controller.Persistence;
  9. using MediaBrowser.Model.Dto;
  10. using MediaBrowser.Model.IO;
  11. using System;
  12. using System.Collections.Generic;
  13. using System.IO;
  14. using System.Text;
  15. using System.Threading.Tasks;
  16. namespace MediaBrowser.Api.Playback.Hls
  17. {
  18. /// <summary>
  19. /// Class BaseHlsService
  20. /// </summary>
  21. public abstract class BaseHlsService : BaseStreamingService
  22. {
  23. protected BaseHlsService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IDtoService dtoService, IFileSystem fileSystem, IItemRepository itemRepository)
  24. : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, dtoService, fileSystem, itemRepository)
  25. {
  26. }
  27. protected override string GetOutputFilePath(StreamState state)
  28. {
  29. var folder = ServerConfigurationManager.ApplicationPaths.EncodedMediaCachePath;
  30. var outputFileExtension = GetOutputFileExtension(state);
  31. return Path.Combine(folder, GetCommandLineArguments("dummy\\dummy", state, false).GetMD5() + (outputFileExtension ?? string.Empty).ToLower());
  32. }
  33. /// <summary>
  34. /// Gets the audio arguments.
  35. /// </summary>
  36. /// <param name="state">The state.</param>
  37. /// <returns>System.String.</returns>
  38. protected abstract string GetAudioArguments(StreamState state);
  39. /// <summary>
  40. /// Gets the video arguments.
  41. /// </summary>
  42. /// <param name="state">The state.</param>
  43. /// <param name="performSubtitleConversion">if set to <c>true</c> [perform subtitle conversion].</param>
  44. /// <returns>System.String.</returns>
  45. protected abstract string GetVideoArguments(StreamState state, bool performSubtitleConversion);
  46. /// <summary>
  47. /// Gets the segment file extension.
  48. /// </summary>
  49. /// <param name="state">The state.</param>
  50. /// <returns>System.String.</returns>
  51. protected abstract string GetSegmentFileExtension(StreamState state);
  52. /// <summary>
  53. /// Gets the type of the transcoding job.
  54. /// </summary>
  55. /// <value>The type of the transcoding job.</value>
  56. protected override TranscodingJobType TranscodingJobType
  57. {
  58. get { return TranscodingJobType.Hls; }
  59. }
  60. /// <summary>
  61. /// Processes the request.
  62. /// </summary>
  63. /// <param name="request">The request.</param>
  64. /// <returns>System.Object.</returns>
  65. protected object ProcessRequest(StreamRequest request)
  66. {
  67. var state = GetState(request);
  68. return ProcessRequestAsync(state).Result;
  69. }
  70. /// <summary>
  71. /// Processes the request async.
  72. /// </summary>
  73. /// <param name="state">The state.</param>
  74. /// <returns>Task{System.Object}.</returns>
  75. public async Task<object> ProcessRequestAsync(StreamState state)
  76. {
  77. if (!state.VideoRequest.VideoBitRate.HasValue && (!state.VideoRequest.VideoCodec.HasValue || state.VideoRequest.VideoCodec.Value != VideoCodecs.Copy))
  78. {
  79. throw new ArgumentException("A video bitrate is required");
  80. }
  81. if (!state.Request.AudioBitRate.HasValue && (!state.Request.AudioCodec.HasValue || state.Request.AudioCodec.Value != AudioCodecs.Copy))
  82. {
  83. throw new ArgumentException("An audio bitrate is required");
  84. }
  85. var playlist = GetOutputFilePath(state);
  86. var isPlaylistNewlyCreated = false;
  87. // If the playlist doesn't already exist, startup ffmpeg
  88. if (!File.Exists(playlist))
  89. {
  90. isPlaylistNewlyCreated = true;
  91. await StartFfMpeg(state, playlist).ConfigureAwait(false);
  92. }
  93. else
  94. {
  95. ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlist, TranscodingJobType.Hls);
  96. }
  97. if (isPlaylistNewlyCreated)
  98. {
  99. await WaitForMinimumSegmentCount(playlist, 3).ConfigureAwait(false);
  100. }
  101. int audioBitrate;
  102. int videoBitrate;
  103. GetPlaylistBitrates(state, out audioBitrate, out videoBitrate);
  104. var appendBaselineStream = false;
  105. var baselineStreamBitrate = 64000;
  106. var hlsVideoRequest = state.VideoRequest as GetHlsVideoStream;
  107. if (hlsVideoRequest != null)
  108. {
  109. appendBaselineStream = hlsVideoRequest.AppendBaselineStream;
  110. baselineStreamBitrate = hlsVideoRequest.BaselineStreamAudioBitRate ?? baselineStreamBitrate;
  111. }
  112. var playlistText = GetMasterPlaylistFileText(playlist, videoBitrate + audioBitrate, appendBaselineStream, baselineStreamBitrate);
  113. try
  114. {
  115. return ResultFactory.GetResult(playlistText, MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary<string, string>());
  116. }
  117. finally
  118. {
  119. ApiEntryPoint.Instance.OnTranscodeEndRequest(playlist, TranscodingJobType.Hls);
  120. }
  121. }
  122. /// <summary>
  123. /// Gets the playlist bitrates.
  124. /// </summary>
  125. /// <param name="state">The state.</param>
  126. /// <param name="audioBitrate">The audio bitrate.</param>
  127. /// <param name="videoBitrate">The video bitrate.</param>
  128. private void GetPlaylistBitrates(StreamState state, out int audioBitrate, out int videoBitrate)
  129. {
  130. var audioBitrateParam = GetAudioBitrateParam(state);
  131. var videoBitrateParam = GetVideoBitrateParam(state);
  132. if (!audioBitrateParam.HasValue)
  133. {
  134. if (state.AudioStream != null)
  135. {
  136. audioBitrateParam = state.AudioStream.BitRate;
  137. }
  138. }
  139. if (!videoBitrateParam.HasValue)
  140. {
  141. if (state.VideoStream != null)
  142. {
  143. videoBitrateParam = state.VideoStream.BitRate;
  144. }
  145. }
  146. audioBitrate = audioBitrateParam ?? 0;
  147. videoBitrate = videoBitrateParam ?? 0;
  148. }
  149. private string GetMasterPlaylistFileText(string firstPlaylist, int bitrate, bool includeBaselineStream, int baselineStreamBitrate)
  150. {
  151. var builder = new StringBuilder();
  152. builder.AppendLine("#EXTM3U");
  153. // Pad a little to satisfy the apple hls validator
  154. var paddedBitrate = Convert.ToInt32(bitrate * 1.05);
  155. // Main stream
  156. builder.AppendLine("#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=" + paddedBitrate.ToString(UsCulture));
  157. var playlistUrl = "hls/" + Path.GetFileName(firstPlaylist).Replace(".m3u8", "/stream.m3u8");
  158. builder.AppendLine(playlistUrl);
  159. // Low bitrate stream
  160. if (includeBaselineStream)
  161. {
  162. builder.AppendLine("#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=" + baselineStreamBitrate.ToString(UsCulture));
  163. playlistUrl = "hls/" + Path.GetFileName(firstPlaylist).Replace(".m3u8", "-low/stream.m3u8");
  164. builder.AppendLine(playlistUrl);
  165. }
  166. return builder.ToString();
  167. }
  168. private async Task WaitForMinimumSegmentCount(string playlist, int segmentCount)
  169. {
  170. while (true)
  171. {
  172. string fileText;
  173. // Need to use FileShare.ReadWrite because we're reading the file at the same time it's being written
  174. using (var fileStream = FileSystem.GetFileStream(playlist, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  175. {
  176. using (var reader = new StreamReader(fileStream))
  177. {
  178. fileText = await reader.ReadToEndAsync().ConfigureAwait(false);
  179. }
  180. }
  181. if (CountStringOccurrences(fileText, "#EXTINF:") >= segmentCount)
  182. {
  183. break;
  184. }
  185. await Task.Delay(25).ConfigureAwait(false);
  186. }
  187. }
  188. /// <summary>
  189. /// Count occurrences of strings.
  190. /// </summary>
  191. /// <param name="text">The text.</param>
  192. /// <param name="pattern">The pattern.</param>
  193. /// <returns>System.Int32.</returns>
  194. private static int CountStringOccurrences(string text, string pattern)
  195. {
  196. // Loop through all instances of the string 'text'.
  197. var count = 0;
  198. var i = 0;
  199. while ((i = text.IndexOf(pattern, i, StringComparison.OrdinalIgnoreCase)) != -1)
  200. {
  201. i += pattern.Length;
  202. count++;
  203. }
  204. return count;
  205. }
  206. /// <summary>
  207. /// Gets the command line arguments.
  208. /// </summary>
  209. /// <param name="outputPath">The output path.</param>
  210. /// <param name="state">The state.</param>
  211. /// <param name="performSubtitleConversions">if set to <c>true</c> [perform subtitle conversions].</param>
  212. /// <returns>System.String.</returns>
  213. protected override string GetCommandLineArguments(string outputPath, StreamState state, bool performSubtitleConversions)
  214. {
  215. var probeSize = GetProbeSizeArgument(state.MediaPath, state.IsInputVideo, state.VideoType, state.IsoType);
  216. var hlsVideoRequest = state.VideoRequest as GetHlsVideoStream;
  217. var itsOffsetMs = hlsVideoRequest == null
  218. ? 0
  219. : ((GetHlsVideoStream)state.VideoRequest).TimeStampOffsetMs;
  220. var itsOffset = itsOffsetMs == 0 ? string.Empty : string.Format("-itsoffset {0} ", TimeSpan.FromMilliseconds(itsOffsetMs).TotalSeconds);
  221. var threads = GetNumberOfThreads();
  222. var args = string.Format("{0}{1} {2} {3} -i {4}{5} -threads {6} {7} {8} -sc_threshold 0 {9} -hls_time 10 -start_number 0 -hls_list_size 1440 \"{10}\"",
  223. itsOffset,
  224. probeSize,
  225. GetUserAgentParam(state.MediaPath),
  226. GetFastSeekCommandLineParameter(state.Request),
  227. GetInputArgument(state),
  228. GetSlowSeekCommandLineParameter(state.Request),
  229. threads,
  230. GetMapArgs(state),
  231. GetVideoArguments(state, performSubtitleConversions),
  232. GetAudioArguments(state),
  233. outputPath
  234. ).Trim();
  235. if (hlsVideoRequest != null)
  236. {
  237. if (hlsVideoRequest.AppendBaselineStream && state.IsInputVideo)
  238. {
  239. var lowBitratePath = Path.Combine(Path.GetDirectoryName(outputPath), Path.GetFileNameWithoutExtension(outputPath) + "-low.m3u8");
  240. var bitrate = hlsVideoRequest.BaselineStreamAudioBitRate ?? 64000;
  241. var lowBitrateParams = string.Format(" -threads {0} -vn -codec:a:0 libmp3lame -ac 2 -ab {2} -hls_time 10 -start_number 0 -hls_list_size 1440 \"{1}\"",
  242. threads,
  243. lowBitratePath,
  244. bitrate / 2);
  245. args += " " + lowBitrateParams;
  246. }
  247. }
  248. return args;
  249. }
  250. }
  251. }