DynamicHlsService.cs 21 KB

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