DynamicHlsService.cs 28 KB

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