DynamicHlsService.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Controller.Channels;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Dlna;
  5. using MediaBrowser.Controller.Library;
  6. using MediaBrowser.Controller.LiveTv;
  7. using MediaBrowser.Controller.MediaEncoding;
  8. using MediaBrowser.Model.IO;
  9. using ServiceStack;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Globalization;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Text;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. namespace MediaBrowser.Api.Playback.Hls
  19. {
  20. [Route("/Videos/{Id}/master.m3u8", "GET")]
  21. [Api(Description = "Gets a video stream using HTTP live streaming.")]
  22. public class GetMasterHlsVideoStream : VideoStreamRequest
  23. {
  24. }
  25. [Route("/Videos/{Id}/main.m3u8", "GET")]
  26. [Api(Description = "Gets a video stream using HTTP live streaming.")]
  27. public class GetMainHlsVideoStream : VideoStreamRequest
  28. {
  29. }
  30. /// <summary>
  31. /// Class GetHlsVideoSegment
  32. /// </summary>
  33. [Route("/Videos/{Id}/hlsdynamic/{PlaylistId}/{SegmentId}.ts", "GET")]
  34. [Api(Description = "Gets an Http live streaming segment file. Internal use only.")]
  35. public class GetDynamicHlsVideoSegment : VideoStreamRequest
  36. {
  37. public string PlaylistId { get; set; }
  38. /// <summary>
  39. /// Gets or sets the segment id.
  40. /// </summary>
  41. /// <value>The segment id.</value>
  42. public string SegmentId { get; set; }
  43. }
  44. public class DynamicHlsService : BaseHlsService
  45. {
  46. public DynamicHlsService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, ILiveTvManager liveTvManager, IDlnaManager dlnaManager, IChannelManager channelManager, ISubtitleEncoder subtitleEncoder)
  47. : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, liveTvManager, dlnaManager, channelManager, subtitleEncoder)
  48. {
  49. }
  50. public object Get(GetMasterHlsVideoStream request)
  51. {
  52. var result = GetAsync(request).Result;
  53. return result;
  54. }
  55. public object Get(GetMainHlsVideoStream request)
  56. {
  57. var result = GetPlaylistAsync(request, "main").Result;
  58. // Get the transcoding started
  59. //var start = GetStartNumber(request);
  60. //var segment = GetDynamicSegment(request, start.ToString(UsCulture)).Result;
  61. return result;
  62. }
  63. public object Get(GetDynamicHlsVideoSegment request)
  64. {
  65. return GetDynamicSegment(request, request.SegmentId).Result;
  66. }
  67. private async Task<object> GetDynamicSegment(VideoStreamRequest request, string segmentId)
  68. {
  69. if ((request.StartTimeTicks ?? 0) > 0)
  70. {
  71. throw new ArgumentException("StartTimeTicks is not allowed.");
  72. }
  73. var cancellationTokenSource = new CancellationTokenSource();
  74. var cancellationToken = cancellationTokenSource.Token;
  75. var index = int.Parse(segmentId, NumberStyles.Integer, UsCulture);
  76. var state = await GetState(request, cancellationToken).ConfigureAwait(false);
  77. var playlistPath = Path.ChangeExtension(state.OutputFilePath, ".m3u8");
  78. var segmentPath = GetSegmentPath(playlistPath, index);
  79. if (File.Exists(segmentPath))
  80. {
  81. ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType.Hls);
  82. return await GetSegmentResult(playlistPath, segmentPath, index, cancellationToken).ConfigureAwait(false);
  83. }
  84. await ApiEntryPoint.Instance.TranscodingStartLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);
  85. try
  86. {
  87. if (File.Exists(segmentPath))
  88. {
  89. ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType.Hls);
  90. return await GetSegmentResult(playlistPath, segmentPath, index, cancellationToken).ConfigureAwait(false);
  91. }
  92. else
  93. {
  94. var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath);
  95. if (currentTranscodingIndex == null || index < currentTranscodingIndex.Value || (index - currentTranscodingIndex.Value) > 4)
  96. {
  97. // If the playlist doesn't already exist, startup ffmpeg
  98. try
  99. {
  100. // TODO: Delete files from other jobs, but not this one
  101. await ApiEntryPoint.Instance.KillTranscodingJobs(state.Request.DeviceId, TranscodingJobType.Hls, FileDeleteMode.None, false).ConfigureAwait(false);
  102. if (currentTranscodingIndex.HasValue)
  103. {
  104. DeleteLastFile(playlistPath, 0);
  105. }
  106. var startSeconds = index * state.SegmentLength;
  107. request.StartTimeTicks = TimeSpan.FromSeconds(startSeconds).Ticks;
  108. await StartFfMpeg(state, playlistPath, cancellationTokenSource).ConfigureAwait(false);
  109. }
  110. catch
  111. {
  112. state.Dispose();
  113. throw;
  114. }
  115. await WaitForMinimumSegmentCount(playlistPath, 1, cancellationTokenSource.Token).ConfigureAwait(false);
  116. }
  117. }
  118. }
  119. finally
  120. {
  121. ApiEntryPoint.Instance.TranscodingStartLock.Release();
  122. }
  123. Logger.Info("waiting for {0}", segmentPath);
  124. while (!File.Exists(segmentPath))
  125. {
  126. await Task.Delay(50, cancellationToken).ConfigureAwait(false);
  127. }
  128. Logger.Info("returning {0}", segmentPath);
  129. return await GetSegmentResult(playlistPath, segmentPath, index, cancellationToken).ConfigureAwait(false);
  130. }
  131. public int? GetCurrentTranscodingIndex(string playlist)
  132. {
  133. var file = GetLastTranscodingFile(playlist, FileSystem);
  134. if (file == null)
  135. {
  136. return null;
  137. }
  138. var playlistFilename = Path.GetFileNameWithoutExtension(playlist);
  139. var indexString = Path.GetFileNameWithoutExtension(file.Name).Substring(playlistFilename.Length);
  140. return int.Parse(indexString, NumberStyles.Integer, UsCulture);
  141. }
  142. private void DeleteLastFile(string path, int retryCount)
  143. {
  144. if (retryCount >= 5)
  145. {
  146. return;
  147. }
  148. var file = GetLastTranscodingFile(path, FileSystem);
  149. if (file != null)
  150. {
  151. try
  152. {
  153. File.Delete(file.FullName);
  154. }
  155. catch (IOException ex)
  156. {
  157. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, file.FullName);
  158. Thread.Sleep(100);
  159. DeleteLastFile(path, retryCount + 1);
  160. }
  161. catch (Exception ex)
  162. {
  163. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, file.FullName);
  164. }
  165. }
  166. }
  167. private static FileInfo GetLastTranscodingFile(string playlist, IFileSystem fileSystem)
  168. {
  169. var folder = Path.GetDirectoryName(playlist);
  170. try
  171. {
  172. return new DirectoryInfo(folder)
  173. .EnumerateFiles("*", SearchOption.TopDirectoryOnly)
  174. .Where(i => string.Equals(i.Extension, ".ts", StringComparison.OrdinalIgnoreCase))
  175. .OrderByDescending(fileSystem.GetLastWriteTimeUtc)
  176. .FirstOrDefault();
  177. }
  178. catch (DirectoryNotFoundException)
  179. {
  180. return null;
  181. }
  182. }
  183. protected override int GetStartNumber(StreamState state)
  184. {
  185. return GetStartNumber(state.VideoRequest);
  186. }
  187. private int GetStartNumber(VideoStreamRequest request)
  188. {
  189. var segmentId = "0";
  190. var segmentRequest = request as GetDynamicHlsVideoSegment;
  191. if (segmentRequest != null)
  192. {
  193. segmentId = segmentRequest.SegmentId;
  194. }
  195. return int.Parse(segmentId, NumberStyles.Integer, UsCulture);
  196. }
  197. private string GetSegmentPath(string playlist, int index)
  198. {
  199. var folder = Path.GetDirectoryName(playlist);
  200. var filename = Path.GetFileNameWithoutExtension(playlist);
  201. return Path.Combine(folder, filename + index.ToString(UsCulture) + ".ts");
  202. }
  203. private async Task<object> GetSegmentResult(string playlistPath, string segmentPath, int segmentIndex, CancellationToken cancellationToken)
  204. {
  205. // If all transcoding has completed, just return immediately
  206. if (!IsTranscoding(playlistPath))
  207. {
  208. return ResultFactory.GetStaticFileResult(Request, segmentPath, FileShare.ReadWrite);
  209. }
  210. var segmentFilename = Path.GetFileName(segmentPath);
  211. // If it appears in the playlist, it's done
  212. if (File.ReadAllText(playlistPath).IndexOf(segmentFilename, StringComparison.OrdinalIgnoreCase) != -1)
  213. {
  214. return ResultFactory.GetStaticFileResult(Request, segmentPath, FileShare.ReadWrite);
  215. }
  216. // if a different file is encoding, it's done
  217. //var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath);
  218. //if (currentTranscodingIndex > segmentIndex)
  219. //{
  220. // return ResultFactory.GetStaticFileResult(Request, segmentPath, FileShare.ReadWrite);
  221. //}
  222. // Wait for the file to stop being written to, then stream it
  223. var length = new FileInfo(segmentPath).Length;
  224. var eofCount = 0;
  225. while (eofCount < 10)
  226. {
  227. var info = new FileInfo(segmentPath);
  228. if (!info.Exists)
  229. {
  230. break;
  231. }
  232. var newLength = info.Length;
  233. if (newLength == length)
  234. {
  235. eofCount++;
  236. }
  237. else
  238. {
  239. eofCount = 0;
  240. }
  241. length = newLength;
  242. await Task.Delay(100, cancellationToken).ConfigureAwait(false);
  243. }
  244. return ResultFactory.GetStaticFileResult(Request, segmentPath, FileShare.ReadWrite);
  245. }
  246. private bool IsTranscoding(string playlistPath)
  247. {
  248. var job = ApiEntryPoint.Instance.GetTranscodingJob(playlistPath, TranscodingJobType);
  249. return job != null && !job.HasExited;
  250. }
  251. private async Task<object> GetAsync(GetMasterHlsVideoStream request)
  252. {
  253. var state = await GetState(request, CancellationToken.None).ConfigureAwait(false);
  254. var audioBitrate = state.OutputAudioBitrate ?? 0;
  255. var videoBitrate = state.OutputVideoBitrate ?? 0;
  256. var playlistText = GetMasterPlaylistFileText(state, videoBitrate + audioBitrate);
  257. return ResultFactory.GetResult(playlistText, Common.Net.MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary<string, string>());
  258. }
  259. private string GetMasterPlaylistFileText(StreamState state, int totalBitrate)
  260. {
  261. var builder = new StringBuilder();
  262. builder.AppendLine("#EXTM3U");
  263. var queryStringIndex = Request.RawUrl.IndexOf('?');
  264. var queryString = queryStringIndex == -1 ? string.Empty : Request.RawUrl.Substring(queryStringIndex);
  265. // Main stream
  266. var playlistUrl = (state.RunTimeTicks ?? 0) > 0 ? "main.m3u8" : "live.m3u8";
  267. playlistUrl += queryString;
  268. AppendPlaylist(builder, playlistUrl, totalBitrate);
  269. if (state.VideoRequest.VideoBitRate.HasValue)
  270. {
  271. var requestedVideoBitrate = state.VideoRequest.VideoBitRate.Value;
  272. // By default, vary by just 200k
  273. var variation = GetBitrateVariation(totalBitrate);
  274. var newBitrate = totalBitrate - variation;
  275. AppendPlaylist(builder, playlistUrl.Replace(requestedVideoBitrate.ToString(UsCulture), (requestedVideoBitrate - variation).ToString(UsCulture)), newBitrate);
  276. variation *= 2;
  277. newBitrate = totalBitrate - variation;
  278. AppendPlaylist(builder, playlistUrl.Replace(requestedVideoBitrate.ToString(UsCulture), (requestedVideoBitrate - variation).ToString(UsCulture)), newBitrate);
  279. }
  280. return builder.ToString();
  281. }
  282. private void AppendPlaylist(StringBuilder builder, string url, int bitrate)
  283. {
  284. builder.AppendLine("#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=" + bitrate.ToString(UsCulture));
  285. builder.AppendLine(url);
  286. }
  287. private int GetBitrateVariation(int bitrate)
  288. {
  289. // By default, vary by just 200k
  290. var variation = 200000;
  291. if (bitrate >= 10000000)
  292. {
  293. variation = 2000000;
  294. }
  295. else if (bitrate >= 5000000)
  296. {
  297. variation = 1500000;
  298. }
  299. else if (bitrate >= 3000000)
  300. {
  301. variation = 1000000;
  302. }
  303. else if (bitrate >= 2000000)
  304. {
  305. variation = 500000;
  306. }
  307. else if (bitrate >= 1000000)
  308. {
  309. variation = 300000;
  310. }
  311. return variation;
  312. }
  313. private async Task<object> GetPlaylistAsync(VideoStreamRequest request, string name)
  314. {
  315. var state = await GetState(request, CancellationToken.None).ConfigureAwait(false);
  316. var builder = new StringBuilder();
  317. builder.AppendLine("#EXTM3U");
  318. builder.AppendLine("#EXT-X-VERSION:3");
  319. builder.AppendLine("#EXT-X-TARGETDURATION:" + state.SegmentLength.ToString(UsCulture));
  320. builder.AppendLine("#EXT-X-MEDIA-SEQUENCE:0");
  321. builder.AppendLine("#EXT-X-ALLOW-CACHE:NO");
  322. var queryStringIndex = Request.RawUrl.IndexOf('?');
  323. var queryString = queryStringIndex == -1 ? string.Empty : Request.RawUrl.Substring(queryStringIndex);
  324. var seconds = TimeSpan.FromTicks(state.RunTimeTicks ?? 0).TotalSeconds;
  325. var index = 0;
  326. while (seconds > 0)
  327. {
  328. var length = seconds >= state.SegmentLength ? state.SegmentLength : seconds;
  329. builder.AppendLine("#EXTINF:" + length.ToString(UsCulture) + ",");
  330. builder.AppendLine(string.Format("hlsdynamic/{0}/{1}.ts{2}",
  331. name,
  332. index.ToString(UsCulture),
  333. queryString));
  334. seconds -= state.SegmentLength;
  335. index++;
  336. }
  337. builder.AppendLine("#EXT-X-ENDLIST");
  338. var playlistText = builder.ToString();
  339. return ResultFactory.GetResult(playlistText, Common.Net.MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary<string, string>());
  340. }
  341. protected override string GetAudioArguments(StreamState state)
  342. {
  343. var codec = state.OutputAudioCodec;
  344. if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
  345. {
  346. return "-codec:a:0 copy";
  347. }
  348. var args = "-codec:a:0 " + codec;
  349. var channels = state.OutputAudioChannels;
  350. if (channels.HasValue)
  351. {
  352. args += " -ac " + channels.Value;
  353. }
  354. var bitrate = state.OutputAudioBitrate;
  355. if (bitrate.HasValue)
  356. {
  357. args += " -ab " + bitrate.Value.ToString(UsCulture);
  358. }
  359. args += " " + GetAudioFilterParam(state, true);
  360. return args;
  361. }
  362. protected override string GetVideoArguments(StreamState state)
  363. {
  364. var codec = state.OutputVideoCodec;
  365. // See if we can save come cpu cycles by avoiding encoding
  366. if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
  367. {
  368. // TOOD: Switch to -bsf dump_extra?
  369. return IsH264(state.VideoStream) ? "-codec:v:0 copy -bsf h264_mp4toannexb" : "-codec:v:0 copy";
  370. }
  371. var keyFrameArg = string.Format(" -force_key_frames expr:gte(t,n_forced*{0})",
  372. state.SegmentLength.ToString(UsCulture));
  373. var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream;
  374. var args = "-codec:v:0 " + codec + " " + GetVideoQualityParam(state, "libx264", true) + keyFrameArg;
  375. // Add resolution params, if specified
  376. if (!hasGraphicalSubs)
  377. {
  378. args += GetOutputSizeParam(state, codec, CancellationToken.None);
  379. }
  380. // This is for internal graphical subs
  381. if (hasGraphicalSubs)
  382. {
  383. args += GetInternalGraphicalSubtitleParam(state, codec);
  384. }
  385. return args;
  386. }
  387. /// <summary>
  388. /// Gets the command line arguments.
  389. /// </summary>
  390. /// <param name="outputPath">The output path.</param>
  391. /// <param name="state">The state.</param>
  392. /// <param name="isEncoding">if set to <c>true</c> [is encoding].</param>
  393. /// <returns>System.String.</returns>
  394. protected override string GetCommandLineArguments(string outputPath, StreamState state, bool isEncoding)
  395. {
  396. var threads = GetNumberOfThreads(state, false);
  397. var inputModifier = GetInputModifier(state);
  398. // If isEncoding is true we're actually starting ffmpeg
  399. var startNumberParam = isEncoding ? GetStartNumber(state).ToString(UsCulture) : "0";
  400. var args = string.Format("{0} -i {1} -map_metadata -1 -threads {2} {3} {4} -flags -global_header {5} -hls_time {6} -start_number {7} -hls_list_size {8} -y \"{9}\"",
  401. inputModifier,
  402. GetInputArgument(state),
  403. threads,
  404. GetMapArgs(state),
  405. GetVideoArguments(state),
  406. GetAudioArguments(state),
  407. state.SegmentLength.ToString(UsCulture),
  408. startNumberParam,
  409. state.HlsListSize.ToString(UsCulture),
  410. outputPath
  411. ).Trim();
  412. return args;
  413. }
  414. /// <summary>
  415. /// Gets the segment file extension.
  416. /// </summary>
  417. /// <param name="state">The state.</param>
  418. /// <returns>System.String.</returns>
  419. protected override string GetSegmentFileExtension(StreamState state)
  420. {
  421. return ".ts";
  422. }
  423. protected override TranscodingJobType TranscodingJobType
  424. {
  425. get
  426. {
  427. return TranscodingJobType.Hls;
  428. }
  429. }
  430. }
  431. }