DynamicHlsService.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Devices;
  5. using MediaBrowser.Controller.Dlna;
  6. using MediaBrowser.Controller.Library;
  7. using MediaBrowser.Controller.MediaEncoding;
  8. using MediaBrowser.Controller.Net;
  9. using MediaBrowser.Model.Dlna;
  10. using MediaBrowser.Model.Entities;
  11. using MediaBrowser.Model.Extensions;
  12. using MediaBrowser.Model.IO;
  13. using MediaBrowser.Model.Serialization;
  14. using ServiceStack;
  15. using System;
  16. using System.Collections.Concurrent;
  17. using System.Collections.Generic;
  18. using System.Globalization;
  19. using System.IO;
  20. using System.Linq;
  21. using System.Text;
  22. using System.Threading;
  23. using System.Threading.Tasks;
  24. using MimeTypes = MediaBrowser.Model.Net.MimeTypes;
  25. namespace MediaBrowser.Api.Playback.Hls
  26. {
  27. /// <summary>
  28. /// Options is needed for chromecast. Threw Head in there since it's related
  29. /// </summary>
  30. [Route("/Videos/{Id}/master.m3u8", "GET", Summary = "Gets a video stream using HTTP live streaming.")]
  31. [Route("/Videos/{Id}/master.m3u8", "HEAD", Summary = "Gets a video stream using HTTP live streaming.")]
  32. public class GetMasterHlsVideoPlaylist : VideoStreamRequest, IMasterHlsRequest
  33. {
  34. public bool EnableAdaptiveBitrateStreaming { get; set; }
  35. public GetMasterHlsVideoPlaylist()
  36. {
  37. EnableAdaptiveBitrateStreaming = true;
  38. }
  39. }
  40. [Route("/Audio/{Id}/master.m3u8", "GET", Summary = "Gets an audio stream using HTTP live streaming.")]
  41. [Route("/Audio/{Id}/master.m3u8", "HEAD", Summary = "Gets an audio stream using HTTP live streaming.")]
  42. public class GetMasterHlsAudioPlaylist : StreamRequest, IMasterHlsRequest
  43. {
  44. public bool EnableAdaptiveBitrateStreaming { get; set; }
  45. public GetMasterHlsAudioPlaylist()
  46. {
  47. EnableAdaptiveBitrateStreaming = true;
  48. }
  49. }
  50. public interface IMasterHlsRequest
  51. {
  52. bool EnableAdaptiveBitrateStreaming { get; set; }
  53. }
  54. [Route("/Videos/{Id}/main.m3u8", "GET", Summary = "Gets a video stream using HTTP live streaming.")]
  55. public class GetVariantHlsVideoPlaylist : VideoStreamRequest
  56. {
  57. }
  58. [Route("/Audio/{Id}/main.m3u8", "GET", Summary = "Gets an audio stream using HTTP live streaming.")]
  59. public class GetVariantHlsAudioPlaylist : StreamRequest
  60. {
  61. }
  62. [Route("/Videos/{Id}/hlsdynamic/{PlaylistId}/{SegmentId}.ts", "GET")]
  63. [Api(Description = "Gets an Http live streaming segment file. Internal use only.")]
  64. public class GetHlsVideoSegment : VideoStreamRequest
  65. {
  66. public string PlaylistId { get; set; }
  67. /// <summary>
  68. /// Gets or sets the segment id.
  69. /// </summary>
  70. /// <value>The segment id.</value>
  71. public string SegmentId { get; set; }
  72. }
  73. [Route("/Audio/{Id}/hlsdynamic/{PlaylistId}/{SegmentId}.aac", "GET")]
  74. [Route("/Audio/{Id}/hlsdynamic/{PlaylistId}/{SegmentId}.ts", "GET")]
  75. [Api(Description = "Gets an Http live streaming segment file. Internal use only.")]
  76. public class GetHlsAudioSegment : StreamRequest
  77. {
  78. public string PlaylistId { get; set; }
  79. /// <summary>
  80. /// Gets or sets the segment id.
  81. /// </summary>
  82. /// <value>The segment id.</value>
  83. public string SegmentId { get; set; }
  84. }
  85. public class DynamicHlsService : BaseHlsService
  86. {
  87. public DynamicHlsService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, IDlnaManager dlnaManager, ISubtitleEncoder subtitleEncoder, IDeviceManager deviceManager, IMediaSourceManager mediaSourceManager, IZipClient zipClient, IJsonSerializer jsonSerializer, INetworkManager networkManager)
  88. : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, dlnaManager, subtitleEncoder, deviceManager, mediaSourceManager, zipClient, jsonSerializer)
  89. {
  90. NetworkManager = networkManager;
  91. }
  92. protected INetworkManager NetworkManager { get; private set; }
  93. public Task<object> Get(GetMasterHlsVideoPlaylist request)
  94. {
  95. return GetMasterPlaylistInternal(request, "GET");
  96. }
  97. public Task<object> Head(GetMasterHlsVideoPlaylist request)
  98. {
  99. return GetMasterPlaylistInternal(request, "HEAD");
  100. }
  101. public Task<object> Get(GetMasterHlsAudioPlaylist request)
  102. {
  103. return GetMasterPlaylistInternal(request, "GET");
  104. }
  105. public Task<object> Head(GetMasterHlsAudioPlaylist request)
  106. {
  107. return GetMasterPlaylistInternal(request, "HEAD");
  108. }
  109. public Task<object> Get(GetVariantHlsVideoPlaylist request)
  110. {
  111. return GetVariantPlaylistInternal(request, true, "main");
  112. }
  113. public Task<object> Get(GetVariantHlsAudioPlaylist request)
  114. {
  115. return GetVariantPlaylistInternal(request, false, "main");
  116. }
  117. public Task<object> Get(GetHlsVideoSegment request)
  118. {
  119. return GetDynamicSegment(request, request.SegmentId);
  120. }
  121. public Task<object> Get(GetHlsAudioSegment request)
  122. {
  123. return GetDynamicSegment(request, request.SegmentId);
  124. }
  125. private async Task<object> GetDynamicSegment(StreamRequest request, string segmentId)
  126. {
  127. if ((request.StartTimeTicks ?? 0) > 0)
  128. {
  129. throw new ArgumentException("StartTimeTicks is not allowed.");
  130. }
  131. var cancellationTokenSource = new CancellationTokenSource();
  132. var cancellationToken = cancellationTokenSource.Token;
  133. var requestedIndex = int.Parse(segmentId, NumberStyles.Integer, UsCulture);
  134. var state = await GetState(request, cancellationToken).ConfigureAwait(false);
  135. var playlistPath = Path.ChangeExtension(state.OutputFilePath, ".m3u8");
  136. var segmentPath = GetSegmentPath(state, playlistPath, requestedIndex);
  137. var segmentLength = state.SegmentLength;
  138. var segmentExtension = GetSegmentFileExtension(state);
  139. TranscodingJob job = null;
  140. if (File.Exists(segmentPath))
  141. {
  142. job = ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
  143. return await GetSegmentResult(playlistPath, segmentPath, requestedIndex, segmentLength, job, cancellationToken).ConfigureAwait(false);
  144. }
  145. await ApiEntryPoint.Instance.TranscodingStartLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);
  146. try
  147. {
  148. if (File.Exists(segmentPath))
  149. {
  150. job = ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
  151. return await GetSegmentResult(playlistPath, segmentPath, requestedIndex, segmentLength, job, cancellationToken).ConfigureAwait(false);
  152. }
  153. else
  154. {
  155. var startTranscoding = false;
  156. var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath, segmentExtension);
  157. var segmentGapRequiringTranscodingChange = 24 / state.SegmentLength;
  158. if (currentTranscodingIndex == null)
  159. {
  160. Logger.Debug("Starting transcoding because currentTranscodingIndex=null");
  161. startTranscoding = true;
  162. }
  163. else if (requestedIndex < currentTranscodingIndex.Value)
  164. {
  165. Logger.Debug("Starting transcoding because requestedIndex={0} and currentTranscodingIndex={1}", requestedIndex, currentTranscodingIndex);
  166. startTranscoding = true;
  167. }
  168. else if ((requestedIndex - currentTranscodingIndex.Value) > segmentGapRequiringTranscodingChange)
  169. {
  170. Logger.Debug("Starting transcoding because segmentGap is {0} and max allowed gap is {1}. requestedIndex={2}", (requestedIndex - currentTranscodingIndex.Value), segmentGapRequiringTranscodingChange, requestedIndex);
  171. startTranscoding = true;
  172. }
  173. if (startTranscoding)
  174. {
  175. // If the playlist doesn't already exist, startup ffmpeg
  176. try
  177. {
  178. ApiEntryPoint.Instance.KillTranscodingJobs(request.DeviceId, request.PlaySessionId, p => false);
  179. await ReadSegmentLengths(playlistPath).ConfigureAwait(false);
  180. if (currentTranscodingIndex.HasValue)
  181. {
  182. DeleteLastFile(playlistPath, segmentExtension, 0);
  183. }
  184. request.StartTimeTicks = GetSeekPositionTicks(state, playlistPath, requestedIndex);
  185. job = await StartFfMpeg(state, playlistPath, cancellationTokenSource).ConfigureAwait(false);
  186. }
  187. catch
  188. {
  189. state.Dispose();
  190. throw;
  191. }
  192. //await WaitForMinimumSegmentCount(playlistPath, 1, cancellationTokenSource.Token).ConfigureAwait(false);
  193. }
  194. else
  195. {
  196. job = ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
  197. if (job.TranscodingThrottler != null)
  198. {
  199. job.TranscodingThrottler.UnpauseTranscoding();
  200. }
  201. }
  202. }
  203. }
  204. finally
  205. {
  206. ApiEntryPoint.Instance.TranscodingStartLock.Release();
  207. }
  208. //Logger.Info("waiting for {0}", segmentPath);
  209. //while (!File.Exists(segmentPath))
  210. //{
  211. // await Task.Delay(50, cancellationToken).ConfigureAwait(false);
  212. //}
  213. Logger.Info("returning {0}", segmentPath);
  214. job = job ?? ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
  215. return await GetSegmentResult(playlistPath, segmentPath, requestedIndex, segmentLength, job, cancellationToken).ConfigureAwait(false);
  216. }
  217. private static readonly ConcurrentDictionary<string, double> SegmentLengths = new ConcurrentDictionary<string, double>(StringComparer.OrdinalIgnoreCase);
  218. private async Task ReadSegmentLengths(string playlist)
  219. {
  220. try
  221. {
  222. using (var fileStream = GetPlaylistFileStream(playlist))
  223. {
  224. using (var reader = new StreamReader(fileStream))
  225. {
  226. double duration = -1;
  227. while (!reader.EndOfStream)
  228. {
  229. var text = await reader.ReadLineAsync().ConfigureAwait(false);
  230. if (text.StartsWith("#EXTINF", StringComparison.OrdinalIgnoreCase))
  231. {
  232. var parts = text.Split(new[] { ':' }, 2);
  233. if (parts.Length == 2)
  234. {
  235. var time = parts[1].Trim(new[] { ',' }).Trim();
  236. double timeValue;
  237. if (double.TryParse(time, NumberStyles.Any, CultureInfo.InvariantCulture, out timeValue))
  238. {
  239. duration = timeValue;
  240. continue;
  241. }
  242. }
  243. }
  244. else if (duration != -1)
  245. {
  246. SegmentLengths.AddOrUpdate(text, duration, (k, v) => duration);
  247. Logger.Debug("Added segment length of {0} for {1}", duration, text);
  248. }
  249. duration = -1;
  250. }
  251. }
  252. }
  253. }
  254. catch (DirectoryNotFoundException)
  255. {
  256. }
  257. catch (FileNotFoundException)
  258. {
  259. }
  260. }
  261. private long GetSeekPositionTicks(StreamState state, string playlist, int requestedIndex)
  262. {
  263. double startSeconds = 0;
  264. for (var i = 0; i < requestedIndex; i++)
  265. {
  266. var segmentPath = GetSegmentPath(state, playlist, i);
  267. double length;
  268. if (SegmentLengths.TryGetValue(Path.GetFileName(segmentPath), out length))
  269. {
  270. Logger.Debug("Found segment length of {0} for index {1}", length, i);
  271. startSeconds += length;
  272. }
  273. else
  274. {
  275. startSeconds += state.SegmentLength;
  276. }
  277. }
  278. var position = TimeSpan.FromSeconds(startSeconds).Ticks;
  279. return position;
  280. }
  281. public int? GetCurrentTranscodingIndex(string playlist, string segmentExtension)
  282. {
  283. var job = ApiEntryPoint.Instance.GetTranscodingJob(playlist, TranscodingJobType);
  284. if (job == null || job.HasExited)
  285. {
  286. return null;
  287. }
  288. var file = GetLastTranscodingFile(playlist, segmentExtension, FileSystem);
  289. if (file == null)
  290. {
  291. return null;
  292. }
  293. var playlistFilename = Path.GetFileNameWithoutExtension(playlist);
  294. var indexString = Path.GetFileNameWithoutExtension(file.Name).Substring(playlistFilename.Length);
  295. return int.Parse(indexString, NumberStyles.Integer, UsCulture);
  296. }
  297. private void DeleteLastFile(string playlistPath, string segmentExtension, int retryCount)
  298. {
  299. var file = GetLastTranscodingFile(playlistPath, segmentExtension, FileSystem);
  300. if (file != null)
  301. {
  302. DeleteFile(file, retryCount);
  303. }
  304. }
  305. private void DeleteFile(FileInfo file, int retryCount)
  306. {
  307. if (retryCount >= 5)
  308. {
  309. return;
  310. }
  311. try
  312. {
  313. FileSystem.DeleteFile(file.FullName);
  314. }
  315. catch (IOException ex)
  316. {
  317. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, file.FullName);
  318. Thread.Sleep(100);
  319. DeleteFile(file, retryCount + 1);
  320. }
  321. catch (Exception ex)
  322. {
  323. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, file.FullName);
  324. }
  325. }
  326. private static FileInfo GetLastTranscodingFile(string playlist, string segmentExtension, IFileSystem fileSystem)
  327. {
  328. var folder = Path.GetDirectoryName(playlist);
  329. var filePrefix = Path.GetFileNameWithoutExtension(playlist) ?? string.Empty;
  330. try
  331. {
  332. return new DirectoryInfo(folder)
  333. .EnumerateFiles("*", SearchOption.TopDirectoryOnly)
  334. .Where(i => string.Equals(i.Extension, segmentExtension, StringComparison.OrdinalIgnoreCase) && Path.GetFileNameWithoutExtension(i.Name).StartsWith(filePrefix, StringComparison.OrdinalIgnoreCase))
  335. .OrderByDescending(fileSystem.GetLastWriteTimeUtc)
  336. .FirstOrDefault();
  337. }
  338. catch (DirectoryNotFoundException)
  339. {
  340. return null;
  341. }
  342. }
  343. protected override int GetStartNumber(StreamState state)
  344. {
  345. return GetStartNumber(state.VideoRequest);
  346. }
  347. private int GetStartNumber(VideoStreamRequest request)
  348. {
  349. var segmentId = "0";
  350. var segmentRequest = request as GetHlsVideoSegment;
  351. if (segmentRequest != null)
  352. {
  353. segmentId = segmentRequest.SegmentId;
  354. }
  355. return int.Parse(segmentId, NumberStyles.Integer, UsCulture);
  356. }
  357. private string GetSegmentPath(StreamState state, string playlist, int index)
  358. {
  359. var folder = Path.GetDirectoryName(playlist);
  360. var filename = Path.GetFileNameWithoutExtension(playlist);
  361. return Path.Combine(folder, filename + index.ToString(UsCulture) + GetSegmentFileExtension(state));
  362. }
  363. private async Task<object> GetSegmentResult(string playlistPath,
  364. string segmentPath,
  365. int segmentIndex,
  366. int segmentLength,
  367. TranscodingJob transcodingJob,
  368. CancellationToken cancellationToken)
  369. {
  370. // If all transcoding has completed, just return immediately
  371. if (transcodingJob != null && transcodingJob.HasExited)
  372. {
  373. return GetSegmentResult(segmentPath, segmentIndex, segmentLength, transcodingJob);
  374. }
  375. var segmentFilename = Path.GetFileName(segmentPath);
  376. while (!cancellationToken.IsCancellationRequested)
  377. {
  378. try
  379. {
  380. using (var fileStream = GetPlaylistFileStream(playlistPath))
  381. {
  382. using (var reader = new StreamReader(fileStream))
  383. {
  384. while (!reader.EndOfStream)
  385. {
  386. var text = await reader.ReadLineAsync().ConfigureAwait(false);
  387. // If it appears in the playlist, it's done
  388. if (text.IndexOf(segmentFilename, StringComparison.OrdinalIgnoreCase) != -1)
  389. {
  390. return GetSegmentResult(segmentPath, segmentIndex, segmentLength, transcodingJob);
  391. }
  392. }
  393. }
  394. }
  395. }
  396. catch (IOException)
  397. {
  398. // May get an error if the file is locked
  399. }
  400. await Task.Delay(100, cancellationToken).ConfigureAwait(false);
  401. }
  402. // if a different file is encoding, it's done
  403. //var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath);
  404. //if (currentTranscodingIndex > segmentIndex)
  405. //{
  406. //return GetSegmentResult(segmentPath, segmentIndex);
  407. //}
  408. //// Wait for the file to stop being written to, then stream it
  409. //var length = new FileInfo(segmentPath).Length;
  410. //var eofCount = 0;
  411. //while (eofCount < 10)
  412. //{
  413. // var info = new FileInfo(segmentPath);
  414. // if (!info.Exists)
  415. // {
  416. // break;
  417. // }
  418. // var newLength = info.Length;
  419. // if (newLength == length)
  420. // {
  421. // eofCount++;
  422. // }
  423. // else
  424. // {
  425. // eofCount = 0;
  426. // }
  427. // length = newLength;
  428. // await Task.Delay(100, cancellationToken).ConfigureAwait(false);
  429. //}
  430. cancellationToken.ThrowIfCancellationRequested();
  431. return GetSegmentResult(segmentPath, segmentIndex, segmentLength, transcodingJob);
  432. }
  433. private object GetSegmentResult(string segmentPath, int index, int segmentLength, TranscodingJob transcodingJob)
  434. {
  435. var segmentEndingSeconds = (1 + index) * segmentLength;
  436. var segmentEndingPositionTicks = TimeSpan.FromSeconds(segmentEndingSeconds).Ticks;
  437. return ResultFactory.GetStaticFileResult(Request, new StaticFileResultOptions
  438. {
  439. Path = segmentPath,
  440. FileShare = FileShare.ReadWrite,
  441. OnComplete = () =>
  442. {
  443. if (transcodingJob != null)
  444. {
  445. transcodingJob.DownloadPositionTicks = Math.Max(transcodingJob.DownloadPositionTicks ?? segmentEndingPositionTicks, segmentEndingPositionTicks);
  446. ApiEntryPoint.Instance.OnTranscodeEndRequest(transcodingJob);
  447. }
  448. }
  449. });
  450. }
  451. private async Task<object> GetMasterPlaylistInternal(StreamRequest request, string method)
  452. {
  453. var state = await GetState(request, CancellationToken.None).ConfigureAwait(false);
  454. if (string.IsNullOrEmpty(request.MediaSourceId))
  455. {
  456. throw new ArgumentException("MediaSourceId is required");
  457. }
  458. var playlistText = string.Empty;
  459. if (string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase))
  460. {
  461. var audioBitrate = state.OutputAudioBitrate ?? 0;
  462. var videoBitrate = state.OutputVideoBitrate ?? 0;
  463. playlistText = GetMasterPlaylistFileText(state, videoBitrate + audioBitrate);
  464. }
  465. return ResultFactory.GetResult(playlistText, MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary<string, string>());
  466. }
  467. private string GetMasterPlaylistFileText(StreamState state, int totalBitrate)
  468. {
  469. var builder = new StringBuilder();
  470. builder.AppendLine("#EXTM3U");
  471. var queryStringIndex = Request.RawUrl.IndexOf('?');
  472. var queryString = queryStringIndex == -1 ? string.Empty : Request.RawUrl.Substring(queryStringIndex);
  473. var isLiveStream = (state.RunTimeTicks ?? 0) == 0;
  474. // Main stream
  475. var playlistUrl = isLiveStream ? "live.m3u8" : "main.m3u8";
  476. playlistUrl += queryString;
  477. var request = state.Request;
  478. var subtitleStreams = state.MediaSource
  479. .MediaStreams
  480. .Where(i => i.IsTextSubtitleStream)
  481. .ToList();
  482. var subtitleGroup = subtitleStreams.Count > 0 &&
  483. (request is GetMasterHlsVideoPlaylist) &&
  484. ((GetMasterHlsVideoPlaylist)request).SubtitleMethod == SubtitleDeliveryMethod.Hls ?
  485. "subs" :
  486. null;
  487. AppendPlaylist(builder, playlistUrl, totalBitrate, subtitleGroup);
  488. if (EnableAdaptiveBitrateStreaming(state, isLiveStream))
  489. {
  490. var requestedVideoBitrate = state.VideoRequest == null ? 0 : state.VideoRequest.VideoBitRate ?? 0;
  491. // By default, vary by just 200k
  492. var variation = GetBitrateVariation(totalBitrate);
  493. var newBitrate = totalBitrate - variation;
  494. var variantUrl = ReplaceBitrate(playlistUrl, requestedVideoBitrate, (requestedVideoBitrate - variation));
  495. AppendPlaylist(builder, variantUrl, newBitrate, subtitleGroup);
  496. variation *= 2;
  497. newBitrate = totalBitrate - variation;
  498. variantUrl = ReplaceBitrate(playlistUrl, requestedVideoBitrate, (requestedVideoBitrate - variation));
  499. AppendPlaylist(builder, variantUrl, newBitrate, subtitleGroup);
  500. }
  501. if (!string.IsNullOrWhiteSpace(subtitleGroup))
  502. {
  503. AddSubtitles(state, subtitleStreams, builder);
  504. }
  505. return builder.ToString();
  506. }
  507. private string ReplaceBitrate(string url, int oldValue, int newValue)
  508. {
  509. return url.Replace(
  510. "videobitrate=" + oldValue.ToString(UsCulture),
  511. "videobitrate=" + newValue.ToString(UsCulture),
  512. StringComparison.OrdinalIgnoreCase);
  513. }
  514. private void AddSubtitles(StreamState state, IEnumerable<MediaStream> subtitles, StringBuilder builder)
  515. {
  516. var selectedIndex = state.SubtitleStream == null ? (int?)null : state.SubtitleStream.Index;
  517. foreach (var stream in subtitles)
  518. {
  519. const string format = "#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID=\"subs\",NAME=\"{0}\",DEFAULT={1},FORCED={2},URI=\"{3}\",LANGUAGE=\"{4}\"";
  520. var name = stream.Language;
  521. var isDefault = selectedIndex.HasValue && selectedIndex.Value == stream.Index;
  522. var isForced = stream.IsForced;
  523. if (string.IsNullOrWhiteSpace(name)) name = stream.Codec ?? "Unknown";
  524. var url = string.Format("{0}/Subtitles/{1}/subtitles.m3u8?SegmentLength={2}",
  525. state.Request.MediaSourceId,
  526. stream.Index.ToString(UsCulture),
  527. 30.ToString(UsCulture));
  528. var line = string.Format(format,
  529. name,
  530. isDefault ? "YES" : "NO",
  531. isForced ? "YES" : "NO",
  532. url,
  533. stream.Language ?? "Unknown");
  534. builder.AppendLine(line);
  535. }
  536. }
  537. private bool EnableAdaptiveBitrateStreaming(StreamState state, bool isLiveStream)
  538. {
  539. // Within the local network this will likely do more harm than good.
  540. if (Request.IsLocal || NetworkManager.IsInLocalNetwork(Request.RemoteIp))
  541. {
  542. return false;
  543. }
  544. var request = state.Request as IMasterHlsRequest;
  545. if (request != null && !request.EnableAdaptiveBitrateStreaming)
  546. {
  547. return false;
  548. }
  549. if (isLiveStream || string.IsNullOrWhiteSpace(state.MediaPath))
  550. {
  551. // Opening live streams is so slow it's not even worth it
  552. return false;
  553. }
  554. if (string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  555. {
  556. return false;
  557. }
  558. if (string.Equals(state.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase))
  559. {
  560. return false;
  561. }
  562. if (!state.IsOutputVideo)
  563. {
  564. return false;
  565. }
  566. // Having problems in android
  567. return false;
  568. //return state.VideoRequest.VideoBitRate.HasValue;
  569. }
  570. private void AppendPlaylist(StringBuilder builder, string url, int bitrate, string subtitleGroup)
  571. {
  572. var header = "#EXT-X-STREAM-INF:BANDWIDTH=" + bitrate.ToString(UsCulture);
  573. if (!string.IsNullOrWhiteSpace(subtitleGroup))
  574. {
  575. header += string.Format(",SUBTITLES=\"{0}\"", subtitleGroup);
  576. }
  577. builder.AppendLine(header);
  578. builder.AppendLine(url);
  579. }
  580. private int GetBitrateVariation(int bitrate)
  581. {
  582. // By default, vary by just 50k
  583. var variation = 50000;
  584. if (bitrate >= 10000000)
  585. {
  586. variation = 2000000;
  587. }
  588. else if (bitrate >= 5000000)
  589. {
  590. variation = 1500000;
  591. }
  592. else if (bitrate >= 3000000)
  593. {
  594. variation = 1000000;
  595. }
  596. else if (bitrate >= 2000000)
  597. {
  598. variation = 500000;
  599. }
  600. else if (bitrate >= 1000000)
  601. {
  602. variation = 300000;
  603. }
  604. else if (bitrate >= 600000)
  605. {
  606. variation = 200000;
  607. }
  608. else if (bitrate >= 400000)
  609. {
  610. variation = 100000;
  611. }
  612. return variation;
  613. }
  614. private async Task<object> GetVariantPlaylistInternal(StreamRequest request, bool isOutputVideo, string name)
  615. {
  616. var state = await GetState(request, CancellationToken.None).ConfigureAwait(false);
  617. var builder = new StringBuilder();
  618. builder.AppendLine("#EXTM3U");
  619. builder.AppendLine("#EXT-X-VERSION:3");
  620. builder.AppendLine("#EXT-X-TARGETDURATION:" + (state.SegmentLength).ToString(UsCulture));
  621. builder.AppendLine("#EXT-X-MEDIA-SEQUENCE:0");
  622. var queryStringIndex = Request.RawUrl.IndexOf('?');
  623. var queryString = queryStringIndex == -1 ? string.Empty : Request.RawUrl.Substring(queryStringIndex);
  624. var seconds = TimeSpan.FromTicks(state.RunTimeTicks ?? 0).TotalSeconds;
  625. var index = 0;
  626. while (seconds > 0)
  627. {
  628. var length = seconds >= state.SegmentLength ? state.SegmentLength : seconds;
  629. builder.AppendLine("#EXTINF:" + length.ToString(UsCulture) + ",");
  630. builder.AppendLine(string.Format("hlsdynamic/{0}/{1}{2}{3}",
  631. name,
  632. index.ToString(UsCulture),
  633. GetSegmentFileExtension(isOutputVideo),
  634. queryString));
  635. seconds -= state.SegmentLength;
  636. index++;
  637. }
  638. builder.AppendLine("#EXT-X-ENDLIST");
  639. var playlistText = builder.ToString();
  640. return ResultFactory.GetResult(playlistText, MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary<string, string>());
  641. }
  642. protected override string GetAudioArguments(StreamState state)
  643. {
  644. var codec = GetAudioEncoder(state.Request);
  645. if (!state.IsOutputVideo)
  646. {
  647. if (string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase))
  648. {
  649. return "-acodec copy";
  650. }
  651. var audioTranscodeParams = new List<string>();
  652. audioTranscodeParams.Add("-acodec " + codec);
  653. if (state.OutputAudioBitrate.HasValue)
  654. {
  655. audioTranscodeParams.Add("-ab " + state.OutputAudioBitrate.Value.ToString(UsCulture));
  656. }
  657. if (state.OutputAudioChannels.HasValue)
  658. {
  659. audioTranscodeParams.Add("-ac " + state.OutputAudioChannels.Value.ToString(UsCulture));
  660. }
  661. if (state.OutputAudioSampleRate.HasValue)
  662. {
  663. audioTranscodeParams.Add("-ar " + state.OutputAudioSampleRate.Value.ToString(UsCulture));
  664. }
  665. audioTranscodeParams.Add("-vn");
  666. return string.Join(" ", audioTranscodeParams.ToArray());
  667. }
  668. if (string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase))
  669. {
  670. return "-codec:a:0 copy";
  671. }
  672. var args = "-codec:a:0 " + codec;
  673. var channels = state.OutputAudioChannels;
  674. if (channels.HasValue)
  675. {
  676. args += " -ac " + channels.Value;
  677. }
  678. var bitrate = state.OutputAudioBitrate;
  679. if (bitrate.HasValue)
  680. {
  681. args += " -ab " + bitrate.Value.ToString(UsCulture);
  682. }
  683. args += " " + GetAudioFilterParam(state, true);
  684. return args;
  685. }
  686. protected override string GetVideoArguments(StreamState state)
  687. {
  688. if (!state.IsOutputVideo)
  689. {
  690. return string.Empty;
  691. }
  692. var codec = GetVideoEncoder(state.VideoRequest);
  693. var args = "-codec:v:0 " + codec;
  694. if (state.EnableMpegtsM2TsMode)
  695. {
  696. args += " -mpegts_m2ts_mode 1";
  697. }
  698. // See if we can save come cpu cycles by avoiding encoding
  699. if (string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase))
  700. {
  701. if (state.VideoStream != null && IsH264(state.VideoStream))
  702. {
  703. args += " -bsf:v h264_mp4toannexb";
  704. }
  705. args += " -flags -global_header -sc_threshold 0";
  706. }
  707. else
  708. {
  709. var keyFrameArg = string.Format(" -force_key_frames expr:gte(t,n_forced*{0})",
  710. state.SegmentLength.ToString(UsCulture));
  711. var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream;
  712. args += " " + GetVideoQualityParam(state, H264Encoder, true) + keyFrameArg;
  713. //args += " -mixed-refs 0 -refs 3 -x264opts b_pyramid=0:weightb=0:weightp=0";
  714. // Add resolution params, if specified
  715. if (!hasGraphicalSubs)
  716. {
  717. args += GetOutputSizeParam(state, codec, false);
  718. }
  719. // This is for internal graphical subs
  720. if (hasGraphicalSubs)
  721. {
  722. args += GetGraphicalSubtitleParam(state, codec);
  723. }
  724. args += " -flags +loop-global_header -sc_threshold 0";
  725. }
  726. if (!EnableSplitTranscoding(state))
  727. {
  728. //args += " -copyts";
  729. }
  730. return args;
  731. }
  732. protected override string GetCommandLineArguments(string outputPath, StreamState state, bool isEncoding)
  733. {
  734. var threads = GetNumberOfThreads(state, false);
  735. var inputModifier = GetInputModifier(state, false);
  736. // If isEncoding is true we're actually starting ffmpeg
  737. var startNumberParam = isEncoding ? GetStartNumber(state).ToString(UsCulture) : "0";
  738. var toTimeParam = string.Empty;
  739. var timestampOffsetParam = string.Empty;
  740. if (EnableSplitTranscoding(state))
  741. {
  742. var startTime = state.Request.StartTimeTicks ?? 0;
  743. var durationSeconds = ApiEntryPoint.Instance.GetEncodingOptions().ThrottleThresholdInSeconds;
  744. var endTime = startTime + TimeSpan.FromSeconds(durationSeconds).Ticks;
  745. endTime = Math.Min(endTime, state.RunTimeTicks.Value);
  746. if (endTime < state.RunTimeTicks.Value)
  747. {
  748. //toTimeParam = " -to " + MediaEncoder.GetTimeParameter(endTime);
  749. toTimeParam = " -t " + MediaEncoder.GetTimeParameter(TimeSpan.FromSeconds(durationSeconds).Ticks);
  750. }
  751. }
  752. if (state.IsOutputVideo && !string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase) && (state.Request.StartTimeTicks ?? 0) > 0)
  753. {
  754. timestampOffsetParam = " -output_ts_offset " + MediaEncoder.GetTimeParameter(state.Request.StartTimeTicks ?? 0).ToString(CultureInfo.InvariantCulture);
  755. }
  756. var mapArgs = state.IsOutputVideo ? GetMapArgs(state) : string.Empty;
  757. //var outputTsArg = Path.Combine(Path.GetDirectoryName(outputPath), Path.GetFileNameWithoutExtension(outputPath)) + "%d" + GetSegmentFileExtension(state);
  758. //return string.Format("{0} {11} {1}{10} -map_metadata -1 -threads {2} {3} {4} {5} -f segment -segment_time {6} -segment_format mpegts -segment_list_type m3u8 -segment_start_number {7} -segment_list \"{8}\" -y \"{9}\"",
  759. // inputModifier,
  760. // GetInputArgument(state),
  761. // threads,
  762. // mapArgs,
  763. // GetVideoArguments(state),
  764. // GetAudioArguments(state),
  765. // state.SegmentLength.ToString(UsCulture),
  766. // startNumberParam,
  767. // outputPath,
  768. // outputTsArg,
  769. // slowSeekParam,
  770. // toTimeParam
  771. // ).Trim();
  772. return string.Format("{0}{11} {1} -map_metadata -1 -threads {2} {3} {4}{5} {6} -hls_time {7} -start_number {8} -hls_list_size {9} -y \"{10}\"",
  773. inputModifier,
  774. GetInputArgument(state),
  775. threads,
  776. mapArgs,
  777. GetVideoArguments(state),
  778. timestampOffsetParam,
  779. GetAudioArguments(state),
  780. state.SegmentLength.ToString(UsCulture),
  781. startNumberParam,
  782. state.HlsListSize.ToString(UsCulture),
  783. outputPath,
  784. toTimeParam
  785. ).Trim();
  786. }
  787. protected override bool EnableThrottling(StreamState state)
  788. {
  789. return !EnableSplitTranscoding(state);
  790. }
  791. private bool EnableSplitTranscoding(StreamState state)
  792. {
  793. return false;
  794. if (string.Equals(Request.QueryString["EnableSplitTranscoding"], "false", StringComparison.OrdinalIgnoreCase))
  795. {
  796. return false;
  797. }
  798. if (string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  799. {
  800. return false;
  801. }
  802. if (string.Equals(state.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase))
  803. {
  804. return false;
  805. }
  806. return state.RunTimeTicks.HasValue && state.IsOutputVideo;
  807. }
  808. protected override bool EnableStreamCopy
  809. {
  810. get
  811. {
  812. return false;
  813. }
  814. }
  815. /// <summary>
  816. /// Gets the segment file extension.
  817. /// </summary>
  818. /// <param name="state">The state.</param>
  819. /// <returns>System.String.</returns>
  820. protected override string GetSegmentFileExtension(StreamState state)
  821. {
  822. return GetSegmentFileExtension(state.IsOutputVideo);
  823. }
  824. protected string GetSegmentFileExtension(bool isOutputVideo)
  825. {
  826. return isOutputVideo ? ".ts" : ".ts";
  827. }
  828. }
  829. }