DynamicHlsService.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977
  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.Generic;
  17. using System.Globalization;
  18. using System.IO;
  19. using System.Linq;
  20. using System.Text;
  21. using System.Threading;
  22. using System.Threading.Tasks;
  23. using MimeTypes = MediaBrowser.Model.Net.MimeTypes;
  24. namespace MediaBrowser.Api.Playback.Hls
  25. {
  26. /// <summary>
  27. /// Options is needed for chromecast. Threw Head in there since it's related
  28. /// </summary>
  29. [Route("/Videos/{Id}/master.m3u8", "GET", Summary = "Gets a video stream using HTTP live streaming.")]
  30. [Route("/Videos/{Id}/master.m3u8", "HEAD", Summary = "Gets a video stream using HTTP live streaming.")]
  31. public class GetMasterHlsVideoPlaylist : VideoStreamRequest, IMasterHlsRequest
  32. {
  33. public bool EnableAdaptiveBitrateStreaming { get; set; }
  34. public GetMasterHlsVideoPlaylist()
  35. {
  36. EnableAdaptiveBitrateStreaming = true;
  37. }
  38. }
  39. [Route("/Audio/{Id}/master.m3u8", "GET", Summary = "Gets an audio stream using HTTP live streaming.")]
  40. [Route("/Audio/{Id}/master.m3u8", "HEAD", Summary = "Gets an audio stream using HTTP live streaming.")]
  41. public class GetMasterHlsAudioPlaylist : StreamRequest, IMasterHlsRequest
  42. {
  43. public bool EnableAdaptiveBitrateStreaming { get; set; }
  44. public GetMasterHlsAudioPlaylist()
  45. {
  46. EnableAdaptiveBitrateStreaming = true;
  47. }
  48. }
  49. public interface IMasterHlsRequest
  50. {
  51. bool EnableAdaptiveBitrateStreaming { get; set; }
  52. }
  53. [Route("/Videos/{Id}/main.m3u8", "GET", Summary = "Gets a video stream using HTTP live streaming.")]
  54. public class GetVariantHlsVideoPlaylist : VideoStreamRequest
  55. {
  56. }
  57. [Route("/Audio/{Id}/main.m3u8", "GET", Summary = "Gets an audio stream using HTTP live streaming.")]
  58. public class GetVariantHlsAudioPlaylist : StreamRequest
  59. {
  60. }
  61. [Route("/Videos/{Id}/hlsdynamic/{PlaylistId}/{SegmentId}.ts", "GET")]
  62. [Api(Description = "Gets an Http live streaming segment file. Internal use only.")]
  63. public class GetHlsVideoSegment : VideoStreamRequest
  64. {
  65. public string PlaylistId { get; set; }
  66. /// <summary>
  67. /// Gets or sets the segment id.
  68. /// </summary>
  69. /// <value>The segment id.</value>
  70. public string SegmentId { get; set; }
  71. }
  72. [Route("/Audio/{Id}/hlsdynamic/{PlaylistId}/{SegmentId}.aac", "GET")]
  73. [Route("/Audio/{Id}/hlsdynamic/{PlaylistId}/{SegmentId}.ts", "GET")]
  74. [Api(Description = "Gets an Http live streaming segment file. Internal use only.")]
  75. public class GetHlsAudioSegment : StreamRequest
  76. {
  77. public string PlaylistId { get; set; }
  78. /// <summary>
  79. /// Gets or sets the segment id.
  80. /// </summary>
  81. /// <value>The segment id.</value>
  82. public string SegmentId { get; set; }
  83. }
  84. public class DynamicHlsService : BaseHlsService
  85. {
  86. 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)
  87. : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, dlnaManager, subtitleEncoder, deviceManager, mediaSourceManager, zipClient, jsonSerializer)
  88. {
  89. NetworkManager = networkManager;
  90. }
  91. protected INetworkManager NetworkManager { get; private set; }
  92. public Task<object> Get(GetMasterHlsVideoPlaylist request)
  93. {
  94. return GetMasterPlaylistInternal(request, "GET");
  95. }
  96. public Task<object> Head(GetMasterHlsVideoPlaylist request)
  97. {
  98. return GetMasterPlaylistInternal(request, "HEAD");
  99. }
  100. public Task<object> Get(GetMasterHlsAudioPlaylist request)
  101. {
  102. return GetMasterPlaylistInternal(request, "GET");
  103. }
  104. public Task<object> Head(GetMasterHlsAudioPlaylist request)
  105. {
  106. return GetMasterPlaylistInternal(request, "HEAD");
  107. }
  108. public Task<object> Get(GetVariantHlsVideoPlaylist request)
  109. {
  110. return GetVariantPlaylistInternal(request, true, "main");
  111. }
  112. public Task<object> Get(GetVariantHlsAudioPlaylist request)
  113. {
  114. return GetVariantPlaylistInternal(request, false, "main");
  115. }
  116. public Task<object> Get(GetHlsVideoSegment request)
  117. {
  118. return GetDynamicSegment(request, request.SegmentId);
  119. }
  120. public Task<object> Get(GetHlsAudioSegment request)
  121. {
  122. return GetDynamicSegment(request, request.SegmentId);
  123. }
  124. private async Task<object> GetDynamicSegment(StreamRequest request, string segmentId)
  125. {
  126. if ((request.StartTimeTicks ?? 0) > 0)
  127. {
  128. throw new ArgumentException("StartTimeTicks is not allowed.");
  129. }
  130. var cancellationTokenSource = new CancellationTokenSource();
  131. var cancellationToken = cancellationTokenSource.Token;
  132. var requestedIndex = int.Parse(segmentId, NumberStyles.Integer, UsCulture);
  133. var state = await GetState(request, cancellationToken).ConfigureAwait(false);
  134. var playlistPath = Path.ChangeExtension(state.OutputFilePath, ".m3u8");
  135. var segmentPath = GetSegmentPath(state, playlistPath, requestedIndex);
  136. var segmentLength = state.SegmentLength;
  137. var segmentExtension = GetSegmentFileExtension(state);
  138. TranscodingJob job = null;
  139. if (File.Exists(segmentPath))
  140. {
  141. job = ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
  142. return await GetSegmentResult(playlistPath, segmentPath, requestedIndex, segmentLength, job, cancellationToken).ConfigureAwait(false);
  143. }
  144. await ApiEntryPoint.Instance.TranscodingStartLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);
  145. try
  146. {
  147. if (File.Exists(segmentPath))
  148. {
  149. job = ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
  150. return await GetSegmentResult(playlistPath, segmentPath, requestedIndex, segmentLength, job, cancellationToken).ConfigureAwait(false);
  151. }
  152. else
  153. {
  154. var startTranscoding = false;
  155. var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath, segmentExtension);
  156. var segmentGapRequiringTranscodingChange = 24 / state.SegmentLength;
  157. if (currentTranscodingIndex == null)
  158. {
  159. Logger.Debug("Starting transcoding because currentTranscodingIndex=null");
  160. startTranscoding = true;
  161. }
  162. else if (requestedIndex < currentTranscodingIndex.Value)
  163. {
  164. Logger.Debug("Starting transcoding because requestedIndex={0} and currentTranscodingIndex={1}", requestedIndex, currentTranscodingIndex);
  165. startTranscoding = true;
  166. }
  167. else if ((requestedIndex - currentTranscodingIndex.Value) > segmentGapRequiringTranscodingChange)
  168. {
  169. Logger.Debug("Starting transcoding because segmentGap is {0} and max allowed gap is {1}. requestedIndex={2}", (requestedIndex - currentTranscodingIndex.Value), segmentGapRequiringTranscodingChange, requestedIndex);
  170. startTranscoding = true;
  171. }
  172. if (startTranscoding)
  173. {
  174. // If the playlist doesn't already exist, startup ffmpeg
  175. try
  176. {
  177. ApiEntryPoint.Instance.KillTranscodingJobs(request.DeviceId, request.PlaySessionId, p => false);
  178. if (currentTranscodingIndex.HasValue)
  179. {
  180. DeleteLastFile(playlistPath, segmentExtension, 0);
  181. }
  182. request.StartTimeTicks = GetSeekPositionTicks(state, playlistPath, requestedIndex);
  183. job = await StartFfMpeg(state, playlistPath, cancellationTokenSource).ConfigureAwait(false);
  184. }
  185. catch
  186. {
  187. state.Dispose();
  188. throw;
  189. }
  190. //await WaitForMinimumSegmentCount(playlistPath, 1, cancellationTokenSource.Token).ConfigureAwait(false);
  191. }
  192. else
  193. {
  194. job = ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
  195. if (job.TranscodingThrottler != null)
  196. {
  197. job.TranscodingThrottler.UnpauseTranscoding();
  198. }
  199. }
  200. }
  201. }
  202. finally
  203. {
  204. ApiEntryPoint.Instance.TranscodingStartLock.Release();
  205. }
  206. //Logger.Info("waiting for {0}", segmentPath);
  207. //while (!File.Exists(segmentPath))
  208. //{
  209. // await Task.Delay(50, cancellationToken).ConfigureAwait(false);
  210. //}
  211. Logger.Info("returning {0}", segmentPath);
  212. job = job ?? ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
  213. return await GetSegmentResult(playlistPath, segmentPath, requestedIndex, segmentLength, job, cancellationToken).ConfigureAwait(false);
  214. }
  215. // 256k
  216. private const int BufferSize = 262144;
  217. private long GetSeekPositionTicks(StreamState state, string playlist, int requestedIndex)
  218. {
  219. double startSeconds = 0;
  220. for (var i = 0; i < requestedIndex; i++)
  221. {
  222. var segmentPath = GetSegmentPath(state, playlist, i);
  223. //double length;
  224. //if (SegmentLengths.TryGetValue(Path.GetFileName(segmentPath), out length))
  225. //{
  226. // Logger.Debug("Found segment length of {0} for index {1}", length, i);
  227. // startSeconds += length;
  228. //}
  229. //else
  230. //{
  231. // startSeconds += state.SegmentLength;
  232. //}
  233. startSeconds += state.SegmentLength;
  234. }
  235. var position = TimeSpan.FromSeconds(startSeconds).Ticks;
  236. return position;
  237. }
  238. public int? GetCurrentTranscodingIndex(string playlist, string segmentExtension)
  239. {
  240. var job = ApiEntryPoint.Instance.GetTranscodingJob(playlist, TranscodingJobType);
  241. if (job == null || job.HasExited)
  242. {
  243. return null;
  244. }
  245. var file = GetLastTranscodingFile(playlist, segmentExtension, FileSystem);
  246. if (file == null)
  247. {
  248. return null;
  249. }
  250. var playlistFilename = Path.GetFileNameWithoutExtension(playlist);
  251. var indexString = Path.GetFileNameWithoutExtension(file.Name).Substring(playlistFilename.Length);
  252. return int.Parse(indexString, NumberStyles.Integer, UsCulture);
  253. }
  254. private void DeleteLastFile(string playlistPath, string segmentExtension, int retryCount)
  255. {
  256. var file = GetLastTranscodingFile(playlistPath, segmentExtension, FileSystem);
  257. if (file != null)
  258. {
  259. DeleteFile(file, retryCount);
  260. }
  261. }
  262. private void DeleteFile(FileInfo file, int retryCount)
  263. {
  264. if (retryCount >= 5)
  265. {
  266. return;
  267. }
  268. try
  269. {
  270. FileSystem.DeleteFile(file.FullName);
  271. }
  272. catch (IOException ex)
  273. {
  274. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, file.FullName);
  275. Thread.Sleep(100);
  276. DeleteFile(file, retryCount + 1);
  277. }
  278. catch (Exception ex)
  279. {
  280. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, file.FullName);
  281. }
  282. }
  283. private static FileInfo GetLastTranscodingFile(string playlist, string segmentExtension, IFileSystem fileSystem)
  284. {
  285. var folder = Path.GetDirectoryName(playlist);
  286. var filePrefix = Path.GetFileNameWithoutExtension(playlist) ?? string.Empty;
  287. try
  288. {
  289. return new DirectoryInfo(folder)
  290. .EnumerateFiles("*", SearchOption.TopDirectoryOnly)
  291. .Where(i => string.Equals(i.Extension, segmentExtension, StringComparison.OrdinalIgnoreCase) && Path.GetFileNameWithoutExtension(i.Name).StartsWith(filePrefix, StringComparison.OrdinalIgnoreCase))
  292. .OrderByDescending(fileSystem.GetLastWriteTimeUtc)
  293. .FirstOrDefault();
  294. }
  295. catch (DirectoryNotFoundException)
  296. {
  297. return null;
  298. }
  299. }
  300. protected override int GetStartNumber(StreamState state)
  301. {
  302. return GetStartNumber(state.VideoRequest);
  303. }
  304. private int GetStartNumber(VideoStreamRequest request)
  305. {
  306. var segmentId = "0";
  307. var segmentRequest = request as GetHlsVideoSegment;
  308. if (segmentRequest != null)
  309. {
  310. segmentId = segmentRequest.SegmentId;
  311. }
  312. return int.Parse(segmentId, NumberStyles.Integer, UsCulture);
  313. }
  314. private string GetSegmentPath(StreamState state, string playlist, int index)
  315. {
  316. var folder = Path.GetDirectoryName(playlist);
  317. var filename = Path.GetFileNameWithoutExtension(playlist);
  318. return Path.Combine(folder, filename + index.ToString(UsCulture) + GetSegmentFileExtension(state));
  319. }
  320. private async Task<object> GetSegmentResult(string playlistPath,
  321. string segmentPath,
  322. int segmentIndex,
  323. int segmentLength,
  324. TranscodingJob transcodingJob,
  325. CancellationToken cancellationToken)
  326. {
  327. // If all transcoding has completed, just return immediately
  328. if (transcodingJob != null && transcodingJob.HasExited && File.Exists(segmentPath))
  329. {
  330. return GetSegmentResult(segmentPath, segmentIndex, segmentLength, transcodingJob);
  331. }
  332. var segmentFilename = Path.GetFileName(segmentPath);
  333. while (!cancellationToken.IsCancellationRequested)
  334. {
  335. try
  336. {
  337. using (var fileStream = GetPlaylistFileStream(playlistPath))
  338. {
  339. using (var reader = new StreamReader(fileStream, Encoding.UTF8, true, BufferSize))
  340. {
  341. var text = await reader.ReadToEndAsync().ConfigureAwait(false);
  342. // If it appears in the playlist, it's done
  343. if (text.IndexOf(segmentFilename, StringComparison.OrdinalIgnoreCase) != -1)
  344. {
  345. if (File.Exists(segmentPath))
  346. {
  347. return GetSegmentResult(segmentPath, segmentIndex, segmentLength, transcodingJob);
  348. }
  349. //break;
  350. }
  351. }
  352. }
  353. }
  354. catch (IOException)
  355. {
  356. // May get an error if the file is locked
  357. }
  358. await Task.Delay(100, cancellationToken).ConfigureAwait(false);
  359. }
  360. // if a different file is encoding, it's done
  361. //var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath);
  362. //if (currentTranscodingIndex > segmentIndex)
  363. //{
  364. //return GetSegmentResult(segmentPath, segmentIndex);
  365. //}
  366. //// Wait for the file to stop being written to, then stream it
  367. //var length = new FileInfo(segmentPath).Length;
  368. //var eofCount = 0;
  369. //while (eofCount < 10)
  370. //{
  371. // var info = new FileInfo(segmentPath);
  372. // if (!info.Exists)
  373. // {
  374. // break;
  375. // }
  376. // var newLength = info.Length;
  377. // if (newLength == length)
  378. // {
  379. // eofCount++;
  380. // }
  381. // else
  382. // {
  383. // eofCount = 0;
  384. // }
  385. // length = newLength;
  386. // await Task.Delay(100, cancellationToken).ConfigureAwait(false);
  387. //}
  388. cancellationToken.ThrowIfCancellationRequested();
  389. return GetSegmentResult(segmentPath, segmentIndex, segmentLength, transcodingJob);
  390. }
  391. private object GetSegmentResult(string segmentPath, int index, int segmentLength, TranscodingJob transcodingJob)
  392. {
  393. var segmentEndingSeconds = (1 + index) * segmentLength;
  394. var segmentEndingPositionTicks = TimeSpan.FromSeconds(segmentEndingSeconds).Ticks;
  395. return ResultFactory.GetStaticFileResult(Request, new StaticFileResultOptions
  396. {
  397. Path = segmentPath,
  398. FileShare = FileShare.ReadWrite,
  399. OnComplete = () =>
  400. {
  401. if (transcodingJob != null)
  402. {
  403. transcodingJob.DownloadPositionTicks = Math.Max(transcodingJob.DownloadPositionTicks ?? segmentEndingPositionTicks, segmentEndingPositionTicks);
  404. ApiEntryPoint.Instance.OnTranscodeEndRequest(transcodingJob);
  405. }
  406. }
  407. });
  408. }
  409. private async Task<object> GetMasterPlaylistInternal(StreamRequest request, string method)
  410. {
  411. var state = await GetState(request, CancellationToken.None).ConfigureAwait(false);
  412. if (string.IsNullOrEmpty(request.MediaSourceId))
  413. {
  414. throw new ArgumentException("MediaSourceId is required");
  415. }
  416. var playlistText = string.Empty;
  417. if (string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase))
  418. {
  419. var audioBitrate = state.OutputAudioBitrate ?? 0;
  420. var videoBitrate = state.OutputVideoBitrate ?? 0;
  421. playlistText = GetMasterPlaylistFileText(state, videoBitrate + audioBitrate);
  422. }
  423. return ResultFactory.GetResult(playlistText, MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary<string, string>());
  424. }
  425. private string GetMasterPlaylistFileText(StreamState state, int totalBitrate)
  426. {
  427. var builder = new StringBuilder();
  428. builder.AppendLine("#EXTM3U");
  429. var isLiveStream = (state.RunTimeTicks ?? 0) == 0;
  430. var queryStringIndex = Request.RawUrl.IndexOf('?');
  431. var queryString = queryStringIndex == -1 ? string.Empty : Request.RawUrl.Substring(queryStringIndex);
  432. // Main stream
  433. var playlistUrl = isLiveStream ? "live.m3u8" : "main.m3u8";
  434. playlistUrl += queryString;
  435. var request = state.Request;
  436. var subtitleStreams = state.MediaSource
  437. .MediaStreams
  438. .Where(i => i.IsTextSubtitleStream)
  439. .ToList();
  440. var subtitleGroup = subtitleStreams.Count > 0 &&
  441. (request is GetMasterHlsVideoPlaylist) &&
  442. ((GetMasterHlsVideoPlaylist)request).SubtitleMethod == SubtitleDeliveryMethod.Hls ?
  443. "subs" :
  444. null;
  445. AppendPlaylist(builder, playlistUrl, totalBitrate, subtitleGroup);
  446. if (EnableAdaptiveBitrateStreaming(state, isLiveStream))
  447. {
  448. var requestedVideoBitrate = state.VideoRequest == null ? 0 : state.VideoRequest.VideoBitRate ?? 0;
  449. // By default, vary by just 200k
  450. var variation = GetBitrateVariation(totalBitrate);
  451. var newBitrate = totalBitrate - variation;
  452. var variantUrl = ReplaceBitrate(playlistUrl, requestedVideoBitrate, (requestedVideoBitrate - variation));
  453. AppendPlaylist(builder, variantUrl, newBitrate, subtitleGroup);
  454. variation *= 2;
  455. newBitrate = totalBitrate - variation;
  456. variantUrl = ReplaceBitrate(playlistUrl, requestedVideoBitrate, (requestedVideoBitrate - variation));
  457. AppendPlaylist(builder, variantUrl, newBitrate, subtitleGroup);
  458. }
  459. if (!string.IsNullOrWhiteSpace(subtitleGroup))
  460. {
  461. AddSubtitles(state, subtitleStreams, builder);
  462. }
  463. return builder.ToString();
  464. }
  465. private string ReplaceBitrate(string url, int oldValue, int newValue)
  466. {
  467. return url.Replace(
  468. "videobitrate=" + oldValue.ToString(UsCulture),
  469. "videobitrate=" + newValue.ToString(UsCulture),
  470. StringComparison.OrdinalIgnoreCase);
  471. }
  472. private void AddSubtitles(StreamState state, IEnumerable<MediaStream> subtitles, StringBuilder builder)
  473. {
  474. var selectedIndex = state.SubtitleStream == null ? (int?)null : state.SubtitleStream.Index;
  475. foreach (var stream in subtitles)
  476. {
  477. const string format = "#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID=\"subs\",NAME=\"{0}\",DEFAULT={1},FORCED={2},URI=\"{3}\",LANGUAGE=\"{4}\"";
  478. var name = stream.Language;
  479. var isDefault = selectedIndex.HasValue && selectedIndex.Value == stream.Index;
  480. var isForced = stream.IsForced;
  481. if (string.IsNullOrWhiteSpace(name)) name = stream.Codec ?? "Unknown";
  482. var url = string.Format("{0}/Subtitles/{1}/subtitles.m3u8?SegmentLength={2}",
  483. state.Request.MediaSourceId,
  484. stream.Index.ToString(UsCulture),
  485. 30.ToString(UsCulture));
  486. var line = string.Format(format,
  487. name,
  488. isDefault ? "YES" : "NO",
  489. isForced ? "YES" : "NO",
  490. url,
  491. stream.Language ?? "Unknown");
  492. builder.AppendLine(line);
  493. }
  494. }
  495. private bool EnableAdaptiveBitrateStreaming(StreamState state, bool isLiveStream)
  496. {
  497. // Within the local network this will likely do more harm than good.
  498. if (Request.IsLocal || NetworkManager.IsInLocalNetwork(Request.RemoteIp))
  499. {
  500. return false;
  501. }
  502. var request = state.Request as IMasterHlsRequest;
  503. if (request != null && !request.EnableAdaptiveBitrateStreaming)
  504. {
  505. return false;
  506. }
  507. if (isLiveStream || string.IsNullOrWhiteSpace(state.MediaPath))
  508. {
  509. // Opening live streams is so slow it's not even worth it
  510. return false;
  511. }
  512. if (string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  513. {
  514. return false;
  515. }
  516. if (string.Equals(state.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase))
  517. {
  518. return false;
  519. }
  520. if (!state.IsOutputVideo)
  521. {
  522. return false;
  523. }
  524. // Having problems in android
  525. return false;
  526. //return state.VideoRequest.VideoBitRate.HasValue;
  527. }
  528. private void AppendPlaylist(StringBuilder builder, string url, int bitrate, string subtitleGroup)
  529. {
  530. var header = "#EXT-X-STREAM-INF:BANDWIDTH=" + bitrate.ToString(UsCulture);
  531. if (!string.IsNullOrWhiteSpace(subtitleGroup))
  532. {
  533. header += string.Format(",SUBTITLES=\"{0}\"", subtitleGroup);
  534. }
  535. builder.AppendLine(header);
  536. builder.AppendLine(url);
  537. }
  538. private int GetBitrateVariation(int bitrate)
  539. {
  540. // By default, vary by just 50k
  541. var variation = 50000;
  542. if (bitrate >= 10000000)
  543. {
  544. variation = 2000000;
  545. }
  546. else if (bitrate >= 5000000)
  547. {
  548. variation = 1500000;
  549. }
  550. else if (bitrate >= 3000000)
  551. {
  552. variation = 1000000;
  553. }
  554. else if (bitrate >= 2000000)
  555. {
  556. variation = 500000;
  557. }
  558. else if (bitrate >= 1000000)
  559. {
  560. variation = 300000;
  561. }
  562. else if (bitrate >= 600000)
  563. {
  564. variation = 200000;
  565. }
  566. else if (bitrate >= 400000)
  567. {
  568. variation = 100000;
  569. }
  570. return variation;
  571. }
  572. private async Task<object> GetVariantPlaylistInternal(StreamRequest request, bool isOutputVideo, string name)
  573. {
  574. var state = await GetState(request, CancellationToken.None).ConfigureAwait(false);
  575. var builder = new StringBuilder();
  576. builder.AppendLine("#EXTM3U");
  577. builder.AppendLine("#EXT-X-VERSION:3");
  578. builder.AppendLine("#EXT-X-TARGETDURATION:" + (state.SegmentLength).ToString(UsCulture));
  579. builder.AppendLine("#EXT-X-MEDIA-SEQUENCE:0");
  580. var queryStringIndex = Request.RawUrl.IndexOf('?');
  581. var queryString = queryStringIndex == -1 ? string.Empty : Request.RawUrl.Substring(queryStringIndex);
  582. var seconds = TimeSpan.FromTicks(state.RunTimeTicks ?? 0).TotalSeconds;
  583. var index = 0;
  584. double segmentLength = state.SegmentLength;
  585. while (seconds > 0)
  586. {
  587. var length = seconds >= state.SegmentLength ? segmentLength : seconds;
  588. builder.AppendLine("#EXTINF:" + length.ToString("0.000000", UsCulture) + ",");
  589. builder.AppendLine(string.Format("hlsdynamic/{0}/{1}{2}{3}",
  590. name,
  591. index.ToString(UsCulture),
  592. GetSegmentFileExtension(isOutputVideo),
  593. queryString));
  594. seconds -= length;
  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. }