BaseHlsService.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Controller.Channels;
  5. using MediaBrowser.Controller.Configuration;
  6. using MediaBrowser.Controller.Dlna;
  7. using MediaBrowser.Controller.Dto;
  8. using MediaBrowser.Controller.Library;
  9. using MediaBrowser.Controller.LiveTv;
  10. using MediaBrowser.Controller.MediaEncoding;
  11. using MediaBrowser.Controller.Persistence;
  12. using MediaBrowser.Model.Configuration;
  13. using MediaBrowser.Model.IO;
  14. using System;
  15. using System.Collections.Generic;
  16. using System.IO;
  17. using System.Text;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  20. namespace MediaBrowser.Api.Playback.Hls
  21. {
  22. /// <summary>
  23. /// Class BaseHlsService
  24. /// </summary>
  25. public abstract class BaseHlsService : BaseStreamingService
  26. {
  27. protected BaseHlsService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, ILiveTvManager liveTvManager, IDlnaManager dlnaManager, IChannelManager channelManager, ISubtitleEncoder subtitleEncoder) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, liveTvManager, dlnaManager, channelManager, subtitleEncoder)
  28. {
  29. }
  30. /// <summary>
  31. /// Gets the audio arguments.
  32. /// </summary>
  33. /// <param name="state">The state.</param>
  34. /// <returns>System.String.</returns>
  35. protected abstract string GetAudioArguments(StreamState state);
  36. /// <summary>
  37. /// Gets the video arguments.
  38. /// </summary>
  39. /// <param name="state">The state.</param>
  40. /// <returns>System.String.</returns>
  41. protected abstract string GetVideoArguments(StreamState state);
  42. /// <summary>
  43. /// Gets the segment file extension.
  44. /// </summary>
  45. /// <param name="state">The state.</param>
  46. /// <returns>System.String.</returns>
  47. protected abstract string GetSegmentFileExtension(StreamState state);
  48. /// <summary>
  49. /// Gets the type of the transcoding job.
  50. /// </summary>
  51. /// <value>The type of the transcoding job.</value>
  52. protected override TranscodingJobType TranscodingJobType
  53. {
  54. get { return TranscodingJobType.Hls; }
  55. }
  56. /// <summary>
  57. /// Processes the request.
  58. /// </summary>
  59. /// <param name="request">The request.</param>
  60. /// <returns>System.Object.</returns>
  61. protected object ProcessRequest(StreamRequest request)
  62. {
  63. return ProcessRequestAsync(request).Result;
  64. }
  65. private static readonly SemaphoreSlim FfmpegStartLock = new SemaphoreSlim(1, 1);
  66. /// <summary>
  67. /// Processes the request async.
  68. /// </summary>
  69. /// <param name="request">The request.</param>
  70. /// <returns>Task{System.Object}.</returns>
  71. /// <exception cref="ArgumentException">
  72. /// A video bitrate is required
  73. /// or
  74. /// An audio bitrate is required
  75. /// </exception>
  76. private async Task<object> ProcessRequestAsync(StreamRequest request)
  77. {
  78. var cancellationTokenSource = new CancellationTokenSource();
  79. var state = GetState(request, cancellationTokenSource.Token).Result;
  80. var playlist = state.OutputFilePath;
  81. if (File.Exists(playlist))
  82. {
  83. ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlist, TranscodingJobType.Hls);
  84. }
  85. else
  86. {
  87. await FfmpegStartLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);
  88. try
  89. {
  90. if (File.Exists(playlist))
  91. {
  92. ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlist, TranscodingJobType.Hls);
  93. }
  94. else
  95. {
  96. // If the playlist doesn't already exist, startup ffmpeg
  97. try
  98. {
  99. await StartFfMpeg(state, playlist, cancellationTokenSource).ConfigureAwait(false);
  100. }
  101. catch
  102. {
  103. state.Dispose();
  104. throw;
  105. }
  106. await WaitForMinimumSegmentCount(playlist, GetSegmentWait(), cancellationTokenSource.Token).ConfigureAwait(false);
  107. }
  108. }
  109. finally
  110. {
  111. FfmpegStartLock.Release();
  112. }
  113. }
  114. int audioBitrate;
  115. int videoBitrate;
  116. GetPlaylistBitrates(state, out audioBitrate, out videoBitrate);
  117. var appendBaselineStream = false;
  118. var baselineStreamBitrate = 64000;
  119. var hlsVideoRequest = state.VideoRequest as GetHlsVideoStream;
  120. if (hlsVideoRequest != null)
  121. {
  122. appendBaselineStream = hlsVideoRequest.AppendBaselineStream;
  123. baselineStreamBitrate = hlsVideoRequest.BaselineStreamAudioBitRate ?? baselineStreamBitrate;
  124. }
  125. var playlistText = GetMasterPlaylistFileText(playlist, videoBitrate + audioBitrate, appendBaselineStream, baselineStreamBitrate);
  126. try
  127. {
  128. return ResultFactory.GetResult(playlistText, MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary<string, string>());
  129. }
  130. finally
  131. {
  132. ApiEntryPoint.Instance.OnTranscodeEndRequest(playlist, TranscodingJobType.Hls);
  133. }
  134. }
  135. /// <summary>
  136. /// Gets the segment wait.
  137. /// </summary>
  138. /// <returns>System.Int32.</returns>
  139. protected int GetSegmentWait()
  140. {
  141. var minimumSegmentCount = 3;
  142. var quality = GetQualitySetting();
  143. if (quality == EncodingQuality.HighSpeed || quality == EncodingQuality.HighQuality)
  144. {
  145. minimumSegmentCount = 2;
  146. }
  147. return minimumSegmentCount;
  148. }
  149. /// <summary>
  150. /// Gets the playlist bitrates.
  151. /// </summary>
  152. /// <param name="state">The state.</param>
  153. /// <param name="audioBitrate">The audio bitrate.</param>
  154. /// <param name="videoBitrate">The video bitrate.</param>
  155. protected void GetPlaylistBitrates(StreamState state, out int audioBitrate, out int videoBitrate)
  156. {
  157. var audioBitrateParam = state.OutputAudioBitrate;
  158. var videoBitrateParam = state.OutputVideoBitrate;
  159. if (!audioBitrateParam.HasValue)
  160. {
  161. if (state.AudioStream != null)
  162. {
  163. audioBitrateParam = state.AudioStream.BitRate;
  164. }
  165. }
  166. if (!videoBitrateParam.HasValue)
  167. {
  168. if (state.VideoStream != null)
  169. {
  170. videoBitrateParam = state.VideoStream.BitRate;
  171. }
  172. }
  173. audioBitrate = audioBitrateParam ?? 0;
  174. videoBitrate = videoBitrateParam ?? 0;
  175. }
  176. private string GetMasterPlaylistFileText(string firstPlaylist, int bitrate, bool includeBaselineStream, int baselineStreamBitrate)
  177. {
  178. var builder = new StringBuilder();
  179. builder.AppendLine("#EXTM3U");
  180. // Pad a little to satisfy the apple hls validator
  181. var paddedBitrate = Convert.ToInt32(bitrate * 1.15);
  182. // Main stream
  183. builder.AppendLine("#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=" + paddedBitrate.ToString(UsCulture));
  184. var playlistUrl = "hls/" + Path.GetFileName(firstPlaylist).Replace(".m3u8", "/stream.m3u8");
  185. builder.AppendLine(playlistUrl);
  186. // Low bitrate stream
  187. if (includeBaselineStream)
  188. {
  189. builder.AppendLine("#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=" + baselineStreamBitrate.ToString(UsCulture));
  190. playlistUrl = "hls/" + Path.GetFileName(firstPlaylist).Replace(".m3u8", "-low/stream.m3u8");
  191. builder.AppendLine(playlistUrl);
  192. }
  193. return builder.ToString();
  194. }
  195. protected async Task WaitForMinimumSegmentCount(string playlist, int segmentCount, CancellationToken cancellationToken)
  196. {
  197. while (true)
  198. {
  199. cancellationToken.ThrowIfCancellationRequested();
  200. string fileText;
  201. // Need to use FileShare.ReadWrite because we're reading the file at the same time it's being written
  202. using (var fileStream = FileSystem.GetFileStream(playlist, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  203. {
  204. using (var reader = new StreamReader(fileStream))
  205. {
  206. fileText = await reader.ReadToEndAsync().ConfigureAwait(false);
  207. }
  208. }
  209. if (CountStringOccurrences(fileText, "#EXTINF:") >= segmentCount)
  210. {
  211. break;
  212. }
  213. await Task.Delay(25, cancellationToken).ConfigureAwait(false);
  214. }
  215. }
  216. /// <summary>
  217. /// Count occurrences of strings.
  218. /// </summary>
  219. /// <param name="text">The text.</param>
  220. /// <param name="pattern">The pattern.</param>
  221. /// <returns>System.Int32.</returns>
  222. private static int CountStringOccurrences(string text, string pattern)
  223. {
  224. // Loop through all instances of the string 'text'.
  225. var count = 0;
  226. var i = 0;
  227. while ((i = text.IndexOf(pattern, i, StringComparison.OrdinalIgnoreCase)) != -1)
  228. {
  229. i += pattern.Length;
  230. count++;
  231. }
  232. return count;
  233. }
  234. /// <summary>
  235. /// Gets the command line arguments.
  236. /// </summary>
  237. /// <param name="outputPath">The output path.</param>
  238. /// <param name="state">The state.</param>
  239. /// <param name="isEncoding">if set to <c>true</c> [is encoding].</param>
  240. /// <returns>System.String.</returns>
  241. protected override string GetCommandLineArguments(string outputPath, StreamState state, bool isEncoding)
  242. {
  243. var hlsVideoRequest = state.VideoRequest as GetHlsVideoStream;
  244. var itsOffsetMs = hlsVideoRequest == null
  245. ? 0
  246. : ((GetHlsVideoStream)state.VideoRequest).TimeStampOffsetMs;
  247. var itsOffset = itsOffsetMs == 0 ? string.Empty : string.Format("-itsoffset {0} ", TimeSpan.FromMilliseconds(itsOffsetMs).TotalSeconds.ToString(UsCulture));
  248. var threads = GetNumberOfThreads(state, false);
  249. var inputModifier = GetInputModifier(state);
  250. // If isEncoding is true we're actually starting ffmpeg
  251. var startNumberParam = isEncoding ? GetStartNumber(state).ToString(UsCulture) : "0";
  252. var args = string.Format("{0} {1} -i {2} -map_metadata -1 -threads {3} {4} {5} -sc_threshold 0 {6} -hls_time {7} -start_number {8} -hls_list_size {9} -y \"{10}\"",
  253. itsOffset,
  254. inputModifier,
  255. GetInputArgument(state),
  256. threads,
  257. GetMapArgs(state),
  258. GetVideoArguments(state),
  259. GetAudioArguments(state),
  260. state.SegmentLength.ToString(UsCulture),
  261. startNumberParam,
  262. state.HlsListSize.ToString(UsCulture),
  263. outputPath
  264. ).Trim();
  265. if (hlsVideoRequest != null)
  266. {
  267. if (hlsVideoRequest.AppendBaselineStream)
  268. {
  269. var lowBitratePath = Path.Combine(Path.GetDirectoryName(outputPath), Path.GetFileNameWithoutExtension(outputPath) + "-low.m3u8");
  270. var bitrate = hlsVideoRequest.BaselineStreamAudioBitRate ?? 64000;
  271. var lowBitrateParams = string.Format(" -threads {0} -vn -codec:a:0 libmp3lame -ac 2 -ab {1} -hls_time {2} -start_number {3} -hls_list_size {4} -y \"{5}\"",
  272. threads,
  273. bitrate / 2,
  274. state.SegmentLength.ToString(UsCulture),
  275. startNumberParam,
  276. state.HlsListSize.ToString(UsCulture),
  277. lowBitratePath);
  278. args += " " + lowBitrateParams;
  279. }
  280. }
  281. return args;
  282. }
  283. protected virtual int GetStartNumber(StreamState state)
  284. {
  285. return 0;
  286. }
  287. }
  288. }