BaseHlsService.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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. // fix this to make the media stream validator happy
  117. // https://ffmpeg.org/trac/ffmpeg/ticket/2228
  118. fileText = fileText.Replace("#EXT-X-ALLOWCACHE", "#EXT-X-ALLOW-CACHE");
  119. // Add event type at the top
  120. fileText = fileText.Replace("#EXT-X-ALLOW-CACHE", "#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 probeSize = Kernel.Instance.FFMpegManager.GetProbeSizeArgument(state.Item);
  153. const string keyFrameArg = " -force_key_frames expr:if(isnan(prev_forced_t),gte(t,0),gte(t,prev_forced_t+5))";
  154. return string.Format("{0} {1} -i {2}{3} -threads 0 {4} {5} {6}{7} -f ssegment -segment_list_flags +live -segment_time 10 -segment_list \"{8}\" \"{9}\"",
  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. keyFrameArg,
  163. outputPath,
  164. segmentOutputPath
  165. ).Trim();
  166. }
  167. /// <summary>
  168. /// Deletes the partial stream files.
  169. /// </summary>
  170. /// <param name="outputFilePath">The output file path.</param>
  171. protected override void DeletePartialStreamFiles(string outputFilePath)
  172. {
  173. var directory = Path.GetDirectoryName(outputFilePath);
  174. var name = Path.GetFileNameWithoutExtension(outputFilePath);
  175. var filesToDelete = Directory.EnumerateFiles(directory, "*", SearchOption.TopDirectoryOnly)
  176. .Where(f => f.IndexOf(name, StringComparison.OrdinalIgnoreCase) != -1)
  177. .ToList();
  178. foreach (var file in filesToDelete)
  179. {
  180. try
  181. {
  182. Logger.Info("Deleting HLS file {0}", file);
  183. File.Delete(file);
  184. }
  185. catch (IOException ex)
  186. {
  187. Logger.ErrorException("Error deleting HLS file {0}", ex, file);
  188. }
  189. }
  190. }
  191. }
  192. }