BaseHlsService.cs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. using System.Collections.Generic;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Controller;
  5. using MediaBrowser.Controller.Library;
  6. using System;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. namespace MediaBrowser.Api.Playback.Hls
  12. {
  13. public abstract class BaseHlsService : BaseStreamingService
  14. {
  15. /// <summary>
  16. /// The segment file prefix
  17. /// </summary>
  18. public const string SegmentFilePrefix = "segment-";
  19. protected BaseHlsService(IServerApplicationPaths appPaths, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager)
  20. : base(appPaths, userManager, libraryManager, isoManager)
  21. {
  22. }
  23. /// <summary>
  24. /// Gets the audio arguments.
  25. /// </summary>
  26. /// <returns>System.String.</returns>
  27. protected abstract string GetAudioArguments(StreamState state);
  28. /// <summary>
  29. /// Gets the video arguments.
  30. /// </summary>
  31. /// <returns>System.String.</returns>
  32. protected abstract string GetVideoArguments(StreamState state);
  33. /// <summary>
  34. /// Gets the segment file extension.
  35. /// </summary>
  36. /// <param name="state">The state.</param>
  37. /// <returns>System.String.</returns>
  38. protected abstract string GetSegmentFileExtension(StreamState state);
  39. /// <summary>
  40. /// Gets the type of the transcoding job.
  41. /// </summary>
  42. /// <value>The type of the transcoding job.</value>
  43. protected override TranscodingJobType TranscodingJobType
  44. {
  45. get { return TranscodingJobType.Hls; }
  46. }
  47. /// <summary>
  48. /// Processes the request.
  49. /// </summary>
  50. /// <returns>System.Object.</returns>
  51. protected object ProcessRequest(StreamRequest request)
  52. {
  53. var state = GetState(request);
  54. return ProcessRequestAsync(state).Result;
  55. }
  56. /// <summary>
  57. /// Processes the request async.
  58. /// </summary>
  59. /// <param name="state">The state.</param>
  60. /// <returns>Task{System.Object}.</returns>
  61. public async Task<object> ProcessRequestAsync(StreamState state)
  62. {
  63. var playlist = GetOutputFilePath(state);
  64. var isPlaylistNewlyCreated = false;
  65. // If the playlist doesn't already exist, startup ffmpeg
  66. if (!File.Exists(playlist))
  67. {
  68. isPlaylistNewlyCreated = true;
  69. await StartFFMpeg(state, playlist).ConfigureAwait(false);
  70. }
  71. else
  72. {
  73. ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlist, TranscodingJobType.Hls);
  74. }
  75. // Get the current playlist text and convert to bytes
  76. var playlistText = await GetPlaylistFileText(playlist, isPlaylistNewlyCreated).ConfigureAwait(false);
  77. try
  78. {
  79. return ResultFactory.GetResult(playlistText, MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary<string, string>());
  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. // It's considered live while still encoding (EVENT). Once the encoding has finished, it's video on demand (VOD).
  115. var playlistType = fileText.IndexOf("#EXT-X-ENDLIST", StringComparison.OrdinalIgnoreCase) == -1 ? "EVENT" : "VOD";
  116. const string allowCacheAttributeName = "#EXT-X-ALLOW-CACHE";
  117. // fix this to make the media stream validator happy
  118. // https://ffmpeg.org/trac/ffmpeg/ticket/2228
  119. fileText = fileText.Replace("#EXT-X-ALLOWCACHE", allowCacheAttributeName);
  120. // Add event type at the top
  121. fileText = fileText.Replace(allowCacheAttributeName, "#EXT-X-PLAYLIST-TYPE:" + playlistType + Environment.NewLine + allowCacheAttributeName);
  122. return fileText;
  123. }
  124. /// <summary>
  125. /// Count occurrences of strings.
  126. /// </summary>
  127. /// <param name="text">The text.</param>
  128. /// <param name="pattern">The pattern.</param>
  129. /// <returns>System.Int32.</returns>
  130. private static int CountStringOccurrences(string text, string pattern)
  131. {
  132. // Loop through all instances of the string 'text'.
  133. var count = 0;
  134. var i = 0;
  135. while ((i = text.IndexOf(pattern, i, StringComparison.OrdinalIgnoreCase)) != -1)
  136. {
  137. i += pattern.Length;
  138. count++;
  139. }
  140. return count;
  141. }
  142. /// <summary>
  143. /// Gets the command line arguments.
  144. /// </summary>
  145. /// <param name="outputPath">The output path.</param>
  146. /// <param name="state">The state.</param>
  147. /// <returns>System.String.</returns>
  148. protected override string GetCommandLineArguments(string outputPath, StreamState state)
  149. {
  150. var segmentOutputPath = Path.GetDirectoryName(outputPath);
  151. var segmentOutputName = SegmentFilePrefix + Path.GetFileNameWithoutExtension(outputPath);
  152. segmentOutputPath = Path.Combine(segmentOutputPath, segmentOutputName + "%03d." + GetSegmentFileExtension(state).TrimStart('.'));
  153. var probeSize = Kernel.Instance.FFMpegManager.GetProbeSizeArgument(state.Item);
  154. 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}\"",
  155. probeSize,
  156. GetFastSeekCommandLineParameter(state.Request),
  157. GetInputArgument(state.Item, state.IsoMount),
  158. GetSlowSeekCommandLineParameter(state.Request),
  159. GetMapArgs(state),
  160. GetVideoArguments(state),
  161. GetAudioArguments(state),
  162. outputPath,
  163. segmentOutputPath
  164. ).Trim();
  165. }
  166. /// <summary>
  167. /// Deletes the partial stream files.
  168. /// </summary>
  169. /// <param name="outputFilePath">The output file path.</param>
  170. protected override void DeletePartialStreamFiles(string outputFilePath)
  171. {
  172. var directory = Path.GetDirectoryName(outputFilePath);
  173. var name = Path.GetFileNameWithoutExtension(outputFilePath);
  174. var filesToDelete = Directory.EnumerateFiles(directory, "*", SearchOption.TopDirectoryOnly)
  175. .Where(f => f.IndexOf(name, StringComparison.OrdinalIgnoreCase) != -1)
  176. .ToList();
  177. foreach (var file in filesToDelete)
  178. {
  179. try
  180. {
  181. Logger.Info("Deleting HLS file {0}", file);
  182. File.Delete(file);
  183. }
  184. catch (IOException ex)
  185. {
  186. Logger.ErrorException("Error deleting HLS file {0}", ex, file);
  187. }
  188. }
  189. }
  190. }
  191. }