BaseHlsService.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.Devices;
  4. using MediaBrowser.Controller.Dlna;
  5. using MediaBrowser.Controller.Library;
  6. using MediaBrowser.Controller.MediaEncoding;
  7. using MediaBrowser.Model.Extensions;
  8. using MediaBrowser.Model.IO;
  9. using MediaBrowser.Model.Net;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.IO;
  13. using System.Text;
  14. using System.Threading;
  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, IFileSystem fileSystem, IDlnaManager dlnaManager, ISubtitleEncoder subtitleEncoder, IDeviceManager deviceManager, IMediaSourceManager mediaSourceManager, IZipClient zipClient) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, dlnaManager, subtitleEncoder, deviceManager, mediaSourceManager, zipClient)
  24. {
  25. }
  26. /// <summary>
  27. /// Gets the audio arguments.
  28. /// </summary>
  29. /// <param name="state">The state.</param>
  30. /// <returns>System.String.</returns>
  31. protected abstract string GetAudioArguments(StreamState state);
  32. /// <summary>
  33. /// Gets the video arguments.
  34. /// </summary>
  35. /// <param name="state">The state.</param>
  36. /// <returns>System.String.</returns>
  37. protected abstract string GetVideoArguments(StreamState state);
  38. /// <summary>
  39. /// Gets the segment file extension.
  40. /// </summary>
  41. /// <param name="state">The state.</param>
  42. /// <returns>System.String.</returns>
  43. protected abstract string GetSegmentFileExtension(StreamState state);
  44. /// <summary>
  45. /// Gets the type of the transcoding job.
  46. /// </summary>
  47. /// <value>The type of the transcoding job.</value>
  48. protected override TranscodingJobType TranscodingJobType
  49. {
  50. get { return TranscodingJobType.Hls; }
  51. }
  52. /// <summary>
  53. /// Processes the request.
  54. /// </summary>
  55. /// <param name="request">The request.</param>
  56. /// <param name="isLive">if set to <c>true</c> [is live].</param>
  57. /// <returns>System.Object.</returns>
  58. protected object ProcessRequest(StreamRequest request, bool isLive)
  59. {
  60. return ProcessRequestAsync(request, isLive).Result;
  61. }
  62. /// <summary>
  63. /// Processes the request async.
  64. /// </summary>
  65. /// <param name="request">The request.</param>
  66. /// <param name="isLive">if set to <c>true</c> [is live].</param>
  67. /// <returns>Task{System.Object}.</returns>
  68. /// <exception cref="ArgumentException">A video bitrate is required
  69. /// or
  70. /// An audio bitrate is required</exception>
  71. private async Task<object> ProcessRequestAsync(StreamRequest request, bool isLive)
  72. {
  73. var cancellationTokenSource = new CancellationTokenSource();
  74. var state = await GetState(request, cancellationTokenSource.Token).ConfigureAwait(false);
  75. if (isLive)
  76. {
  77. state.Request.StartTimeTicks = null;
  78. }
  79. TranscodingJob job = null;
  80. var playlist = state.OutputFilePath;
  81. if (!File.Exists(playlist))
  82. {
  83. await ApiEntryPoint.Instance.TranscodingStartLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);
  84. try
  85. {
  86. if (!File.Exists(playlist))
  87. {
  88. // If the playlist doesn't already exist, startup ffmpeg
  89. try
  90. {
  91. job = await StartFfMpeg(state, playlist, cancellationTokenSource).ConfigureAwait(false);
  92. }
  93. catch
  94. {
  95. state.Dispose();
  96. throw;
  97. }
  98. await WaitForMinimumSegmentCount(playlist, 3, cancellationTokenSource.Token).ConfigureAwait(false);
  99. }
  100. }
  101. finally
  102. {
  103. ApiEntryPoint.Instance.TranscodingStartLock.Release();
  104. }
  105. }
  106. if (isLive)
  107. {
  108. job = job ?? ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlist, TranscodingJobType);
  109. if (job != null)
  110. {
  111. ApiEntryPoint.Instance.OnTranscodeEndRequest(job);
  112. }
  113. return ResultFactory.GetResult(GetLivePlaylistText(playlist, state.SegmentLength), MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary<string, string>());
  114. }
  115. var audioBitrate = state.OutputAudioBitrate ?? 0;
  116. var videoBitrate = state.OutputVideoBitrate ?? 0;
  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. job = job ?? ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlist, TranscodingJobType);
  127. if (job != null)
  128. {
  129. ApiEntryPoint.Instance.OnTranscodeEndRequest(job);
  130. }
  131. return ResultFactory.GetResult(playlistText, MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary<string, string>());
  132. }
  133. private string GetLivePlaylistText(string path, int segmentLength)
  134. {
  135. using (var stream = FileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  136. {
  137. using (var reader = new StreamReader(stream))
  138. {
  139. var text = reader.ReadToEnd();
  140. var newDuration = "#EXT-X-TARGETDURATION:" + segmentLength.ToString(UsCulture) + Environment.NewLine + "#EXT-X-ALLOW-CACHE:NO";
  141. // ffmpeg pads the reported length by a full second
  142. return text.Replace("#EXT-X-TARGETDURATION:" + (segmentLength + 1).ToString(UsCulture), newDuration, StringComparison.OrdinalIgnoreCase);
  143. }
  144. }
  145. }
  146. private string GetMasterPlaylistFileText(string firstPlaylist, int bitrate, bool includeBaselineStream, int baselineStreamBitrate)
  147. {
  148. var builder = new StringBuilder();
  149. builder.AppendLine("#EXTM3U");
  150. // Pad a little to satisfy the apple hls validator
  151. var paddedBitrate = Convert.ToInt32(bitrate * 1.15);
  152. // Main stream
  153. builder.AppendLine("#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=" + paddedBitrate.ToString(UsCulture));
  154. var playlistUrl = "hls/" + Path.GetFileName(firstPlaylist).Replace(".m3u8", "/stream.m3u8");
  155. builder.AppendLine(playlistUrl);
  156. // Low bitrate stream
  157. if (includeBaselineStream)
  158. {
  159. builder.AppendLine("#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=" + baselineStreamBitrate.ToString(UsCulture));
  160. playlistUrl = "hls/" + Path.GetFileName(firstPlaylist).Replace(".m3u8", "-low/stream.m3u8");
  161. builder.AppendLine(playlistUrl);
  162. }
  163. return builder.ToString();
  164. }
  165. protected virtual async Task WaitForMinimumSegmentCount(string playlist, int segmentCount, CancellationToken cancellationToken)
  166. {
  167. Logger.Debug("Waiting for {0} segments in {1}", segmentCount, playlist);
  168. while (true)
  169. {
  170. // Need to use FileShare.ReadWrite because we're reading the file at the same time it's being written
  171. using (var fileStream = GetPlaylistFileStream(playlist))
  172. {
  173. using (var reader = new StreamReader(fileStream))
  174. {
  175. var count = 0;
  176. while (!reader.EndOfStream)
  177. {
  178. var line = await reader.ReadLineAsync().ConfigureAwait(false);
  179. if (line.IndexOf("#EXTINF:", StringComparison.OrdinalIgnoreCase) != -1)
  180. {
  181. count++;
  182. if (count >= segmentCount)
  183. {
  184. Logger.Debug("Finished waiting for {0} segments in {1}", segmentCount, playlist);
  185. return;
  186. }
  187. }
  188. }
  189. await Task.Delay(100, cancellationToken).ConfigureAwait(false);
  190. }
  191. }
  192. }
  193. }
  194. protected Stream GetPlaylistFileStream(string path)
  195. {
  196. var tmpPath = path + ".tmp";
  197. try
  198. {
  199. return FileSystem.GetFileStream(tmpPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true);
  200. }
  201. catch (IOException)
  202. {
  203. return FileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true);
  204. }
  205. }
  206. protected override string GetCommandLineArguments(string outputPath, StreamState state, bool isEncoding)
  207. {
  208. var hlsVideoRequest = state.VideoRequest as GetHlsVideoStream;
  209. var itsOffsetMs = hlsVideoRequest == null
  210. ? 0
  211. : hlsVideoRequest.TimeStampOffsetMs;
  212. var itsOffset = itsOffsetMs == 0 ? string.Empty : string.Format("-itsoffset {0} ", TimeSpan.FromMilliseconds(itsOffsetMs).TotalSeconds.ToString(UsCulture));
  213. var threads = GetNumberOfThreads(state, false);
  214. var inputModifier = GetInputModifier(state);
  215. // If isEncoding is true we're actually starting ffmpeg
  216. var startNumberParam = isEncoding ? GetStartNumber(state).ToString(UsCulture) : "0";
  217. var baseUrlParam = string.Empty;
  218. if (state.Request is GetLiveHlsStream)
  219. {
  220. baseUrlParam = string.Format(" -hls_base_url \"{0}/\"",
  221. "hls/" + Path.GetFileNameWithoutExtension(outputPath));
  222. }
  223. var args = string.Format("{0} {1} {2} -map_metadata -1 -threads {3} {4} {5} -sc_threshold 0 {6} -hls_time {7} -start_number {8} -hls_list_size {9}{10} -y \"{11}\"",
  224. itsOffset,
  225. inputModifier,
  226. GetInputArgument(state),
  227. threads,
  228. GetMapArgs(state),
  229. GetVideoArguments(state),
  230. GetAudioArguments(state),
  231. state.SegmentLength.ToString(UsCulture),
  232. startNumberParam,
  233. state.HlsListSize.ToString(UsCulture),
  234. baseUrlParam,
  235. outputPath
  236. ).Trim();
  237. if (hlsVideoRequest != null)
  238. {
  239. if (hlsVideoRequest.AppendBaselineStream)
  240. {
  241. var lowBitratePath = Path.Combine(Path.GetDirectoryName(outputPath), Path.GetFileNameWithoutExtension(outputPath) + "-low.m3u8");
  242. var bitrate = hlsVideoRequest.BaselineStreamAudioBitRate ?? 64000;
  243. 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}\"",
  244. threads,
  245. bitrate / 2,
  246. state.SegmentLength.ToString(UsCulture),
  247. startNumberParam,
  248. state.HlsListSize.ToString(UsCulture),
  249. lowBitratePath);
  250. args += " " + lowBitrateParams;
  251. }
  252. }
  253. return args;
  254. }
  255. protected virtual int GetStartNumber(StreamState state)
  256. {
  257. return 0;
  258. }
  259. }
  260. }