BaseHlsService.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Common.MediaInfo;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Controller;
  5. using MediaBrowser.Controller.Library;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Threading.Tasks;
  11. namespace MediaBrowser.Api.Playback.Hls
  12. {
  13. /// <summary>
  14. /// Class BaseHlsService
  15. /// </summary>
  16. public abstract class BaseHlsService : BaseStreamingService
  17. {
  18. /// <summary>
  19. /// The segment file prefix
  20. /// </summary>
  21. public const string SegmentFilePrefix = "segment-";
  22. /// <summary>
  23. /// Initializes a new instance of the <see cref="BaseStreamingService" /> class.
  24. /// </summary>
  25. /// <param name="appPaths">The app paths.</param>
  26. /// <param name="userManager">The user manager.</param>
  27. /// <param name="libraryManager">The library manager.</param>
  28. /// <param name="isoManager">The iso manager.</param>
  29. /// <param name="mediaEncoder">The media encoder.</param>
  30. protected BaseHlsService(IServerApplicationPaths appPaths, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder)
  31. : base(appPaths, userManager, libraryManager, isoManager, mediaEncoder)
  32. {
  33. }
  34. /// <summary>
  35. /// Gets the audio arguments.
  36. /// </summary>
  37. /// <param name="state">The state.</param>
  38. /// <returns>System.String.</returns>
  39. protected abstract string GetAudioArguments(StreamState state);
  40. /// <summary>
  41. /// Gets the video arguments.
  42. /// </summary>
  43. /// <param name="state">The state.</param>
  44. /// <param name="performSubtitleConversion">if set to <c>true</c> [perform subtitle conversion].</param>
  45. /// <returns>System.String.</returns>
  46. protected abstract string GetVideoArguments(StreamState state, bool performSubtitleConversion);
  47. /// <summary>
  48. /// Gets the segment file extension.
  49. /// </summary>
  50. /// <param name="state">The state.</param>
  51. /// <returns>System.String.</returns>
  52. protected abstract string GetSegmentFileExtension(StreamState state);
  53. /// <summary>
  54. /// Gets the type of the transcoding job.
  55. /// </summary>
  56. /// <value>The type of the transcoding job.</value>
  57. protected override TranscodingJobType TranscodingJobType
  58. {
  59. get { return TranscodingJobType.Hls; }
  60. }
  61. /// <summary>
  62. /// Processes the request.
  63. /// </summary>
  64. /// <param name="request">The request.</param>
  65. /// <returns>System.Object.</returns>
  66. protected object ProcessRequest(StreamRequest request)
  67. {
  68. var state = GetState(request);
  69. return ProcessRequestAsync(state).Result;
  70. }
  71. /// <summary>
  72. /// Processes the request async.
  73. /// </summary>
  74. /// <param name="state">The state.</param>
  75. /// <returns>Task{System.Object}.</returns>
  76. public async Task<object> ProcessRequestAsync(StreamState state)
  77. {
  78. var playlist = GetOutputFilePath(state);
  79. var isPlaylistNewlyCreated = false;
  80. // If the playlist doesn't already exist, startup ffmpeg
  81. if (!File.Exists(playlist))
  82. {
  83. isPlaylistNewlyCreated = true;
  84. await StartFfMpeg(state, playlist).ConfigureAwait(false);
  85. }
  86. else
  87. {
  88. ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlist, TranscodingJobType.Hls);
  89. }
  90. // Get the current playlist text and convert to bytes
  91. var playlistText = await GetPlaylistFileText(playlist, isPlaylistNewlyCreated).ConfigureAwait(false);
  92. try
  93. {
  94. return ResultFactory.GetResult(playlistText, MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary<string, string>());
  95. }
  96. finally
  97. {
  98. ApiEntryPoint.Instance.OnTranscodeEndRequest(playlist, TranscodingJobType.Hls);
  99. }
  100. }
  101. /// <summary>
  102. /// Gets the current playlist text
  103. /// </summary>
  104. /// <param name="playlist">The path to the playlist</param>
  105. /// <param name="waitForMinimumSegments">Whether or not we should wait until it contains three segments</param>
  106. /// <returns>Task{System.String}.</returns>
  107. private async Task<string> GetPlaylistFileText(string playlist, bool waitForMinimumSegments)
  108. {
  109. string fileText;
  110. while (true)
  111. {
  112. // Need to use FileShare.ReadWrite because we're reading the file at the same time it's being written
  113. using (var fileStream = new FileStream(playlist, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  114. {
  115. using (var reader = new StreamReader(fileStream))
  116. {
  117. fileText = await reader.ReadToEndAsync().ConfigureAwait(false);
  118. }
  119. }
  120. if (!waitForMinimumSegments || CountStringOccurrences(fileText, "#EXTINF:") >= 3)
  121. {
  122. break;
  123. }
  124. await Task.Delay(25).ConfigureAwait(false);
  125. }
  126. // The segement paths within the playlist are phsyical, so strip that out to make it relative
  127. fileText = fileText.Replace(Path.GetDirectoryName(playlist) + Path.DirectorySeparatorChar, string.Empty);
  128. fileText = fileText.Replace(SegmentFilePrefix, "segments/").Replace(".ts", "/stream.ts").Replace(".aac", "/stream.aac").Replace(".mp3", "/stream.mp3");
  129. // It's considered live while still encoding (EVENT). Once the encoding has finished, it's video on demand (VOD).
  130. var playlistType = fileText.IndexOf("#EXT-X-ENDLIST", StringComparison.OrdinalIgnoreCase) == -1 ? "EVENT" : "VOD";
  131. const string allowCacheAttributeName = "#EXT-X-ALLOW-CACHE";
  132. // fix this to make the media stream validator happy
  133. // https://ffmpeg.org/trac/ffmpeg/ticket/2228
  134. fileText = fileText.Replace("#EXT-X-ALLOWCACHE", allowCacheAttributeName);
  135. // Add event type at the top
  136. fileText = fileText.Replace(allowCacheAttributeName, "#EXT-X-PLAYLIST-TYPE:" + playlistType + Environment.NewLine + allowCacheAttributeName);
  137. return fileText;
  138. }
  139. /// <summary>
  140. /// Count occurrences of strings.
  141. /// </summary>
  142. /// <param name="text">The text.</param>
  143. /// <param name="pattern">The pattern.</param>
  144. /// <returns>System.Int32.</returns>
  145. private static int CountStringOccurrences(string text, string pattern)
  146. {
  147. // Loop through all instances of the string 'text'.
  148. var count = 0;
  149. var i = 0;
  150. while ((i = text.IndexOf(pattern, i, StringComparison.OrdinalIgnoreCase)) != -1)
  151. {
  152. i += pattern.Length;
  153. count++;
  154. }
  155. return count;
  156. }
  157. /// <summary>
  158. /// Gets the command line arguments.
  159. /// </summary>
  160. /// <param name="outputPath">The output path.</param>
  161. /// <param name="state">The state.</param>
  162. /// <param name="performSubtitleConversions">if set to <c>true</c> [perform subtitle conversions].</param>
  163. /// <returns>System.String.</returns>
  164. protected override string GetCommandLineArguments(string outputPath, StreamState state, bool performSubtitleConversions)
  165. {
  166. var segmentOutputPath = Path.GetDirectoryName(outputPath);
  167. var segmentOutputName = SegmentFilePrefix + Path.GetFileNameWithoutExtension(outputPath);
  168. segmentOutputPath = Path.Combine(segmentOutputPath, segmentOutputName + "%03d." + GetSegmentFileExtension(state).TrimStart('.'));
  169. var probeSize = GetProbeSizeArgument(state.Item);
  170. return string.Format("{0} {1} -i {2}{3} -threads 0 {4} {5} {6} -f ssegment -segment_list_flags +live -segment_time 10 -segment_list \"{7}\" \"{8}\"",
  171. probeSize,
  172. GetFastSeekCommandLineParameter(state.Request),
  173. GetInputArgument(state.Item, state.IsoMount),
  174. GetSlowSeekCommandLineParameter(state.Request),
  175. GetMapArgs(state),
  176. GetVideoArguments(state, performSubtitleConversions),
  177. GetAudioArguments(state),
  178. outputPath,
  179. segmentOutputPath
  180. ).Trim();
  181. }
  182. /// <summary>
  183. /// Deletes the partial stream files.
  184. /// </summary>
  185. /// <param name="outputFilePath">The output file path.</param>
  186. protected override void DeletePartialStreamFiles(string outputFilePath)
  187. {
  188. var directory = Path.GetDirectoryName(outputFilePath);
  189. var name = Path.GetFileNameWithoutExtension(outputFilePath);
  190. var filesToDelete = Directory.EnumerateFiles(directory)
  191. .Where(f => f.IndexOf(name, StringComparison.OrdinalIgnoreCase) != -1)
  192. .ToList();
  193. foreach (var file in filesToDelete)
  194. {
  195. try
  196. {
  197. Logger.Info("Deleting HLS file {0}", file);
  198. File.Delete(file);
  199. }
  200. catch (IOException ex)
  201. {
  202. Logger.ErrorException("Error deleting HLS file {0}", ex, file);
  203. }
  204. }
  205. }
  206. }
  207. }