BaseHlsService.cs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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. // Add event type at the top
  117. fileText = fileText.Replace("#EXT-X-ALLOW-CACHE", "#EXT-X-PLAYLIST-TYPE:" + playlistType + Environment.NewLine + "#EXT-X-ALLOWCACHE");
  118. return fileText;
  119. }
  120. /// <summary>
  121. /// Count occurrences of strings.
  122. /// </summary>
  123. /// <param name="text">The text.</param>
  124. /// <param name="pattern">The pattern.</param>
  125. /// <returns>System.Int32.</returns>
  126. private static int CountStringOccurrences(string text, string pattern)
  127. {
  128. // Loop through all instances of the string 'text'.
  129. var count = 0;
  130. var i = 0;
  131. while ((i = text.IndexOf(pattern, i, StringComparison.OrdinalIgnoreCase)) != -1)
  132. {
  133. i += pattern.Length;
  134. count++;
  135. }
  136. return count;
  137. }
  138. /// <summary>
  139. /// Gets the command line arguments.
  140. /// </summary>
  141. /// <param name="outputPath">The output path.</param>
  142. /// <param name="state">The state.</param>
  143. /// <returns>System.String.</returns>
  144. protected override string GetCommandLineArguments(string outputPath, StreamState state)
  145. {
  146. var segmentOutputPath = Path.GetDirectoryName(outputPath);
  147. var segmentOutputName = SegmentFilePrefix + Path.GetFileNameWithoutExtension(outputPath);
  148. segmentOutputPath = Path.Combine(segmentOutputPath, segmentOutputName + "%03d." + GetSegmentFileExtension(state).TrimStart('.'));
  149. var probeSize = Kernel.Instance.FFMpegManager.GetProbeSizeArgument(state.Item);
  150. return string.Format("{0} {1} -i {2}{3} -threads 0 {4} {5} {6} -force_key_frames expr:gte(t,n_forced*5) -f ssegment -segment_list_flags +live -segment_time 10 -segment_list \"{7}\" \"{8}\"",
  151. probeSize,
  152. GetFastSeekCommandLineParameter(state.Request),
  153. GetInputArgument(state.Item, state.IsoMount),
  154. GetSlowSeekCommandLineParameter(state.Request),
  155. GetMapArgs(state),
  156. GetVideoArguments(state),
  157. GetAudioArguments(state),
  158. outputPath,
  159. segmentOutputPath
  160. ).Trim();
  161. }
  162. /// <summary>
  163. /// Deletes the partial stream files.
  164. /// </summary>
  165. /// <param name="outputFilePath">The output file path.</param>
  166. protected override void DeletePartialStreamFiles(string outputFilePath)
  167. {
  168. var directory = Path.GetDirectoryName(outputFilePath);
  169. var name = Path.GetFileNameWithoutExtension(outputFilePath);
  170. var filesToDelete = Directory.EnumerateFiles(directory, "*", SearchOption.TopDirectoryOnly)
  171. .Where(f => f.IndexOf(name, StringComparison.OrdinalIgnoreCase) != -1)
  172. .ToList();
  173. foreach (var file in filesToDelete)
  174. {
  175. try
  176. {
  177. Logger.Info("Deleting HLS file {0}", file);
  178. File.Delete(file);
  179. }
  180. catch (IOException ex)
  181. {
  182. Logger.ErrorException("Error deleting HLS file {0}", ex, file);
  183. }
  184. }
  185. }
  186. }
  187. }