BaseHlsService.cs 8.5 KB

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