DynamicHlsService.cs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  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 (FileNotFoundException)
  255. {
  256. }
  257. }
  258. private long GetSeekPositionTicks(StreamState state, string playlist, int requestedIndex)
  259. {
  260. double startSeconds = 0;
  261. for (var i = 0; i < requestedIndex; i++)
  262. {
  263. var segmentPath = GetSegmentPath(state, playlist, i);
  264. double length;
  265. if (SegmentLengths.TryGetValue(Path.GetFileName(segmentPath), out length))
  266. {
  267. Logger.Debug("Found segment length of {0} for index {1}", length, i);
  268. startSeconds += length;
  269. }
  270. else
  271. {
  272. startSeconds += state.SegmentLength;
  273. }
  274. }
  275. var position = TimeSpan.FromSeconds(startSeconds).Ticks;
  276. return position;
  277. }
  278. public int? GetCurrentTranscodingIndex(string playlist, string segmentExtension)
  279. {
  280. var job = ApiEntryPoint.Instance.GetTranscodingJob(playlist, TranscodingJobType);
  281. if (job == null || job.HasExited)
  282. {
  283. return null;
  284. }
  285. var file = GetLastTranscodingFile(playlist, segmentExtension, FileSystem);
  286. if (file == null)
  287. {
  288. return null;
  289. }
  290. var playlistFilename = Path.GetFileNameWithoutExtension(playlist);
  291. var indexString = Path.GetFileNameWithoutExtension(file.Name).Substring(playlistFilename.Length);
  292. return int.Parse(indexString, NumberStyles.Integer, UsCulture);
  293. }
  294. private void DeleteLastFile(string playlistPath, string segmentExtension, int retryCount)
  295. {
  296. var file = GetLastTranscodingFile(playlistPath, segmentExtension, FileSystem);
  297. if (file != null)
  298. {
  299. DeleteFile(file, retryCount);
  300. }
  301. }
  302. private void DeleteFile(FileInfo file, int retryCount)
  303. {
  304. if (retryCount >= 5)
  305. {
  306. return;
  307. }
  308. try
  309. {
  310. FileSystem.DeleteFile(file.FullName);
  311. }
  312. catch (IOException ex)
  313. {
  314. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, file.FullName);
  315. Thread.Sleep(100);
  316. DeleteFile(file, retryCount + 1);
  317. }
  318. catch (Exception ex)
  319. {
  320. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, file.FullName);
  321. }
  322. }
  323. private static FileInfo GetLastTranscodingFile(string playlist, string segmentExtension, IFileSystem fileSystem)
  324. {
  325. var folder = Path.GetDirectoryName(playlist);
  326. var filePrefix = Path.GetFileNameWithoutExtension(playlist) ?? string.Empty;
  327. try
  328. {
  329. return new DirectoryInfo(folder)
  330. .EnumerateFiles("*", SearchOption.TopDirectoryOnly)
  331. .Where(i => string.Equals(i.Extension, segmentExtension, StringComparison.OrdinalIgnoreCase) && Path.GetFileNameWithoutExtension(i.Name).StartsWith(filePrefix, StringComparison.OrdinalIgnoreCase))
  332. .OrderByDescending(fileSystem.GetLastWriteTimeUtc)
  333. .FirstOrDefault();
  334. }
  335. catch (DirectoryNotFoundException)
  336. {
  337. return null;
  338. }
  339. }
  340. protected override int GetStartNumber(StreamState state)
  341. {
  342. return GetStartNumber(state.VideoRequest);
  343. }
  344. private int GetStartNumber(VideoStreamRequest request)
  345. {
  346. var segmentId = "0";
  347. var segmentRequest = request as GetHlsVideoSegment;
  348. if (segmentRequest != null)
  349. {
  350. segmentId = segmentRequest.SegmentId;
  351. }
  352. return int.Parse(segmentId, NumberStyles.Integer, UsCulture);
  353. }
  354. private string GetSegmentPath(StreamState state, string playlist, int index)
  355. {
  356. var folder = Path.GetDirectoryName(playlist);
  357. var filename = Path.GetFileNameWithoutExtension(playlist);
  358. return Path.Combine(folder, filename + index.ToString(UsCulture) + GetSegmentFileExtension(state));
  359. }
  360. private async Task<object> GetSegmentResult(string playlistPath,
  361. string segmentPath,
  362. int segmentIndex,
  363. int segmentLength,
  364. TranscodingJob transcodingJob,
  365. CancellationToken cancellationToken)
  366. {
  367. // If all transcoding has completed, just return immediately
  368. if (transcodingJob != null && transcodingJob.HasExited)
  369. {
  370. return GetSegmentResult(segmentPath, segmentIndex, segmentLength, transcodingJob);
  371. }
  372. var segmentFilename = Path.GetFileName(segmentPath);
  373. while (!cancellationToken.IsCancellationRequested)
  374. {
  375. try
  376. {
  377. using (var fileStream = GetPlaylistFileStream(playlistPath))
  378. {
  379. using (var reader = new StreamReader(fileStream))
  380. {
  381. while (!reader.EndOfStream)
  382. {
  383. var text = await reader.ReadLineAsync().ConfigureAwait(false);
  384. // If it appears in the playlist, it's done
  385. if (text.IndexOf(segmentFilename, StringComparison.OrdinalIgnoreCase) != -1)
  386. {
  387. return GetSegmentResult(segmentPath, segmentIndex, segmentLength, transcodingJob);
  388. }
  389. }
  390. }
  391. }
  392. }
  393. catch (IOException)
  394. {
  395. // May get an error if the file is locked
  396. }
  397. await Task.Delay(100, cancellationToken).ConfigureAwait(false);
  398. }
  399. // if a different file is encoding, it's done
  400. //var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath);
  401. //if (currentTranscodingIndex > segmentIndex)
  402. //{
  403. //return GetSegmentResult(segmentPath, segmentIndex);
  404. //}
  405. //// Wait for the file to stop being written to, then stream it
  406. //var length = new FileInfo(segmentPath).Length;
  407. //var eofCount = 0;
  408. //while (eofCount < 10)
  409. //{
  410. // var info = new FileInfo(segmentPath);
  411. // if (!info.Exists)
  412. // {
  413. // break;
  414. // }
  415. // var newLength = info.Length;
  416. // if (newLength == length)
  417. // {
  418. // eofCount++;
  419. // }
  420. // else
  421. // {
  422. // eofCount = 0;
  423. // }
  424. // length = newLength;
  425. // await Task.Delay(100, cancellationToken).ConfigureAwait(false);
  426. //}
  427. cancellationToken.ThrowIfCancellationRequested();
  428. return GetSegmentResult(segmentPath, segmentIndex, segmentLength, transcodingJob);
  429. }
  430. private object GetSegmentResult(string segmentPath, int index, int segmentLength, TranscodingJob transcodingJob)
  431. {
  432. var segmentEndingSeconds = (1 + index) * segmentLength;
  433. var segmentEndingPositionTicks = TimeSpan.FromSeconds(segmentEndingSeconds).Ticks;
  434. return ResultFactory.GetStaticFileResult(Request, new StaticFileResultOptions
  435. {
  436. Path = segmentPath,
  437. FileShare = FileShare.ReadWrite,
  438. OnComplete = () =>
  439. {
  440. if (transcodingJob != null)
  441. {
  442. transcodingJob.DownloadPositionTicks = Math.Max(transcodingJob.DownloadPositionTicks ?? segmentEndingPositionTicks, segmentEndingPositionTicks);
  443. ApiEntryPoint.Instance.OnTranscodeEndRequest(transcodingJob);
  444. }
  445. }
  446. });
  447. }
  448. private async Task<object> GetMasterPlaylistInternal(StreamRequest request, string method)
  449. {
  450. var state = await GetState(request, CancellationToken.None).ConfigureAwait(false);
  451. if (string.IsNullOrEmpty(request.MediaSourceId))
  452. {
  453. throw new ArgumentException("MediaSourceId is required");
  454. }
  455. var playlistText = string.Empty;
  456. if (string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase))
  457. {
  458. var audioBitrate = state.OutputAudioBitrate ?? 0;
  459. var videoBitrate = state.OutputVideoBitrate ?? 0;
  460. playlistText = GetMasterPlaylistFileText(state, videoBitrate + audioBitrate);
  461. }
  462. return ResultFactory.GetResult(playlistText, MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary<string, string>());
  463. }
  464. private string GetMasterPlaylistFileText(StreamState state, int totalBitrate)
  465. {
  466. var builder = new StringBuilder();
  467. builder.AppendLine("#EXTM3U");
  468. var queryStringIndex = Request.RawUrl.IndexOf('?');
  469. var queryString = queryStringIndex == -1 ? string.Empty : Request.RawUrl.Substring(queryStringIndex);
  470. var isLiveStream = (state.RunTimeTicks ?? 0) == 0;
  471. // Main stream
  472. var playlistUrl = isLiveStream ? "live.m3u8" : "main.m3u8";
  473. playlistUrl += queryString;
  474. var request = state.Request;
  475. var subtitleStreams = state.MediaSource
  476. .MediaStreams
  477. .Where(i => i.IsTextSubtitleStream)
  478. .ToList();
  479. var subtitleGroup = subtitleStreams.Count > 0 &&
  480. (request is GetMasterHlsVideoPlaylist) &&
  481. ((GetMasterHlsVideoPlaylist)request).SubtitleMethod == SubtitleDeliveryMethod.Hls ?
  482. "subs" :
  483. null;
  484. AppendPlaylist(builder, playlistUrl, totalBitrate, subtitleGroup);
  485. if (EnableAdaptiveBitrateStreaming(state, isLiveStream))
  486. {
  487. var requestedVideoBitrate = state.VideoRequest == null ? 0 : state.VideoRequest.VideoBitRate ?? 0;
  488. // By default, vary by just 200k
  489. var variation = GetBitrateVariation(totalBitrate);
  490. var newBitrate = totalBitrate - variation;
  491. var variantUrl = ReplaceBitrate(playlistUrl, requestedVideoBitrate, (requestedVideoBitrate - variation));
  492. AppendPlaylist(builder, variantUrl, newBitrate, subtitleGroup);
  493. variation *= 2;
  494. newBitrate = totalBitrate - variation;
  495. variantUrl = ReplaceBitrate(playlistUrl, requestedVideoBitrate, (requestedVideoBitrate - variation));
  496. AppendPlaylist(builder, variantUrl, newBitrate, subtitleGroup);
  497. }
  498. if (!string.IsNullOrWhiteSpace(subtitleGroup))
  499. {
  500. AddSubtitles(state, subtitleStreams, builder);
  501. }
  502. return builder.ToString();
  503. }
  504. private string ReplaceBitrate(string url, int oldValue, int newValue)
  505. {
  506. return url.Replace(
  507. "videobitrate=" + oldValue.ToString(UsCulture),
  508. "videobitrate=" + newValue.ToString(UsCulture),
  509. StringComparison.OrdinalIgnoreCase);
  510. }
  511. private void AddSubtitles(StreamState state, IEnumerable<MediaStream> subtitles, StringBuilder builder)
  512. {
  513. var selectedIndex = state.SubtitleStream == null ? (int?)null : state.SubtitleStream.Index;
  514. foreach (var stream in subtitles)
  515. {
  516. const string format = "#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID=\"subs\",NAME=\"{0}\",DEFAULT={1},FORCED={2},URI=\"{3}\",LANGUAGE=\"{4}\"";
  517. var name = stream.Language;
  518. var isDefault = selectedIndex.HasValue && selectedIndex.Value == stream.Index;
  519. var isForced = stream.IsForced;
  520. if (string.IsNullOrWhiteSpace(name)) name = stream.Codec ?? "Unknown";
  521. var url = string.Format("{0}/Subtitles/{1}/subtitles.m3u8?SegmentLength={2}",
  522. state.Request.MediaSourceId,
  523. stream.Index.ToString(UsCulture),
  524. 30.ToString(UsCulture));
  525. var line = string.Format(format,
  526. name,
  527. isDefault ? "YES" : "NO",
  528. isForced ? "YES" : "NO",
  529. url,
  530. stream.Language ?? "Unknown");
  531. builder.AppendLine(line);
  532. }
  533. }
  534. private bool EnableAdaptiveBitrateStreaming(StreamState state, bool isLiveStream)
  535. {
  536. // Within the local network this will likely do more harm than good.
  537. if (Request.IsLocal || NetworkManager.IsInLocalNetwork(Request.RemoteIp))
  538. {
  539. return false;
  540. }
  541. var request = state.Request as IMasterHlsRequest;
  542. if (request != null && !request.EnableAdaptiveBitrateStreaming)
  543. {
  544. return false;
  545. }
  546. if (isLiveStream || string.IsNullOrWhiteSpace(state.MediaPath))
  547. {
  548. // Opening live streams is so slow it's not even worth it
  549. return false;
  550. }
  551. if (string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  552. {
  553. return false;
  554. }
  555. if (string.Equals(state.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase))
  556. {
  557. return false;
  558. }
  559. if (!state.IsOutputVideo)
  560. {
  561. return false;
  562. }
  563. // Having problems in android
  564. return false;
  565. //return state.VideoRequest.VideoBitRate.HasValue;
  566. }
  567. private void AppendPlaylist(StringBuilder builder, string url, int bitrate, string subtitleGroup)
  568. {
  569. var header = "#EXT-X-STREAM-INF:BANDWIDTH=" + bitrate.ToString(UsCulture);
  570. if (!string.IsNullOrWhiteSpace(subtitleGroup))
  571. {
  572. header += string.Format(",SUBTITLES=\"{0}\"", subtitleGroup);
  573. }
  574. builder.AppendLine(header);
  575. builder.AppendLine(url);
  576. }
  577. private int GetBitrateVariation(int bitrate)
  578. {
  579. // By default, vary by just 50k
  580. var variation = 50000;
  581. if (bitrate >= 10000000)
  582. {
  583. variation = 2000000;
  584. }
  585. else if (bitrate >= 5000000)
  586. {
  587. variation = 1500000;
  588. }
  589. else if (bitrate >= 3000000)
  590. {
  591. variation = 1000000;
  592. }
  593. else if (bitrate >= 2000000)
  594. {
  595. variation = 500000;
  596. }
  597. else if (bitrate >= 1000000)
  598. {
  599. variation = 300000;
  600. }
  601. else if (bitrate >= 600000)
  602. {
  603. variation = 200000;
  604. }
  605. else if (bitrate >= 400000)
  606. {
  607. variation = 100000;
  608. }
  609. return variation;
  610. }
  611. private async Task<object> GetVariantPlaylistInternal(StreamRequest request, bool isOutputVideo, string name)
  612. {
  613. var state = await GetState(request, CancellationToken.None).ConfigureAwait(false);
  614. var builder = new StringBuilder();
  615. builder.AppendLine("#EXTM3U");
  616. builder.AppendLine("#EXT-X-VERSION:3");
  617. builder.AppendLine("#EXT-X-TARGETDURATION:" + (state.SegmentLength).ToString(UsCulture));
  618. builder.AppendLine("#EXT-X-MEDIA-SEQUENCE:0");
  619. var queryStringIndex = Request.RawUrl.IndexOf('?');
  620. var queryString = queryStringIndex == -1 ? string.Empty : Request.RawUrl.Substring(queryStringIndex);
  621. var seconds = TimeSpan.FromTicks(state.RunTimeTicks ?? 0).TotalSeconds;
  622. var index = 0;
  623. while (seconds > 0)
  624. {
  625. var length = seconds >= state.SegmentLength ? state.SegmentLength : seconds;
  626. builder.AppendLine("#EXTINF:" + length.ToString(UsCulture) + ",");
  627. builder.AppendLine(string.Format("hlsdynamic/{0}/{1}{2}{3}",
  628. name,
  629. index.ToString(UsCulture),
  630. GetSegmentFileExtension(isOutputVideo),
  631. queryString));
  632. seconds -= state.SegmentLength;
  633. index++;
  634. }
  635. builder.AppendLine("#EXT-X-ENDLIST");
  636. var playlistText = builder.ToString();
  637. return ResultFactory.GetResult(playlistText, MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary<string, string>());
  638. }
  639. protected override string GetAudioArguments(StreamState state)
  640. {
  641. if (!state.IsOutputVideo)
  642. {
  643. var audioTranscodeParams = new List<string>();
  644. if (state.OutputAudioBitrate.HasValue)
  645. {
  646. audioTranscodeParams.Add("-ab " + state.OutputAudioBitrate.Value.ToString(UsCulture));
  647. }
  648. if (state.OutputAudioChannels.HasValue)
  649. {
  650. audioTranscodeParams.Add("-ac " + state.OutputAudioChannels.Value.ToString(UsCulture));
  651. }
  652. if (state.OutputAudioSampleRate.HasValue)
  653. {
  654. audioTranscodeParams.Add("-ar " + state.OutputAudioSampleRate.Value.ToString(UsCulture));
  655. }
  656. audioTranscodeParams.Add("-vn");
  657. return string.Join(" ", audioTranscodeParams.ToArray());
  658. }
  659. var codec = GetAudioEncoder(state.Request);
  660. if (string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase))
  661. {
  662. return "-codec:a:0 copy";
  663. }
  664. var args = "-codec:a:0 " + codec;
  665. var channels = state.OutputAudioChannels;
  666. if (channels.HasValue)
  667. {
  668. args += " -ac " + channels.Value;
  669. }
  670. var bitrate = state.OutputAudioBitrate;
  671. if (bitrate.HasValue)
  672. {
  673. args += " -ab " + bitrate.Value.ToString(UsCulture);
  674. }
  675. args += " " + GetAudioFilterParam(state, true);
  676. return args;
  677. }
  678. protected override string GetVideoArguments(StreamState state)
  679. {
  680. if (!state.IsOutputVideo)
  681. {
  682. return string.Empty;
  683. }
  684. var codec = GetVideoEncoder(state.VideoRequest);
  685. var args = "-codec:v:0 " + codec;
  686. if (state.EnableMpegtsM2TsMode)
  687. {
  688. args += " -mpegts_m2ts_mode 1";
  689. }
  690. // See if we can save come cpu cycles by avoiding encoding
  691. if (string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase))
  692. {
  693. if (state.VideoStream != null && IsH264(state.VideoStream))
  694. {
  695. args += " -bsf:v h264_mp4toannexb";
  696. }
  697. args += " -flags -global_header -sc_threshold 0";
  698. }
  699. else
  700. {
  701. var keyFrameArg = string.Format(" -force_key_frames expr:gte(t,n_forced*{0})",
  702. state.SegmentLength.ToString(UsCulture));
  703. var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream;
  704. args += " " + GetVideoQualityParam(state, H264Encoder, true) + keyFrameArg;
  705. //args += " -mixed-refs 0 -refs 3 -x264opts b_pyramid=0:weightb=0:weightp=0";
  706. // Add resolution params, if specified
  707. if (!hasGraphicalSubs)
  708. {
  709. args += GetOutputSizeParam(state, codec, false);
  710. }
  711. // This is for internal graphical subs
  712. if (hasGraphicalSubs)
  713. {
  714. args += GetGraphicalSubtitleParam(state, codec);
  715. }
  716. args += " -flags +loop-global_header -sc_threshold 0";
  717. }
  718. if (!EnableSplitTranscoding(state))
  719. {
  720. //args += " -copyts";
  721. }
  722. return args;
  723. }
  724. protected override string GetCommandLineArguments(string outputPath, StreamState state, bool isEncoding)
  725. {
  726. var threads = GetNumberOfThreads(state, false);
  727. var inputModifier = GetInputModifier(state, false);
  728. // If isEncoding is true we're actually starting ffmpeg
  729. var startNumberParam = isEncoding ? GetStartNumber(state).ToString(UsCulture) : "0";
  730. var toTimeParam = string.Empty;
  731. var timestampOffsetParam = string.Empty;
  732. if (EnableSplitTranscoding(state))
  733. {
  734. var startTime = state.Request.StartTimeTicks ?? 0;
  735. var durationSeconds = ApiEntryPoint.Instance.GetEncodingOptions().ThrottleThresholdInSeconds;
  736. var endTime = startTime + TimeSpan.FromSeconds(durationSeconds).Ticks;
  737. endTime = Math.Min(endTime, state.RunTimeTicks.Value);
  738. if (endTime < state.RunTimeTicks.Value)
  739. {
  740. //toTimeParam = " -to " + MediaEncoder.GetTimeParameter(endTime);
  741. toTimeParam = " -t " + MediaEncoder.GetTimeParameter(TimeSpan.FromSeconds(durationSeconds).Ticks);
  742. }
  743. }
  744. if (state.IsOutputVideo && !string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase) && (state.Request.StartTimeTicks ?? 0) > 0)
  745. {
  746. timestampOffsetParam = " -output_ts_offset " + MediaEncoder.GetTimeParameter(state.Request.StartTimeTicks ?? 0).ToString(CultureInfo.InvariantCulture);
  747. }
  748. var mapArgs = state.IsOutputVideo ? GetMapArgs(state) : string.Empty;
  749. //var outputTsArg = Path.Combine(Path.GetDirectoryName(outputPath), Path.GetFileNameWithoutExtension(outputPath)) + "%d" + GetSegmentFileExtension(state);
  750. //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}\"",
  751. // inputModifier,
  752. // GetInputArgument(state),
  753. // threads,
  754. // mapArgs,
  755. // GetVideoArguments(state),
  756. // GetAudioArguments(state),
  757. // state.SegmentLength.ToString(UsCulture),
  758. // startNumberParam,
  759. // outputPath,
  760. // outputTsArg,
  761. // slowSeekParam,
  762. // toTimeParam
  763. // ).Trim();
  764. 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}\"",
  765. inputModifier,
  766. GetInputArgument(state),
  767. threads,
  768. mapArgs,
  769. GetVideoArguments(state),
  770. timestampOffsetParam,
  771. GetAudioArguments(state),
  772. state.SegmentLength.ToString(UsCulture),
  773. startNumberParam,
  774. state.HlsListSize.ToString(UsCulture),
  775. outputPath,
  776. toTimeParam
  777. ).Trim();
  778. }
  779. protected override bool EnableThrottling(StreamState state)
  780. {
  781. return !EnableSplitTranscoding(state);
  782. }
  783. private bool EnableSplitTranscoding(StreamState state)
  784. {
  785. return false;
  786. if (string.Equals(Request.QueryString["EnableSplitTranscoding"], "false", StringComparison.OrdinalIgnoreCase))
  787. {
  788. return false;
  789. }
  790. if (string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  791. {
  792. return false;
  793. }
  794. if (string.Equals(state.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase))
  795. {
  796. return false;
  797. }
  798. return state.RunTimeTicks.HasValue && state.IsOutputVideo;
  799. }
  800. protected override bool EnableStreamCopy
  801. {
  802. get
  803. {
  804. return false;
  805. }
  806. }
  807. /// <summary>
  808. /// Gets the segment file extension.
  809. /// </summary>
  810. /// <param name="state">The state.</param>
  811. /// <returns>System.String.</returns>
  812. protected override string GetSegmentFileExtension(StreamState state)
  813. {
  814. return GetSegmentFileExtension(state.IsOutputVideo);
  815. }
  816. protected string GetSegmentFileExtension(bool isOutputVideo)
  817. {
  818. return isOutputVideo ? ".ts" : ".ts";
  819. }
  820. }
  821. }