2
0

DynamicHlsService.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  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 GetMasterHlsVideoStream : VideoStreamRequest
  33. {
  34. public bool EnableAdaptiveBitrateStreaming { get; set; }
  35. public GetMasterHlsVideoStream()
  36. {
  37. EnableAdaptiveBitrateStreaming = true;
  38. }
  39. }
  40. [Route("/Videos/{Id}/main.m3u8", "GET", Summary = "Gets a video stream using HTTP live streaming.")]
  41. public class GetMainHlsVideoStream : VideoStreamRequest
  42. {
  43. }
  44. /// <summary>
  45. /// Class GetHlsVideoSegment
  46. /// </summary>
  47. [Route("/Videos/{Id}/hlsdynamic/{PlaylistId}/{SegmentId}.ts", "GET")]
  48. [Api(Description = "Gets an Http live streaming segment file. Internal use only.")]
  49. public class GetDynamicHlsVideoSegment : VideoStreamRequest
  50. {
  51. public string PlaylistId { get; set; }
  52. /// <summary>
  53. /// Gets or sets the segment id.
  54. /// </summary>
  55. /// <value>The segment id.</value>
  56. public string SegmentId { get; set; }
  57. }
  58. public class DynamicHlsService : BaseHlsService
  59. {
  60. 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)
  61. : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, dlnaManager, subtitleEncoder, deviceManager, mediaSourceManager, zipClient, jsonSerializer)
  62. {
  63. NetworkManager = networkManager;
  64. }
  65. protected INetworkManager NetworkManager { get; private set; }
  66. public Task<object> Get(GetMasterHlsVideoStream request)
  67. {
  68. return GetAsync(request, "GET");
  69. }
  70. public Task<object> Head(GetMasterHlsVideoStream request)
  71. {
  72. return GetAsync(request, "HEAD");
  73. }
  74. public Task<object> Get(GetMainHlsVideoStream request)
  75. {
  76. return GetPlaylistAsync(request, "main");
  77. }
  78. public Task<object> Get(GetDynamicHlsVideoSegment request)
  79. {
  80. return GetDynamicSegment(request, request.SegmentId);
  81. }
  82. private async Task<object> GetDynamicSegment(VideoStreamRequest request, string segmentId)
  83. {
  84. if ((request.StartTimeTicks ?? 0) > 0)
  85. {
  86. throw new ArgumentException("StartTimeTicks is not allowed.");
  87. }
  88. var cancellationTokenSource = new CancellationTokenSource();
  89. var cancellationToken = cancellationTokenSource.Token;
  90. var requestedIndex = int.Parse(segmentId, NumberStyles.Integer, UsCulture);
  91. var state = await GetState(request, cancellationToken).ConfigureAwait(false);
  92. var playlistPath = Path.ChangeExtension(state.OutputFilePath, ".m3u8");
  93. var segmentPath = GetSegmentPath(playlistPath, requestedIndex);
  94. var segmentLength = state.SegmentLength;
  95. var segmentExtension = GetSegmentFileExtension(state);
  96. TranscodingJob job = null;
  97. if (File.Exists(segmentPath))
  98. {
  99. job = ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
  100. return await GetSegmentResult(playlistPath, segmentPath, requestedIndex, segmentLength, job, cancellationToken).ConfigureAwait(false);
  101. }
  102. await ApiEntryPoint.Instance.TranscodingStartLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);
  103. try
  104. {
  105. if (File.Exists(segmentPath))
  106. {
  107. job = ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
  108. return await GetSegmentResult(playlistPath, segmentPath, requestedIndex, segmentLength, job, cancellationToken).ConfigureAwait(false);
  109. }
  110. else
  111. {
  112. var startTranscoding = false;
  113. var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath, request.PlaySessionId, segmentExtension);
  114. var segmentGapRequiringTranscodingChange = 24 / state.SegmentLength;
  115. if (currentTranscodingIndex == null)
  116. {
  117. Logger.Debug("Starting transcoding because currentTranscodingIndex=null");
  118. startTranscoding = true;
  119. }
  120. else if (requestedIndex < currentTranscodingIndex.Value)
  121. {
  122. Logger.Debug("Starting transcoding because requestedIndex={0} and currentTranscodingIndex={1}", requestedIndex, currentTranscodingIndex);
  123. startTranscoding = true;
  124. }
  125. else if ((requestedIndex - currentTranscodingIndex.Value) > segmentGapRequiringTranscodingChange)
  126. {
  127. Logger.Debug("Starting transcoding because segmentGap is {0} and max allowed gap is {1}. requestedIndex={2}", (requestedIndex - currentTranscodingIndex.Value), segmentGapRequiringTranscodingChange, requestedIndex);
  128. startTranscoding = true;
  129. }
  130. if (startTranscoding)
  131. {
  132. // If the playlist doesn't already exist, startup ffmpeg
  133. try
  134. {
  135. ApiEntryPoint.Instance.KillTranscodingJobs(request.DeviceId, request.PlaySessionId, p => false);
  136. await ReadSegmentLengths(playlistPath).ConfigureAwait(false);
  137. if (currentTranscodingIndex.HasValue)
  138. {
  139. DeleteLastFile(playlistPath, segmentExtension, 0);
  140. }
  141. request.StartTimeTicks = GetSeekPositionTicks(state, playlistPath, requestedIndex);
  142. job = await StartFfMpeg(state, playlistPath, cancellationTokenSource).ConfigureAwait(false);
  143. }
  144. catch
  145. {
  146. state.Dispose();
  147. throw;
  148. }
  149. //await WaitForMinimumSegmentCount(playlistPath, 1, cancellationTokenSource.Token).ConfigureAwait(false);
  150. }
  151. else
  152. {
  153. job = ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
  154. if (job.TranscodingThrottler != null)
  155. {
  156. job.TranscodingThrottler.UnpauseTranscoding();
  157. }
  158. }
  159. }
  160. }
  161. finally
  162. {
  163. ApiEntryPoint.Instance.TranscodingStartLock.Release();
  164. }
  165. Logger.Info("waiting for {0}", segmentPath);
  166. while (!File.Exists(segmentPath))
  167. {
  168. await Task.Delay(50, cancellationToken).ConfigureAwait(false);
  169. }
  170. Logger.Info("returning {0}", segmentPath);
  171. job = job ?? ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
  172. return await GetSegmentResult(playlistPath, segmentPath, requestedIndex, segmentLength, job, cancellationToken).ConfigureAwait(false);
  173. }
  174. private static readonly ConcurrentDictionary<string, double> SegmentLengths = new ConcurrentDictionary<string, double>(StringComparer.OrdinalIgnoreCase);
  175. private async Task ReadSegmentLengths(string playlist)
  176. {
  177. try
  178. {
  179. using (var fileStream = GetPlaylistFileStream(playlist))
  180. {
  181. using (var reader = new StreamReader(fileStream))
  182. {
  183. double duration = -1;
  184. while (!reader.EndOfStream)
  185. {
  186. var text = await reader.ReadLineAsync().ConfigureAwait(false);
  187. if (text.StartsWith("#EXTINF", StringComparison.OrdinalIgnoreCase))
  188. {
  189. var parts = text.Split(new[] { ':' }, 2);
  190. if (parts.Length == 2)
  191. {
  192. var time = parts[1].Trim(new[] { ',' }).Trim();
  193. double timeValue;
  194. if (double.TryParse(time, NumberStyles.Any, CultureInfo.InvariantCulture, out timeValue))
  195. {
  196. duration = timeValue;
  197. continue;
  198. }
  199. }
  200. }
  201. else if (duration != -1)
  202. {
  203. SegmentLengths.AddOrUpdate(text, duration, (k, v) => duration);
  204. Logger.Debug("Added segment length of {0} for {1}", duration, text);
  205. }
  206. duration = -1;
  207. }
  208. }
  209. }
  210. }
  211. catch (FileNotFoundException)
  212. {
  213. }
  214. }
  215. private long GetSeekPositionTicks(StreamState state, string playlist, int requestedIndex)
  216. {
  217. double startSeconds = 0;
  218. for (var i = 0; i < requestedIndex; i++)
  219. {
  220. var segmentPath = GetSegmentPath(playlist, i);
  221. double length;
  222. if (SegmentLengths.TryGetValue(Path.GetFileName(segmentPath), out length))
  223. {
  224. Logger.Debug("Found segment length of {0} for index {1}", length, i);
  225. startSeconds += length;
  226. }
  227. else
  228. {
  229. startSeconds += state.SegmentLength;
  230. }
  231. }
  232. var position = TimeSpan.FromSeconds(startSeconds).Ticks;
  233. return position;
  234. }
  235. public int? GetCurrentTranscodingIndex(string playlist, string playSessionId, string segmentExtension)
  236. {
  237. var job = string.IsNullOrWhiteSpace(playSessionId) ?
  238. ApiEntryPoint.Instance.GetTranscodingJob(playlist, TranscodingJobType) :
  239. ApiEntryPoint.Instance.GetTranscodingJobByPlaySessionId(playSessionId);
  240. if (job == null || job.HasExited)
  241. {
  242. return null;
  243. }
  244. var file = GetLastTranscodingFile(playlist, segmentExtension, FileSystem);
  245. if (file == null)
  246. {
  247. return null;
  248. }
  249. var playlistFilename = Path.GetFileNameWithoutExtension(playlist);
  250. var indexString = Path.GetFileNameWithoutExtension(file.Name).Substring(playlistFilename.Length);
  251. return int.Parse(indexString, NumberStyles.Integer, UsCulture);
  252. }
  253. private void DeleteLastFile(string playlistPath, string segmentExtension, int retryCount)
  254. {
  255. var file = GetLastTranscodingFile(playlistPath, segmentExtension, FileSystem);
  256. if (file != null)
  257. {
  258. DeleteFile(file, retryCount);
  259. }
  260. }
  261. private void DeleteFile(FileInfo file, int retryCount)
  262. {
  263. if (retryCount >= 5)
  264. {
  265. return;
  266. }
  267. try
  268. {
  269. FileSystem.DeleteFile(file.FullName);
  270. }
  271. catch (IOException ex)
  272. {
  273. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, file.FullName);
  274. Thread.Sleep(100);
  275. DeleteFile(file, retryCount + 1);
  276. }
  277. catch (Exception ex)
  278. {
  279. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, file.FullName);
  280. }
  281. }
  282. private static FileInfo GetLastTranscodingFile(string playlist, string segmentExtension, IFileSystem fileSystem)
  283. {
  284. var folder = Path.GetDirectoryName(playlist);
  285. var filePrefix = Path.GetFileNameWithoutExtension(playlist) ?? string.Empty;
  286. try
  287. {
  288. return new DirectoryInfo(folder)
  289. .EnumerateFiles("*", SearchOption.TopDirectoryOnly)
  290. .Where(i => string.Equals(i.Extension, segmentExtension, StringComparison.OrdinalIgnoreCase) && Path.GetFileNameWithoutExtension(i.Name).StartsWith(filePrefix, StringComparison.OrdinalIgnoreCase))
  291. .OrderByDescending(fileSystem.GetLastWriteTimeUtc)
  292. .FirstOrDefault();
  293. }
  294. catch (DirectoryNotFoundException)
  295. {
  296. return null;
  297. }
  298. }
  299. protected override int GetStartNumber(StreamState state)
  300. {
  301. return GetStartNumber(state.VideoRequest);
  302. }
  303. private int GetStartNumber(VideoStreamRequest request)
  304. {
  305. var segmentId = "0";
  306. var segmentRequest = request as GetDynamicHlsVideoSegment;
  307. if (segmentRequest != null)
  308. {
  309. segmentId = segmentRequest.SegmentId;
  310. }
  311. return int.Parse(segmentId, NumberStyles.Integer, UsCulture);
  312. }
  313. private string GetSegmentPath(string playlist, int index)
  314. {
  315. var folder = Path.GetDirectoryName(playlist);
  316. var filename = Path.GetFileNameWithoutExtension(playlist);
  317. return Path.Combine(folder, filename + index.ToString(UsCulture) + ".ts");
  318. }
  319. private async Task<object> GetSegmentResult(string playlistPath,
  320. string segmentPath,
  321. int segmentIndex,
  322. int segmentLength,
  323. TranscodingJob transcodingJob,
  324. CancellationToken cancellationToken)
  325. {
  326. // If all transcoding has completed, just return immediately
  327. if (transcodingJob != null && transcodingJob.HasExited)
  328. {
  329. return GetSegmentResult(segmentPath, segmentIndex, segmentLength, transcodingJob);
  330. }
  331. var segmentFilename = Path.GetFileName(segmentPath);
  332. while (!cancellationToken.IsCancellationRequested)
  333. {
  334. using (var fileStream = GetPlaylistFileStream(playlistPath))
  335. {
  336. using (var reader = new StreamReader(fileStream))
  337. {
  338. while (!reader.EndOfStream)
  339. {
  340. var text = await reader.ReadLineAsync().ConfigureAwait(false);
  341. // If it appears in the playlist, it's done
  342. if (text.IndexOf(segmentFilename, StringComparison.OrdinalIgnoreCase) != -1)
  343. {
  344. return GetSegmentResult(segmentPath, segmentIndex, segmentLength, transcodingJob);
  345. }
  346. }
  347. }
  348. }
  349. await Task.Delay(100, cancellationToken).ConfigureAwait(false);
  350. }
  351. // if a different file is encoding, it's done
  352. //var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath);
  353. //if (currentTranscodingIndex > segmentIndex)
  354. //{
  355. //return GetSegmentResult(segmentPath, segmentIndex);
  356. //}
  357. //// Wait for the file to stop being written to, then stream it
  358. //var length = new FileInfo(segmentPath).Length;
  359. //var eofCount = 0;
  360. //while (eofCount < 10)
  361. //{
  362. // var info = new FileInfo(segmentPath);
  363. // if (!info.Exists)
  364. // {
  365. // break;
  366. // }
  367. // var newLength = info.Length;
  368. // if (newLength == length)
  369. // {
  370. // eofCount++;
  371. // }
  372. // else
  373. // {
  374. // eofCount = 0;
  375. // }
  376. // length = newLength;
  377. // await Task.Delay(100, cancellationToken).ConfigureAwait(false);
  378. //}
  379. cancellationToken.ThrowIfCancellationRequested();
  380. return GetSegmentResult(segmentPath, segmentIndex, segmentLength, transcodingJob);
  381. }
  382. private object GetSegmentResult(string segmentPath, int index, int segmentLength, TranscodingJob transcodingJob)
  383. {
  384. var segmentEndingSeconds = (1 + index) * segmentLength;
  385. var segmentEndingPositionTicks = TimeSpan.FromSeconds(segmentEndingSeconds).Ticks;
  386. return ResultFactory.GetStaticFileResult(Request, new StaticFileResultOptions
  387. {
  388. Path = segmentPath,
  389. FileShare = FileShare.ReadWrite,
  390. OnComplete = () =>
  391. {
  392. if (transcodingJob != null)
  393. {
  394. transcodingJob.DownloadPositionTicks = Math.Max(transcodingJob.DownloadPositionTicks ?? segmentEndingPositionTicks, segmentEndingPositionTicks);
  395. ApiEntryPoint.Instance.OnTranscodeEndRequest(transcodingJob);
  396. }
  397. }
  398. });
  399. }
  400. private async Task<object> GetAsync(GetMasterHlsVideoStream request, string method)
  401. {
  402. var state = await GetState(request, CancellationToken.None).ConfigureAwait(false);
  403. if (string.IsNullOrEmpty(request.MediaSourceId))
  404. {
  405. throw new ArgumentException("MediaSourceId is required");
  406. }
  407. var playlistText = string.Empty;
  408. if (string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase))
  409. {
  410. var audioBitrate = state.OutputAudioBitrate ?? 0;
  411. var videoBitrate = state.OutputVideoBitrate ?? 0;
  412. playlistText = GetMasterPlaylistFileText(state, videoBitrate + audioBitrate);
  413. }
  414. return ResultFactory.GetResult(playlistText, MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary<string, string>());
  415. }
  416. private string GetMasterPlaylistFileText(StreamState state, int totalBitrate)
  417. {
  418. var builder = new StringBuilder();
  419. builder.AppendLine("#EXTM3U");
  420. var queryStringIndex = Request.RawUrl.IndexOf('?');
  421. var queryString = queryStringIndex == -1 ? string.Empty : Request.RawUrl.Substring(queryStringIndex);
  422. var isLiveStream = (state.RunTimeTicks ?? 0) == 0;
  423. // Main stream
  424. var playlistUrl = isLiveStream ? "live.m3u8" : "main.m3u8";
  425. playlistUrl += queryString;
  426. var request = (GetMasterHlsVideoStream)state.Request;
  427. var subtitleStreams = state.MediaSource
  428. .MediaStreams
  429. .Where(i => i.IsTextSubtitleStream)
  430. .ToList();
  431. var subtitleGroup = subtitleStreams.Count > 0 && request.SubtitleMethod == SubtitleDeliveryMethod.Hls ?
  432. "subs" :
  433. null;
  434. AppendPlaylist(builder, playlistUrl, totalBitrate, subtitleGroup);
  435. if (EnableAdaptiveBitrateStreaming(state, isLiveStream))
  436. {
  437. var requestedVideoBitrate = state.VideoRequest.VideoBitRate.Value;
  438. // By default, vary by just 200k
  439. var variation = GetBitrateVariation(totalBitrate);
  440. var newBitrate = totalBitrate - variation;
  441. var variantUrl = ReplaceBitrate(playlistUrl, requestedVideoBitrate, (requestedVideoBitrate - variation));
  442. AppendPlaylist(builder, variantUrl, newBitrate, subtitleGroup);
  443. variation *= 2;
  444. newBitrate = totalBitrate - variation;
  445. variantUrl = ReplaceBitrate(playlistUrl, requestedVideoBitrate, (requestedVideoBitrate - variation));
  446. AppendPlaylist(builder, variantUrl, newBitrate, subtitleGroup);
  447. }
  448. if (!string.IsNullOrWhiteSpace(subtitleGroup))
  449. {
  450. AddSubtitles(state, subtitleStreams, builder);
  451. }
  452. return builder.ToString();
  453. }
  454. private string ReplaceBitrate(string url, int oldValue, int newValue)
  455. {
  456. return url.Replace(
  457. "videobitrate=" + oldValue.ToString(UsCulture),
  458. "videobitrate=" + newValue.ToString(UsCulture),
  459. StringComparison.OrdinalIgnoreCase);
  460. }
  461. private void AddSubtitles(StreamState state, IEnumerable<MediaStream> subtitles, StringBuilder builder)
  462. {
  463. var selectedIndex = state.SubtitleStream == null ? (int?)null : state.SubtitleStream.Index;
  464. foreach (var stream in subtitles)
  465. {
  466. const string format = "#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID=\"subs\",NAME=\"{0}\",DEFAULT={1},FORCED={2},URI=\"{3}\",LANGUAGE=\"{4}\"";
  467. var name = stream.Language;
  468. var isDefault = selectedIndex.HasValue && selectedIndex.Value == stream.Index;
  469. var isForced = stream.IsForced;
  470. if (string.IsNullOrWhiteSpace(name)) name = stream.Codec ?? "Unknown";
  471. var url = string.Format("{0}/Subtitles/{1}/subtitles.m3u8?SegmentLength={2}",
  472. state.Request.MediaSourceId,
  473. stream.Index.ToString(UsCulture),
  474. 30.ToString(UsCulture));
  475. var line = string.Format(format,
  476. name,
  477. isDefault ? "YES" : "NO",
  478. isForced ? "YES" : "NO",
  479. url,
  480. stream.Language ?? "Unknown");
  481. builder.AppendLine(line);
  482. }
  483. }
  484. private bool EnableAdaptiveBitrateStreaming(StreamState state, bool isLiveStream)
  485. {
  486. // Within the local network this will likely do more harm than good.
  487. if (Request.IsLocal || NetworkManager.IsInLocalNetwork(Request.RemoteIp))
  488. {
  489. return false;
  490. }
  491. var request = state.Request as GetMasterHlsVideoStream;
  492. if (request != null && !request.EnableAdaptiveBitrateStreaming)
  493. {
  494. return false;
  495. }
  496. if (isLiveStream || string.IsNullOrWhiteSpace(state.MediaPath))
  497. {
  498. // Opening live streams is so slow it's not even worth it
  499. return false;
  500. }
  501. if (string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  502. {
  503. return false;
  504. }
  505. if (string.Equals(state.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase))
  506. {
  507. return false;
  508. }
  509. // Having problems in android
  510. return false;
  511. //return state.VideoRequest.VideoBitRate.HasValue;
  512. }
  513. private void AppendPlaylist(StringBuilder builder, string url, int bitrate, string subtitleGroup)
  514. {
  515. var header = "#EXT-X-STREAM-INF:BANDWIDTH=" + bitrate.ToString(UsCulture);
  516. if (!string.IsNullOrWhiteSpace(subtitleGroup))
  517. {
  518. header += string.Format(",SUBTITLES=\"{0}\"", subtitleGroup);
  519. }
  520. builder.AppendLine(header);
  521. builder.AppendLine(url);
  522. }
  523. private int GetBitrateVariation(int bitrate)
  524. {
  525. // By default, vary by just 50k
  526. var variation = 50000;
  527. if (bitrate >= 10000000)
  528. {
  529. variation = 2000000;
  530. }
  531. else if (bitrate >= 5000000)
  532. {
  533. variation = 1500000;
  534. }
  535. else if (bitrate >= 3000000)
  536. {
  537. variation = 1000000;
  538. }
  539. else if (bitrate >= 2000000)
  540. {
  541. variation = 500000;
  542. }
  543. else if (bitrate >= 1000000)
  544. {
  545. variation = 300000;
  546. }
  547. else if (bitrate >= 600000)
  548. {
  549. variation = 200000;
  550. }
  551. else if (bitrate >= 400000)
  552. {
  553. variation = 100000;
  554. }
  555. return variation;
  556. }
  557. private async Task<object> GetPlaylistAsync(VideoStreamRequest request, string name)
  558. {
  559. var state = await GetState(request, CancellationToken.None).ConfigureAwait(false);
  560. var builder = new StringBuilder();
  561. builder.AppendLine("#EXTM3U");
  562. builder.AppendLine("#EXT-X-VERSION:3");
  563. builder.AppendLine("#EXT-X-TARGETDURATION:" + (state.SegmentLength).ToString(UsCulture));
  564. builder.AppendLine("#EXT-X-MEDIA-SEQUENCE:0");
  565. var queryStringIndex = Request.RawUrl.IndexOf('?');
  566. var queryString = queryStringIndex == -1 ? string.Empty : Request.RawUrl.Substring(queryStringIndex);
  567. var seconds = TimeSpan.FromTicks(state.RunTimeTicks ?? 0).TotalSeconds;
  568. var index = 0;
  569. while (seconds > 0)
  570. {
  571. var length = seconds >= state.SegmentLength ? state.SegmentLength : seconds;
  572. builder.AppendLine("#EXTINF:" + length.ToString(UsCulture) + ",");
  573. builder.AppendLine(string.Format("hlsdynamic/{0}/{1}.ts{2}",
  574. name,
  575. index.ToString(UsCulture),
  576. queryString));
  577. seconds -= state.SegmentLength;
  578. index++;
  579. }
  580. builder.AppendLine("#EXT-X-ENDLIST");
  581. var playlistText = builder.ToString();
  582. return ResultFactory.GetResult(playlistText, MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary<string, string>());
  583. }
  584. protected override string GetAudioArguments(StreamState state)
  585. {
  586. var codec = state.OutputAudioCodec;
  587. if (string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase))
  588. {
  589. return "-codec:a:0 copy";
  590. }
  591. var args = "-codec:a:0 " + codec;
  592. var channels = state.OutputAudioChannels;
  593. if (channels.HasValue)
  594. {
  595. args += " -ac " + channels.Value;
  596. }
  597. var bitrate = state.OutputAudioBitrate;
  598. if (bitrate.HasValue)
  599. {
  600. args += " -ab " + bitrate.Value.ToString(UsCulture);
  601. }
  602. args += " " + GetAudioFilterParam(state, true);
  603. return args;
  604. }
  605. protected override string GetVideoArguments(StreamState state)
  606. {
  607. var codec = state.OutputVideoCodec;
  608. var args = "-codec:v:0 " + codec;
  609. if (state.EnableMpegtsM2TsMode)
  610. {
  611. args += " -mpegts_m2ts_mode 1";
  612. }
  613. // See if we can save come cpu cycles by avoiding encoding
  614. if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
  615. {
  616. return state.VideoStream != null && IsH264(state.VideoStream) ?
  617. args + " -bsf:v h264_mp4toannexb" :
  618. args;
  619. }
  620. var keyFrameArg = string.Format(" -force_key_frames expr:gte(t,n_forced*{0})",
  621. state.SegmentLength.ToString(UsCulture));
  622. var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream;
  623. args += " " + GetVideoQualityParam(state, H264Encoder, true) + keyFrameArg;
  624. //args += " -mixed-refs 0 -refs 3 -x264opts b_pyramid=0:weightb=0:weightp=0";
  625. // Add resolution params, if specified
  626. if (!hasGraphicalSubs)
  627. {
  628. args += GetOutputSizeParam(state, codec, false);
  629. }
  630. // This is for internal graphical subs
  631. if (hasGraphicalSubs)
  632. {
  633. args += GetGraphicalSubtitleParam(state, codec);
  634. }
  635. return args;
  636. }
  637. protected override string GetCommandLineArguments(string outputPath, StreamState state, bool isEncoding)
  638. {
  639. var threads = GetNumberOfThreads(state, false);
  640. var inputModifier = GetInputModifier(state, false);
  641. // If isEncoding is true we're actually starting ffmpeg
  642. var startNumberParam = isEncoding ? GetStartNumber(state).ToString(UsCulture) : "0";
  643. var toTimeParam = string.Empty;
  644. if (state.RunTimeTicks.HasValue)
  645. {
  646. var startTime = state.Request.StartTimeTicks ?? 0;
  647. var durationSeconds = ApiEntryPoint.Instance.GetEncodingOptions().ThrottleThresholdInSeconds;
  648. var endTime = startTime + TimeSpan.FromSeconds(durationSeconds).Ticks;
  649. endTime = Math.Min(endTime, state.RunTimeTicks.Value);
  650. if (endTime < state.RunTimeTicks.Value)
  651. {
  652. //toTimeParam = " -to " + MediaEncoder.GetTimeParameter(endTime);
  653. toTimeParam = " -t " + MediaEncoder.GetTimeParameter(TimeSpan.FromSeconds(durationSeconds).Ticks);
  654. }
  655. }
  656. var slowSeekParam = GetSlowSeekCommandLineParameter(state.Request);
  657. if (!string.IsNullOrWhiteSpace(slowSeekParam))
  658. {
  659. slowSeekParam = " " + slowSeekParam;
  660. }
  661. //state.EnableGenericHlsSegmenter = true;
  662. if (state.EnableGenericHlsSegmenter)
  663. {
  664. var outputTsArg = Path.Combine(Path.GetDirectoryName(outputPath), Path.GetFileNameWithoutExtension(outputPath)) + "%d.ts";
  665. return string.Format("{0} {11} {1}{10} -map_metadata -1 -threads {2} {3} {4} -flags -global_header -sc_threshold 0 {5} -f segment -segment_time {6} -segment_format mpegts -segment_list_type m3u8 -segment_start_number {7} -segment_list \"{8}\" -y \"{9}\"",
  666. inputModifier,
  667. GetInputArgument(state),
  668. threads,
  669. GetMapArgs(state),
  670. GetVideoArguments(state),
  671. GetAudioArguments(state),
  672. state.SegmentLength.ToString(UsCulture),
  673. startNumberParam,
  674. outputPath,
  675. outputTsArg,
  676. slowSeekParam,
  677. toTimeParam
  678. ).Trim();
  679. }
  680. return string.Format("{0}{11} {1}{10} -map_metadata -1 -threads {2} {3} {4} -output_ts_offset " + MediaEncoder.GetTimeParameter(state.Request.StartTimeTicks ?? 0) + " -flags -global_header -sc_threshold 0 {5} -hls_time {6} -start_number {7} -hls_list_size {8} -y \"{9}\"",
  681. inputModifier,
  682. GetInputArgument(state),
  683. threads,
  684. GetMapArgs(state),
  685. GetVideoArguments(state),
  686. GetAudioArguments(state),
  687. state.SegmentLength.ToString(UsCulture),
  688. startNumberParam,
  689. state.HlsListSize.ToString(UsCulture),
  690. outputPath,
  691. slowSeekParam,
  692. toTimeParam
  693. ).Trim();
  694. }
  695. protected override bool EnableThrottling
  696. {
  697. get
  698. {
  699. return false;
  700. }
  701. }
  702. protected override bool EnableStreamCopy
  703. {
  704. get
  705. {
  706. return false;
  707. }
  708. }
  709. protected override bool EnableSlowSeek
  710. {
  711. get
  712. {
  713. return true;
  714. }
  715. }
  716. /// <summary>
  717. /// Gets the segment file extension.
  718. /// </summary>
  719. /// <param name="state">The state.</param>
  720. /// <returns>System.String.</returns>
  721. protected override string GetSegmentFileExtension(StreamState state)
  722. {
  723. return ".ts";
  724. }
  725. }
  726. }