DynamicHlsService.cs 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  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. using (var fileStream = GetPlaylistFileStream(playlistPath))
  376. {
  377. using (var reader = new StreamReader(fileStream))
  378. {
  379. while (!reader.EndOfStream)
  380. {
  381. var text = await reader.ReadLineAsync().ConfigureAwait(false);
  382. // If it appears in the playlist, it's done
  383. if (text.IndexOf(segmentFilename, StringComparison.OrdinalIgnoreCase) != -1)
  384. {
  385. return GetSegmentResult(segmentPath, segmentIndex, segmentLength, transcodingJob);
  386. }
  387. }
  388. }
  389. }
  390. await Task.Delay(100, cancellationToken).ConfigureAwait(false);
  391. }
  392. // if a different file is encoding, it's done
  393. //var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath);
  394. //if (currentTranscodingIndex > segmentIndex)
  395. //{
  396. //return GetSegmentResult(segmentPath, segmentIndex);
  397. //}
  398. //// Wait for the file to stop being written to, then stream it
  399. //var length = new FileInfo(segmentPath).Length;
  400. //var eofCount = 0;
  401. //while (eofCount < 10)
  402. //{
  403. // var info = new FileInfo(segmentPath);
  404. // if (!info.Exists)
  405. // {
  406. // break;
  407. // }
  408. // var newLength = info.Length;
  409. // if (newLength == length)
  410. // {
  411. // eofCount++;
  412. // }
  413. // else
  414. // {
  415. // eofCount = 0;
  416. // }
  417. // length = newLength;
  418. // await Task.Delay(100, cancellationToken).ConfigureAwait(false);
  419. //}
  420. cancellationToken.ThrowIfCancellationRequested();
  421. return GetSegmentResult(segmentPath, segmentIndex, segmentLength, transcodingJob);
  422. }
  423. private object GetSegmentResult(string segmentPath, int index, int segmentLength, TranscodingJob transcodingJob)
  424. {
  425. var segmentEndingSeconds = (1 + index) * segmentLength;
  426. var segmentEndingPositionTicks = TimeSpan.FromSeconds(segmentEndingSeconds).Ticks;
  427. return ResultFactory.GetStaticFileResult(Request, new StaticFileResultOptions
  428. {
  429. Path = segmentPath,
  430. FileShare = FileShare.ReadWrite,
  431. OnComplete = () =>
  432. {
  433. if (transcodingJob != null)
  434. {
  435. transcodingJob.DownloadPositionTicks = Math.Max(transcodingJob.DownloadPositionTicks ?? segmentEndingPositionTicks, segmentEndingPositionTicks);
  436. ApiEntryPoint.Instance.OnTranscodeEndRequest(transcodingJob);
  437. }
  438. }
  439. });
  440. }
  441. private async Task<object> GetMasterPlaylistInternal(StreamRequest request, string method)
  442. {
  443. var state = await GetState(request, CancellationToken.None).ConfigureAwait(false);
  444. if (string.IsNullOrEmpty(request.MediaSourceId))
  445. {
  446. throw new ArgumentException("MediaSourceId is required");
  447. }
  448. var playlistText = string.Empty;
  449. if (string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase))
  450. {
  451. var audioBitrate = state.OutputAudioBitrate ?? 0;
  452. var videoBitrate = state.OutputVideoBitrate ?? 0;
  453. playlistText = GetMasterPlaylistFileText(state, videoBitrate + audioBitrate);
  454. }
  455. return ResultFactory.GetResult(playlistText, MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary<string, string>());
  456. }
  457. private string GetMasterPlaylistFileText(StreamState state, int totalBitrate)
  458. {
  459. var builder = new StringBuilder();
  460. builder.AppendLine("#EXTM3U");
  461. var queryStringIndex = Request.RawUrl.IndexOf('?');
  462. var queryString = queryStringIndex == -1 ? string.Empty : Request.RawUrl.Substring(queryStringIndex);
  463. var isLiveStream = (state.RunTimeTicks ?? 0) == 0;
  464. // Main stream
  465. var playlistUrl = isLiveStream ? "live.m3u8" : "main.m3u8";
  466. playlistUrl += queryString;
  467. var request = state.Request;
  468. var subtitleStreams = state.MediaSource
  469. .MediaStreams
  470. .Where(i => i.IsTextSubtitleStream)
  471. .ToList();
  472. var subtitleGroup = subtitleStreams.Count > 0 &&
  473. (request is GetMasterHlsVideoPlaylist) &&
  474. ((GetMasterHlsVideoPlaylist)request).SubtitleMethod == SubtitleDeliveryMethod.Hls ?
  475. "subs" :
  476. null;
  477. AppendPlaylist(builder, playlistUrl, totalBitrate, subtitleGroup);
  478. if (EnableAdaptiveBitrateStreaming(state, isLiveStream))
  479. {
  480. var requestedVideoBitrate = state.VideoRequest == null ? 0 : state.VideoRequest.VideoBitRate ?? 0;
  481. // By default, vary by just 200k
  482. var variation = GetBitrateVariation(totalBitrate);
  483. var newBitrate = totalBitrate - variation;
  484. var variantUrl = ReplaceBitrate(playlistUrl, requestedVideoBitrate, (requestedVideoBitrate - variation));
  485. AppendPlaylist(builder, variantUrl, newBitrate, subtitleGroup);
  486. variation *= 2;
  487. newBitrate = totalBitrate - variation;
  488. variantUrl = ReplaceBitrate(playlistUrl, requestedVideoBitrate, (requestedVideoBitrate - variation));
  489. AppendPlaylist(builder, variantUrl, newBitrate, subtitleGroup);
  490. }
  491. if (!string.IsNullOrWhiteSpace(subtitleGroup))
  492. {
  493. AddSubtitles(state, subtitleStreams, builder);
  494. }
  495. return builder.ToString();
  496. }
  497. private string ReplaceBitrate(string url, int oldValue, int newValue)
  498. {
  499. return url.Replace(
  500. "videobitrate=" + oldValue.ToString(UsCulture),
  501. "videobitrate=" + newValue.ToString(UsCulture),
  502. StringComparison.OrdinalIgnoreCase);
  503. }
  504. private void AddSubtitles(StreamState state, IEnumerable<MediaStream> subtitles, StringBuilder builder)
  505. {
  506. var selectedIndex = state.SubtitleStream == null ? (int?)null : state.SubtitleStream.Index;
  507. foreach (var stream in subtitles)
  508. {
  509. const string format = "#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID=\"subs\",NAME=\"{0}\",DEFAULT={1},FORCED={2},URI=\"{3}\",LANGUAGE=\"{4}\"";
  510. var name = stream.Language;
  511. var isDefault = selectedIndex.HasValue && selectedIndex.Value == stream.Index;
  512. var isForced = stream.IsForced;
  513. if (string.IsNullOrWhiteSpace(name)) name = stream.Codec ?? "Unknown";
  514. var url = string.Format("{0}/Subtitles/{1}/subtitles.m3u8?SegmentLength={2}",
  515. state.Request.MediaSourceId,
  516. stream.Index.ToString(UsCulture),
  517. 30.ToString(UsCulture));
  518. var line = string.Format(format,
  519. name,
  520. isDefault ? "YES" : "NO",
  521. isForced ? "YES" : "NO",
  522. url,
  523. stream.Language ?? "Unknown");
  524. builder.AppendLine(line);
  525. }
  526. }
  527. private bool EnableAdaptiveBitrateStreaming(StreamState state, bool isLiveStream)
  528. {
  529. // Within the local network this will likely do more harm than good.
  530. if (Request.IsLocal || NetworkManager.IsInLocalNetwork(Request.RemoteIp))
  531. {
  532. return false;
  533. }
  534. var request = state.Request as IMasterHlsRequest;
  535. if (request != null && !request.EnableAdaptiveBitrateStreaming)
  536. {
  537. return false;
  538. }
  539. if (isLiveStream || string.IsNullOrWhiteSpace(state.MediaPath))
  540. {
  541. // Opening live streams is so slow it's not even worth it
  542. return false;
  543. }
  544. if (string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  545. {
  546. return false;
  547. }
  548. if (string.Equals(state.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase))
  549. {
  550. return false;
  551. }
  552. if (!state.IsOutputVideo)
  553. {
  554. return false;
  555. }
  556. // Having problems in android
  557. return false;
  558. //return state.VideoRequest.VideoBitRate.HasValue;
  559. }
  560. private void AppendPlaylist(StringBuilder builder, string url, int bitrate, string subtitleGroup)
  561. {
  562. var header = "#EXT-X-STREAM-INF:BANDWIDTH=" + bitrate.ToString(UsCulture);
  563. if (!string.IsNullOrWhiteSpace(subtitleGroup))
  564. {
  565. header += string.Format(",SUBTITLES=\"{0}\"", subtitleGroup);
  566. }
  567. builder.AppendLine(header);
  568. builder.AppendLine(url);
  569. }
  570. private int GetBitrateVariation(int bitrate)
  571. {
  572. // By default, vary by just 50k
  573. var variation = 50000;
  574. if (bitrate >= 10000000)
  575. {
  576. variation = 2000000;
  577. }
  578. else if (bitrate >= 5000000)
  579. {
  580. variation = 1500000;
  581. }
  582. else if (bitrate >= 3000000)
  583. {
  584. variation = 1000000;
  585. }
  586. else if (bitrate >= 2000000)
  587. {
  588. variation = 500000;
  589. }
  590. else if (bitrate >= 1000000)
  591. {
  592. variation = 300000;
  593. }
  594. else if (bitrate >= 600000)
  595. {
  596. variation = 200000;
  597. }
  598. else if (bitrate >= 400000)
  599. {
  600. variation = 100000;
  601. }
  602. return variation;
  603. }
  604. private async Task<object> GetVariantPlaylistInternal(StreamRequest request, bool isOutputVideo, string name)
  605. {
  606. var state = await GetState(request, CancellationToken.None).ConfigureAwait(false);
  607. var builder = new StringBuilder();
  608. builder.AppendLine("#EXTM3U");
  609. builder.AppendLine("#EXT-X-VERSION:3");
  610. builder.AppendLine("#EXT-X-TARGETDURATION:" + (state.SegmentLength).ToString(UsCulture));
  611. builder.AppendLine("#EXT-X-MEDIA-SEQUENCE:0");
  612. var queryStringIndex = Request.RawUrl.IndexOf('?');
  613. var queryString = queryStringIndex == -1 ? string.Empty : Request.RawUrl.Substring(queryStringIndex);
  614. var seconds = TimeSpan.FromTicks(state.RunTimeTicks ?? 0).TotalSeconds;
  615. var index = 0;
  616. while (seconds > 0)
  617. {
  618. var length = seconds >= state.SegmentLength ? state.SegmentLength : seconds;
  619. builder.AppendLine("#EXTINF:" + length.ToString(UsCulture) + ",");
  620. builder.AppendLine(string.Format("hlsdynamic/{0}/{1}{2}{3}",
  621. name,
  622. index.ToString(UsCulture),
  623. GetSegmentFileExtension(isOutputVideo),
  624. queryString));
  625. seconds -= state.SegmentLength;
  626. index++;
  627. }
  628. builder.AppendLine("#EXT-X-ENDLIST");
  629. var playlistText = builder.ToString();
  630. return ResultFactory.GetResult(playlistText, MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary<string, string>());
  631. }
  632. protected override string GetAudioArguments(StreamState state)
  633. {
  634. if (!state.IsOutputVideo)
  635. {
  636. var audioTranscodeParams = new List<string>();
  637. if (state.OutputAudioBitrate.HasValue)
  638. {
  639. audioTranscodeParams.Add("-ab " + state.OutputAudioBitrate.Value.ToString(UsCulture));
  640. }
  641. if (state.OutputAudioChannels.HasValue)
  642. {
  643. audioTranscodeParams.Add("-ac " + state.OutputAudioChannels.Value.ToString(UsCulture));
  644. }
  645. if (state.OutputAudioSampleRate.HasValue)
  646. {
  647. audioTranscodeParams.Add("-ar " + state.OutputAudioSampleRate.Value.ToString(UsCulture));
  648. }
  649. audioTranscodeParams.Add("-vn");
  650. return string.Join(" ", audioTranscodeParams.ToArray());
  651. }
  652. var codec = state.OutputAudioCodec;
  653. if (string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase))
  654. {
  655. return "-codec:a:0 copy";
  656. }
  657. var args = "-codec:a:0 " + codec;
  658. var channels = state.OutputAudioChannels;
  659. if (channels.HasValue)
  660. {
  661. args += " -ac " + channels.Value;
  662. }
  663. var bitrate = state.OutputAudioBitrate;
  664. if (bitrate.HasValue)
  665. {
  666. args += " -ab " + bitrate.Value.ToString(UsCulture);
  667. }
  668. args += " " + GetAudioFilterParam(state, true);
  669. return args;
  670. }
  671. protected override string GetVideoArguments(StreamState state)
  672. {
  673. if (!state.IsOutputVideo)
  674. {
  675. return string.Empty;
  676. }
  677. var codec = state.OutputVideoCodec;
  678. var args = "-codec:v:0 " + codec;
  679. if (state.EnableMpegtsM2TsMode)
  680. {
  681. args += " -mpegts_m2ts_mode 1";
  682. }
  683. // See if we can save come cpu cycles by avoiding encoding
  684. if (string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase))
  685. {
  686. if (state.VideoStream != null && IsH264(state.VideoStream))
  687. {
  688. args += " -bsf:v h264_mp4toannexb";
  689. }
  690. args += " -flags -global_header -sc_threshold 0";
  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. args += " -flags +loop-global_header -sc_threshold 0";
  710. }
  711. if (!EnableSplitTranscoding(state))
  712. {
  713. args += " -copyts";
  714. }
  715. return args;
  716. }
  717. protected override string GetCommandLineArguments(string outputPath, StreamState state, bool isEncoding)
  718. {
  719. var threads = GetNumberOfThreads(state, false);
  720. var inputModifier = GetInputModifier(state, false);
  721. // If isEncoding is true we're actually starting ffmpeg
  722. var startNumberParam = isEncoding ? GetStartNumber(state).ToString(UsCulture) : "0";
  723. var toTimeParam = string.Empty;
  724. var timestampOffsetParam = string.Empty;
  725. if (EnableSplitTranscoding(state))
  726. {
  727. var startTime = state.Request.StartTimeTicks ?? 0;
  728. var durationSeconds = ApiEntryPoint.Instance.GetEncodingOptions().ThrottleThresholdInSeconds;
  729. var endTime = startTime + TimeSpan.FromSeconds(durationSeconds).Ticks;
  730. endTime = Math.Min(endTime, state.RunTimeTicks.Value);
  731. if (endTime < state.RunTimeTicks.Value)
  732. {
  733. //toTimeParam = " -to " + MediaEncoder.GetTimeParameter(endTime);
  734. toTimeParam = " -t " + MediaEncoder.GetTimeParameter(TimeSpan.FromSeconds(durationSeconds).Ticks);
  735. }
  736. if (state.IsOutputVideo && !string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase) && (state.Request.StartTimeTicks ?? 0) > 0)
  737. {
  738. timestampOffsetParam = " -output_ts_offset " + MediaEncoder.GetTimeParameter(state.Request.StartTimeTicks ?? 0).ToString(CultureInfo.InvariantCulture);
  739. }
  740. }
  741. var mapArgs = state.IsOutputVideo ? GetMapArgs(state) : string.Empty;
  742. //var outputTsArg = Path.Combine(Path.GetDirectoryName(outputPath), Path.GetFileNameWithoutExtension(outputPath)) + "%d" + GetSegmentFileExtension(state);
  743. //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}\"",
  744. // inputModifier,
  745. // GetInputArgument(state),
  746. // threads,
  747. // mapArgs,
  748. // GetVideoArguments(state),
  749. // GetAudioArguments(state),
  750. // state.SegmentLength.ToString(UsCulture),
  751. // startNumberParam,
  752. // outputPath,
  753. // outputTsArg,
  754. // slowSeekParam,
  755. // toTimeParam
  756. // ).Trim();
  757. 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}\"",
  758. inputModifier,
  759. GetInputArgument(state),
  760. threads,
  761. mapArgs,
  762. GetVideoArguments(state),
  763. timestampOffsetParam,
  764. GetAudioArguments(state),
  765. state.SegmentLength.ToString(UsCulture),
  766. startNumberParam,
  767. state.HlsListSize.ToString(UsCulture),
  768. outputPath,
  769. toTimeParam
  770. ).Trim();
  771. }
  772. protected override bool EnableThrottling(StreamState state)
  773. {
  774. return !EnableSplitTranscoding(state);
  775. }
  776. private bool EnableSplitTranscoding(StreamState state)
  777. {
  778. if (string.Equals(Request.QueryString["EnableSplitTranscoding"], "false", StringComparison.OrdinalIgnoreCase))
  779. {
  780. return false;
  781. }
  782. if (string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  783. {
  784. return false;
  785. }
  786. if (string.Equals(state.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase))
  787. {
  788. return false;
  789. }
  790. return state.RunTimeTicks.HasValue && state.IsOutputVideo;
  791. }
  792. protected override bool EnableStreamCopy
  793. {
  794. get
  795. {
  796. return false;
  797. }
  798. }
  799. /// <summary>
  800. /// Gets the segment file extension.
  801. /// </summary>
  802. /// <param name="state">The state.</param>
  803. /// <returns>System.String.</returns>
  804. protected override string GetSegmentFileExtension(StreamState state)
  805. {
  806. return GetSegmentFileExtension(state.IsOutputVideo);
  807. }
  808. protected string GetSegmentFileExtension(bool isOutputVideo)
  809. {
  810. return isOutputVideo ? ".ts" : ".ts";
  811. }
  812. }
  813. }