DynamicHlsService.cs 28 KB

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