DynamicHlsService.cs 36 KB

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