DynamicHlsService.cs 21 KB

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