DynamicHlsService.cs 20 KB

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