BaseHlsService.cs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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)
  19. : base(appPaths, userManager)
  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. /// <param name="state">The state.</param>
  50. /// <returns>System.Object.</returns>
  51. protected object ProcessRequest(StreamState state)
  52. {
  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. Plugin.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. var content = Encoding.UTF8.GetBytes(playlistText);
  77. var stream = new MemoryStream(content);
  78. try
  79. {
  80. Response.ContentType = MimeTypes.GetMimeType("playlist.m3u8");
  81. return new StreamWriter(stream);
  82. }
  83. finally
  84. {
  85. Plugin.Instance.OnTranscodeEndRequest(playlist, TranscodingJobType.Hls);
  86. }
  87. }
  88. /// <summary>
  89. /// Gets the current playlist text
  90. /// </summary>
  91. /// <param name="playlist">The path to the playlist</param>
  92. /// <param name="waitForMinimumSegments">Whether or not we should wait until it contains three segments</param>
  93. /// <returns>Task{System.String}.</returns>
  94. private async Task<string> GetPlaylistFileText(string playlist, bool waitForMinimumSegments)
  95. {
  96. string fileText;
  97. while (true)
  98. {
  99. // Need to use FileShare.ReadWrite because we're reading the file at the same time it's being written
  100. using (var fileStream = new FileStream(playlist, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  101. {
  102. using (var reader = new StreamReader(fileStream))
  103. {
  104. fileText = await reader.ReadToEndAsync().ConfigureAwait(false);
  105. }
  106. }
  107. if (!waitForMinimumSegments || CountStringOccurrences(fileText, "#EXTINF:") >= 3)
  108. {
  109. break;
  110. }
  111. await Task.Delay(25).ConfigureAwait(false);
  112. }
  113. // The segement paths within the playlist are phsyical, so strip that out to make it relative
  114. fileText = fileText.Replace(Path.GetDirectoryName(playlist) + Path.DirectorySeparatorChar, string.Empty);
  115. // Even though we specify target duration of 9, ffmpeg seems unable to keep all segments under that amount
  116. fileText = fileText.Replace("#EXT-X-TARGETDURATION:9", "#EXT-X-TARGETDURATION:10");
  117. // It's considered live while still encoding (EVENT). Once the encoding has finished, it's video on demand (VOD).
  118. var playlistType = fileText.IndexOf("#EXT-X-ENDLIST", StringComparison.OrdinalIgnoreCase) == -1 ? "EVENT" : "VOD";
  119. // Add event type at the top
  120. fileText = fileText.Replace("#EXT-X-ALLOWCACHE", "#EXT-X-PLAYLIST-TYPE:" + playlistType + Environment.NewLine + "#EXT-X-ALLOWCACHE");
  121. return fileText;
  122. }
  123. /// <summary>
  124. /// Count occurrences of strings.
  125. /// </summary>
  126. /// <param name="text">The text.</param>
  127. /// <param name="pattern">The pattern.</param>
  128. /// <returns>System.Int32.</returns>
  129. private static int CountStringOccurrences(string text, string pattern)
  130. {
  131. // Loop through all instances of the string 'text'.
  132. var count = 0;
  133. var i = 0;
  134. while ((i = text.IndexOf(pattern, i, StringComparison.OrdinalIgnoreCase)) != -1)
  135. {
  136. i += pattern.Length;
  137. count++;
  138. }
  139. return count;
  140. }
  141. /// <summary>
  142. /// Gets the command line arguments.
  143. /// </summary>
  144. /// <param name="outputPath">The output path.</param>
  145. /// <param name="state">The state.</param>
  146. /// <returns>System.String.</returns>
  147. protected override string GetCommandLineArguments(string outputPath, StreamState state)
  148. {
  149. var segmentOutputPath = Path.GetDirectoryName(outputPath);
  150. var segmentOutputName = SegmentFilePrefix + Path.GetFileNameWithoutExtension(outputPath);
  151. segmentOutputPath = Path.Combine(segmentOutputPath, segmentOutputName + "%03d." + GetSegmentFileExtension(state).TrimStart('.'));
  152. var kernel = (Kernel)Kernel;
  153. var probeSize = kernel.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 9 -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. }