DynamicHlsService.cs 20 KB

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