BaseHlsPlaylistHandler.cs 8.7 KB

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