BaseHlsService.cs 9.9 KB

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