2
0

DynamicHlsService.cs 25 KB

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