DynamicHlsService.cs 26 KB

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