BaseHlsService.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Common.MediaInfo;
  4. using MediaBrowser.Common.Net;
  5. using MediaBrowser.Controller;
  6. using MediaBrowser.Controller.Dto;
  7. using MediaBrowser.Controller.Entities;
  8. using MediaBrowser.Controller.Library;
  9. using MediaBrowser.Model.IO;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.IO;
  13. using System.Linq;
  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 override string GetOutputFilePath(StreamState state)
  24. {
  25. var folder = ApplicationPaths.EncodedMediaCachePath;
  26. var outputFileExtension = GetOutputFileExtension(state);
  27. return Path.Combine(folder, GetCommandLineArguments("dummy\\dummy", state, false).GetMD5() + (outputFileExtension ?? string.Empty).ToLower());
  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. protected BaseHlsService(IServerApplicationPaths appPaths, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IDtoService dtoService)
  38. : base(appPaths, userManager, libraryManager, isoManager, mediaEncoder, dtoService)
  39. {
  40. }
  41. /// <summary>
  42. /// Gets the audio arguments.
  43. /// </summary>
  44. /// <param name="state">The state.</param>
  45. /// <returns>System.String.</returns>
  46. protected abstract string GetAudioArguments(StreamState state);
  47. /// <summary>
  48. /// Gets the video arguments.
  49. /// </summary>
  50. /// <param name="state">The state.</param>
  51. /// <param name="performSubtitleConversion">if set to <c>true</c> [perform subtitle conversion].</param>
  52. /// <returns>System.String.</returns>
  53. protected abstract string GetVideoArguments(StreamState state, bool performSubtitleConversion);
  54. /// <summary>
  55. /// Gets the segment file extension.
  56. /// </summary>
  57. /// <param name="state">The state.</param>
  58. /// <returns>System.String.</returns>
  59. protected abstract string GetSegmentFileExtension(StreamState state);
  60. /// <summary>
  61. /// Gets the type of the transcoding job.
  62. /// </summary>
  63. /// <value>The type of the transcoding job.</value>
  64. protected override TranscodingJobType TranscodingJobType
  65. {
  66. get { return TranscodingJobType.Hls; }
  67. }
  68. /// <summary>
  69. /// Processes the request.
  70. /// </summary>
  71. /// <param name="request">The request.</param>
  72. /// <returns>System.Object.</returns>
  73. protected object ProcessRequest(StreamRequest request)
  74. {
  75. var state = GetState(request);
  76. return ProcessRequestAsync(state).Result;
  77. }
  78. /// <summary>
  79. /// Processes the request async.
  80. /// </summary>
  81. /// <param name="state">The state.</param>
  82. /// <returns>Task{System.Object}.</returns>
  83. public async Task<object> ProcessRequestAsync(StreamState state)
  84. {
  85. if (!state.VideoRequest.VideoBitRate.HasValue)
  86. {
  87. throw new ArgumentException("A video bitrate is required");
  88. }
  89. if (!state.Request.AudioBitRate.HasValue)
  90. {
  91. throw new ArgumentException("An audio bitrate is required");
  92. }
  93. var playlist = GetOutputFilePath(state);
  94. var isPlaylistNewlyCreated = false;
  95. // If the playlist doesn't already exist, startup ffmpeg
  96. if (!File.Exists(playlist))
  97. {
  98. isPlaylistNewlyCreated = true;
  99. await StartFfMpeg(state, playlist).ConfigureAwait(false);
  100. }
  101. else
  102. {
  103. ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlist, TranscodingJobType.Hls);
  104. }
  105. if (isPlaylistNewlyCreated)
  106. {
  107. await WaitForMinimumSegmentCount(playlist, 3).ConfigureAwait(false);
  108. }
  109. var audioBitrate = GetAudioBitrateParam(state) ?? 0;
  110. var videoBitrate = GetVideoBitrateParam(state) ?? 0;
  111. var playlistText = GetMasterPlaylistFileText(playlist, videoBitrate + audioBitrate);
  112. try
  113. {
  114. return ResultFactory.GetResult(playlistText, MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary<string, string>());
  115. }
  116. finally
  117. {
  118. ApiEntryPoint.Instance.OnTranscodeEndRequest(playlist, TranscodingJobType.Hls);
  119. }
  120. }
  121. private string GetMasterPlaylistFileText(string firstPlaylist, int bitrate)
  122. {
  123. var builder = new StringBuilder();
  124. builder.AppendLine("#EXTM3U");
  125. // Pad a little to satisfy the apple hls validator
  126. var paddedBitrate = Convert.ToInt32(bitrate * 1.05);
  127. // Main stream
  128. builder.AppendLine("#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=" + paddedBitrate.ToString(UsCulture));
  129. var playlistUrl = "hls/" + Path.GetFileName(firstPlaylist).Replace(".m3u8", "/stream.m3u8");
  130. builder.AppendLine(playlistUrl);
  131. // Low bitrate stream
  132. builder.AppendLine("#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=64000");
  133. playlistUrl = "hls/" + Path.GetFileName(firstPlaylist).Replace(".m3u8", "-low/stream.m3u8");
  134. builder.AppendLine(playlistUrl);
  135. return builder.ToString();
  136. }
  137. private async Task WaitForMinimumSegmentCount(string playlist, int segmentCount)
  138. {
  139. while (true)
  140. {
  141. string fileText;
  142. // Need to use FileShare.ReadWrite because we're reading the file at the same time it's being written
  143. using (var fileStream = new FileStream(playlist, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  144. {
  145. using (var reader = new StreamReader(fileStream))
  146. {
  147. fileText = await reader.ReadToEndAsync().ConfigureAwait(false);
  148. }
  149. }
  150. if (CountStringOccurrences(fileText, "#EXTINF:") >= segmentCount)
  151. {
  152. break;
  153. }
  154. await Task.Delay(25).ConfigureAwait(false);
  155. }
  156. }
  157. /// <summary>
  158. /// Count occurrences of strings.
  159. /// </summary>
  160. /// <param name="text">The text.</param>
  161. /// <param name="pattern">The pattern.</param>
  162. /// <returns>System.Int32.</returns>
  163. private static int CountStringOccurrences(string text, string pattern)
  164. {
  165. // Loop through all instances of the string 'text'.
  166. var count = 0;
  167. var i = 0;
  168. while ((i = text.IndexOf(pattern, i, StringComparison.OrdinalIgnoreCase)) != -1)
  169. {
  170. i += pattern.Length;
  171. count++;
  172. }
  173. return count;
  174. }
  175. protected void ExtendHlsTimer(string itemId, string playlistId)
  176. {
  177. var normalizedPlaylistId = playlistId.Replace("-low", string.Empty);
  178. foreach (var playlist in Directory.EnumerateFiles(ApplicationPaths.EncodedMediaCachePath, "*.m3u8")
  179. .Where(i => i.IndexOf(normalizedPlaylistId, StringComparison.OrdinalIgnoreCase) != -1)
  180. .ToList())
  181. {
  182. ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlist, TranscodingJobType.Hls);
  183. // Avoid implicitly captured closure
  184. var playlist1 = playlist;
  185. Task.Run(async () =>
  186. {
  187. // This is an arbitrary time period corresponding to when the request completes.
  188. await Task.Delay(30000).ConfigureAwait(false);
  189. ApiEntryPoint.Instance.OnTranscodeEndRequest(playlist1, TranscodingJobType.Hls);
  190. });
  191. }
  192. }
  193. /// <summary>
  194. /// Gets the command line arguments.
  195. /// </summary>
  196. /// <param name="outputPath">The output path.</param>
  197. /// <param name="state">The state.</param>
  198. /// <param name="performSubtitleConversions">if set to <c>true</c> [perform subtitle conversions].</param>
  199. /// <returns>System.String.</returns>
  200. protected override string GetCommandLineArguments(string outputPath, StreamState state, bool performSubtitleConversions)
  201. {
  202. var probeSize = GetProbeSizeArgument(state.Item);
  203. var args = string.Format("-itsoffset 1 {0} {1} {2} -i {3}{4} -threads 0 {5} {6} -sc_threshold 0 {7} -hls_time 10 -start_number 0 -hls_list_size 1440 \"{8}\"",
  204. probeSize,
  205. GetUserAgentParam(state.Item),
  206. GetFastSeekCommandLineParameter(state.Request),
  207. GetInputArgument(state.Item, state.IsoMount),
  208. GetSlowSeekCommandLineParameter(state.Request),
  209. GetMapArgs(state),
  210. GetVideoArguments(state, performSubtitleConversions),
  211. GetAudioArguments(state),
  212. outputPath
  213. ).Trim();
  214. if (state.Item is Video)
  215. {
  216. var lowBitratePath = Path.Combine(Path.GetDirectoryName(outputPath), Path.GetFileNameWithoutExtension(outputPath) + "-low.m3u8");
  217. var lowBitrateParams = string.Format(" -threads 0 -vn -codec:a:0 libmp3lame -ac 2 -ab 32000 -hls_time 10 -start_number 0 -hls_list_size 1440 \"{0}\"",
  218. lowBitratePath,
  219. state.AudioStream.Index);
  220. args += " " + lowBitrateParams;
  221. }
  222. return args;
  223. }
  224. }
  225. }