DynamicHlsService.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882
  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. using (var fileStream = GetPlaylistFileStream(playlistPath))
  333. {
  334. using (var reader = new StreamReader(fileStream))
  335. {
  336. while (!reader.EndOfStream)
  337. {
  338. var text = await reader.ReadLineAsync().ConfigureAwait(false);
  339. // If it appears in the playlist, it's done
  340. if (text.IndexOf(segmentFilename, StringComparison.OrdinalIgnoreCase) != -1)
  341. {
  342. return GetSegmentResult(segmentPath, segmentIndex, segmentLength, transcodingJob);
  343. }
  344. }
  345. }
  346. }
  347. // if a different file is encoding, it's done
  348. //var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath);
  349. //if (currentTranscodingIndex > segmentIndex)
  350. //{
  351. //return GetSegmentResult(segmentPath, segmentIndex);
  352. //}
  353. // Wait for the file to stop being written to, then stream it
  354. var length = new FileInfo(segmentPath).Length;
  355. var eofCount = 0;
  356. while (eofCount < 10)
  357. {
  358. var info = new FileInfo(segmentPath);
  359. if (!info.Exists)
  360. {
  361. break;
  362. }
  363. var newLength = info.Length;
  364. if (newLength == length)
  365. {
  366. eofCount++;
  367. }
  368. else
  369. {
  370. eofCount = 0;
  371. }
  372. length = newLength;
  373. await Task.Delay(100, cancellationToken).ConfigureAwait(false);
  374. }
  375. return GetSegmentResult(segmentPath, segmentIndex, segmentLength, transcodingJob);
  376. }
  377. private object GetSegmentResult(string segmentPath, int index, int segmentLength, TranscodingJob transcodingJob)
  378. {
  379. var segmentEndingSeconds = (1 + index) * segmentLength;
  380. var segmentEndingPositionTicks = TimeSpan.FromSeconds(segmentEndingSeconds).Ticks;
  381. return ResultFactory.GetStaticFileResult(Request, new StaticFileResultOptions
  382. {
  383. Path = segmentPath,
  384. FileShare = FileShare.ReadWrite,
  385. OnComplete = () =>
  386. {
  387. if (transcodingJob != null)
  388. {
  389. transcodingJob.DownloadPositionTicks = Math.Max(transcodingJob.DownloadPositionTicks ?? segmentEndingPositionTicks, segmentEndingPositionTicks);
  390. ApiEntryPoint.Instance.OnTranscodeEndRequest(transcodingJob);
  391. }
  392. }
  393. });
  394. }
  395. private async Task<object> GetAsync(GetMasterHlsVideoStream request, string method)
  396. {
  397. var state = await GetState(request, CancellationToken.None).ConfigureAwait(false);
  398. if (string.IsNullOrEmpty(request.MediaSourceId))
  399. {
  400. throw new ArgumentException("MediaSourceId is required");
  401. }
  402. var playlistText = string.Empty;
  403. if (string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase))
  404. {
  405. var audioBitrate = state.OutputAudioBitrate ?? 0;
  406. var videoBitrate = state.OutputVideoBitrate ?? 0;
  407. playlistText = GetMasterPlaylistFileText(state, videoBitrate + audioBitrate);
  408. }
  409. return ResultFactory.GetResult(playlistText, MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary<string, string>());
  410. }
  411. private string GetMasterPlaylistFileText(StreamState state, int totalBitrate)
  412. {
  413. var builder = new StringBuilder();
  414. builder.AppendLine("#EXTM3U");
  415. var queryStringIndex = Request.RawUrl.IndexOf('?');
  416. var queryString = queryStringIndex == -1 ? string.Empty : Request.RawUrl.Substring(queryStringIndex);
  417. var isLiveStream = (state.RunTimeTicks ?? 0) == 0;
  418. // Main stream
  419. var playlistUrl = isLiveStream ? "live.m3u8" : "main.m3u8";
  420. playlistUrl += queryString;
  421. var request = (GetMasterHlsVideoStream)state.Request;
  422. var subtitleStreams = state.MediaSource
  423. .MediaStreams
  424. .Where(i => i.IsTextSubtitleStream)
  425. .ToList();
  426. var subtitleGroup = subtitleStreams.Count > 0 && request.SubtitleMethod == SubtitleDeliveryMethod.Hls ?
  427. "subs" :
  428. null;
  429. AppendPlaylist(builder, playlistUrl, totalBitrate, subtitleGroup);
  430. if (EnableAdaptiveBitrateStreaming(state, isLiveStream))
  431. {
  432. var requestedVideoBitrate = state.VideoRequest.VideoBitRate.Value;
  433. // By default, vary by just 200k
  434. var variation = GetBitrateVariation(totalBitrate);
  435. var newBitrate = totalBitrate - variation;
  436. var variantUrl = ReplaceBitrate(playlistUrl, requestedVideoBitrate, (requestedVideoBitrate - variation));
  437. AppendPlaylist(builder, variantUrl, newBitrate, subtitleGroup);
  438. variation *= 2;
  439. newBitrate = totalBitrate - variation;
  440. variantUrl = ReplaceBitrate(playlistUrl, requestedVideoBitrate, (requestedVideoBitrate - variation));
  441. AppendPlaylist(builder, variantUrl, newBitrate, subtitleGroup);
  442. }
  443. if (!string.IsNullOrWhiteSpace(subtitleGroup))
  444. {
  445. AddSubtitles(state, subtitleStreams, builder);
  446. }
  447. return builder.ToString();
  448. }
  449. private string ReplaceBitrate(string url, int oldValue, int newValue)
  450. {
  451. return url.Replace(
  452. "videobitrate=" + oldValue.ToString(UsCulture),
  453. "videobitrate=" + newValue.ToString(UsCulture),
  454. StringComparison.OrdinalIgnoreCase);
  455. }
  456. private void AddSubtitles(StreamState state, IEnumerable<MediaStream> subtitles, StringBuilder builder)
  457. {
  458. var selectedIndex = state.SubtitleStream == null ? (int?)null : state.SubtitleStream.Index;
  459. foreach (var stream in subtitles)
  460. {
  461. const string format = "#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID=\"subs\",NAME=\"{0}\",DEFAULT={1},FORCED={2},URI=\"{3}\",LANGUAGE=\"{4}\"";
  462. var name = stream.Language;
  463. var isDefault = selectedIndex.HasValue && selectedIndex.Value == stream.Index;
  464. var isForced = stream.IsForced;
  465. if (string.IsNullOrWhiteSpace(name)) name = stream.Codec ?? "Unknown";
  466. var url = string.Format("{0}/Subtitles/{1}/subtitles.m3u8?SegmentLength={2}",
  467. state.Request.MediaSourceId,
  468. stream.Index.ToString(UsCulture),
  469. 30.ToString(UsCulture));
  470. var line = string.Format(format,
  471. name,
  472. isDefault ? "YES" : "NO",
  473. isForced ? "YES" : "NO",
  474. url,
  475. stream.Language ?? "Unknown");
  476. builder.AppendLine(line);
  477. }
  478. }
  479. private bool EnableAdaptiveBitrateStreaming(StreamState state, bool isLiveStream)
  480. {
  481. // Within the local network this will likely do more harm than good.
  482. if (Request.IsLocal || NetworkManager.IsInLocalNetwork(Request.RemoteIp))
  483. {
  484. return false;
  485. }
  486. var request = state.Request as GetMasterHlsVideoStream;
  487. if (request != null && !request.EnableAdaptiveBitrateStreaming)
  488. {
  489. return false;
  490. }
  491. if (isLiveStream || string.IsNullOrWhiteSpace(state.MediaPath))
  492. {
  493. // Opening live streams is so slow it's not even worth it
  494. return false;
  495. }
  496. if (string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  497. {
  498. return false;
  499. }
  500. if (string.Equals(state.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase))
  501. {
  502. return false;
  503. }
  504. // Having problems in android
  505. return false;
  506. //return state.VideoRequest.VideoBitRate.HasValue;
  507. }
  508. private void AppendPlaylist(StringBuilder builder, string url, int bitrate, string subtitleGroup)
  509. {
  510. var header = "#EXT-X-STREAM-INF:BANDWIDTH=" + bitrate.ToString(UsCulture);
  511. if (!string.IsNullOrWhiteSpace(subtitleGroup))
  512. {
  513. header += string.Format(",SUBTITLES=\"{0}\"", subtitleGroup);
  514. }
  515. builder.AppendLine(header);
  516. builder.AppendLine(url);
  517. }
  518. private int GetBitrateVariation(int bitrate)
  519. {
  520. // By default, vary by just 50k
  521. var variation = 50000;
  522. if (bitrate >= 10000000)
  523. {
  524. variation = 2000000;
  525. }
  526. else if (bitrate >= 5000000)
  527. {
  528. variation = 1500000;
  529. }
  530. else if (bitrate >= 3000000)
  531. {
  532. variation = 1000000;
  533. }
  534. else if (bitrate >= 2000000)
  535. {
  536. variation = 500000;
  537. }
  538. else if (bitrate >= 1000000)
  539. {
  540. variation = 300000;
  541. }
  542. else if (bitrate >= 600000)
  543. {
  544. variation = 200000;
  545. }
  546. else if (bitrate >= 400000)
  547. {
  548. variation = 100000;
  549. }
  550. return variation;
  551. }
  552. private async Task<object> GetPlaylistAsync(VideoStreamRequest request, string name)
  553. {
  554. var state = await GetState(request, CancellationToken.None).ConfigureAwait(false);
  555. var builder = new StringBuilder();
  556. builder.AppendLine("#EXTM3U");
  557. builder.AppendLine("#EXT-X-VERSION:3");
  558. builder.AppendLine("#EXT-X-TARGETDURATION:" + state.SegmentLength.ToString(UsCulture));
  559. builder.AppendLine("#EXT-X-MEDIA-SEQUENCE:0");
  560. var queryStringIndex = Request.RawUrl.IndexOf('?');
  561. var queryString = queryStringIndex == -1 ? string.Empty : Request.RawUrl.Substring(queryStringIndex);
  562. var seconds = TimeSpan.FromTicks(state.RunTimeTicks ?? 0).TotalSeconds;
  563. var index = 0;
  564. while (seconds > 0)
  565. {
  566. var length = seconds >= state.SegmentLength ? state.SegmentLength : seconds;
  567. builder.AppendLine("#EXTINF:" + length.ToString(UsCulture) + ",");
  568. builder.AppendLine(string.Format("hlsdynamic/{0}/{1}.ts{2}",
  569. name,
  570. index.ToString(UsCulture),
  571. queryString));
  572. seconds -= state.SegmentLength;
  573. index++;
  574. }
  575. builder.AppendLine("#EXT-X-ENDLIST");
  576. var playlistText = builder.ToString();
  577. return ResultFactory.GetResult(playlistText, MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary<string, string>());
  578. }
  579. protected override string GetAudioArguments(StreamState state)
  580. {
  581. var codec = state.OutputAudioCodec;
  582. if (string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase))
  583. {
  584. return "-codec:a:0 copy";
  585. }
  586. var args = "-codec:a:0 " + codec;
  587. var channels = state.OutputAudioChannels;
  588. if (channels.HasValue)
  589. {
  590. args += " -ac " + channels.Value;
  591. }
  592. var bitrate = state.OutputAudioBitrate;
  593. if (bitrate.HasValue)
  594. {
  595. args += " -ab " + bitrate.Value.ToString(UsCulture);
  596. }
  597. args += " " + GetAudioFilterParam(state, true);
  598. return args;
  599. }
  600. protected override string GetVideoArguments(StreamState state)
  601. {
  602. var codec = state.OutputVideoCodec;
  603. var args = "-codec:v:0 " + codec;
  604. if (state.EnableMpegtsM2TsMode)
  605. {
  606. args += " -mpegts_m2ts_mode 1";
  607. }
  608. // See if we can save come cpu cycles by avoiding encoding
  609. if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
  610. {
  611. return state.VideoStream != null && IsH264(state.VideoStream) ?
  612. args + " -bsf:v h264_mp4toannexb" :
  613. args;
  614. }
  615. var keyFrameArg = string.Format(" -force_key_frames expr:gte(t,n_forced*{0})",
  616. 1.ToString(UsCulture));
  617. var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream;
  618. args += " " + GetVideoQualityParam(state, H264Encoder, true) + keyFrameArg;
  619. // Add resolution params, if specified
  620. if (!hasGraphicalSubs)
  621. {
  622. args += GetOutputSizeParam(state, codec, false);
  623. }
  624. // This is for internal graphical subs
  625. if (hasGraphicalSubs)
  626. {
  627. args += GetGraphicalSubtitleParam(state, codec);
  628. }
  629. return args;
  630. }
  631. protected override string GetCommandLineArguments(string outputPath, StreamState state, bool isEncoding)
  632. {
  633. var threads = GetNumberOfThreads(state, false);
  634. var inputModifier = GetInputModifier(state);
  635. // If isEncoding is true we're actually starting ffmpeg
  636. var startNumberParam = isEncoding ? GetStartNumber(state).ToString(UsCulture) : "0";
  637. var toTimeParam = string.Empty;
  638. if (state.RunTimeTicks.HasValue)
  639. {
  640. var startTime = state.Request.StartTimeTicks ?? 0;
  641. var durationSeconds = ApiEntryPoint.Instance.GetEncodingOptions().ThrottleThresholdInSeconds;
  642. var endTime = startTime + TimeSpan.FromSeconds(durationSeconds).Ticks;
  643. endTime = Math.Min(endTime, state.RunTimeTicks.Value);
  644. if (endTime < state.RunTimeTicks.Value)
  645. {
  646. toTimeParam = " -to " + MediaEncoder.GetTimeParameter(endTime);
  647. }
  648. }
  649. var slowSeekParam = GetSlowSeekCommandLineParameter(state.Request);
  650. if (!string.IsNullOrWhiteSpace(slowSeekParam))
  651. {
  652. slowSeekParam = " " + slowSeekParam;
  653. }
  654. if (state.EnableGenericHlsSegmenter)
  655. {
  656. var outputTsArg = Path.Combine(Path.GetDirectoryName(outputPath), Path.GetFileNameWithoutExtension(outputPath)) + "%d.ts";
  657. return string.Format("{0} {1}{10}{11} -map_metadata -1 -threads {2} {3} {4} -flags -global_header -sc_threshold 0 {5} -f segment -segment_time {6} -segment_start_number {7} -segment_list \"{8}\" -y \"{9}\"",
  658. inputModifier,
  659. GetInputArgument(state),
  660. threads,
  661. GetMapArgs(state),
  662. GetVideoArguments(state),
  663. GetAudioArguments(state),
  664. state.SegmentLength.ToString(UsCulture),
  665. startNumberParam,
  666. outputPath,
  667. outputTsArg,
  668. slowSeekParam,
  669. toTimeParam
  670. ).Trim();
  671. }
  672. return string.Format("{0} {1}{10}{11} -map_metadata -1 -threads {2} {3} {4} -flags -global_header -copyts -sc_threshold 0 {5} -hls_time {6} -start_number {7} -hls_list_size {8} -y \"{9}\"",
  673. inputModifier,
  674. GetInputArgument(state),
  675. threads,
  676. GetMapArgs(state),
  677. GetVideoArguments(state),
  678. GetAudioArguments(state),
  679. state.SegmentLength.ToString(UsCulture),
  680. startNumberParam,
  681. state.HlsListSize.ToString(UsCulture),
  682. outputPath,
  683. slowSeekParam,
  684. toTimeParam
  685. ).Trim();
  686. }
  687. protected override bool EnableThrottling
  688. {
  689. get
  690. {
  691. return false;
  692. }
  693. }
  694. protected override bool EnableStreamCopy
  695. {
  696. get
  697. {
  698. return false;
  699. }
  700. }
  701. protected override bool EnableSlowSeek
  702. {
  703. get
  704. {
  705. return true;
  706. }
  707. }
  708. /// <summary>
  709. /// Gets the segment file extension.
  710. /// </summary>
  711. /// <param name="state">The state.</param>
  712. /// <returns>System.String.</returns>
  713. protected override string GetSegmentFileExtension(StreamState state)
  714. {
  715. return ".ts";
  716. }
  717. }
  718. }