DynamicHlsService.cs 37 KB

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