DynamicHlsService.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Controller.Channels;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Dlna;
  6. using MediaBrowser.Controller.Library;
  7. using MediaBrowser.Controller.LiveTv;
  8. using MediaBrowser.Controller.MediaEncoding;
  9. using MediaBrowser.Controller.Net;
  10. using MediaBrowser.Model.Dlna;
  11. using MediaBrowser.Model.Entities;
  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. namespace MediaBrowser.Api.Playback.Hls
  23. {
  24. /// <summary>
  25. /// Options is needed for chromecast. Threw Head in there since it's related
  26. /// </summary>
  27. [Route("/Videos/{Id}/master.m3u8", "GET", Summary = "Gets a video stream using HTTP live streaming.")]
  28. [Route("/Videos/{Id}/master.m3u8", "HEAD", Summary = "Gets a video stream using HTTP live streaming.")]
  29. public class GetMasterHlsVideoStream : VideoStreamRequest
  30. {
  31. public bool EnableAdaptiveBitrateStreaming { get; set; }
  32. public GetMasterHlsVideoStream()
  33. {
  34. EnableAdaptiveBitrateStreaming = true;
  35. }
  36. }
  37. [Route("/Videos/{Id}/main.m3u8", "GET", Summary = "Gets a video stream using HTTP live streaming.")]
  38. public class GetMainHlsVideoStream : VideoStreamRequest
  39. {
  40. }
  41. /// <summary>
  42. /// Class GetHlsVideoSegment
  43. /// </summary>
  44. [Route("/Videos/{Id}/hlsdynamic/{PlaylistId}/{SegmentId}.ts", "GET")]
  45. [Api(Description = "Gets an Http live streaming segment file. Internal use only.")]
  46. public class GetDynamicHlsVideoSegment : VideoStreamRequest
  47. {
  48. public string PlaylistId { get; set; }
  49. /// <summary>
  50. /// Gets or sets the segment id.
  51. /// </summary>
  52. /// <value>The segment id.</value>
  53. public string SegmentId { get; set; }
  54. }
  55. public class DynamicHlsService : BaseHlsService
  56. {
  57. public DynamicHlsService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, ILiveTvManager liveTvManager, IDlnaManager dlnaManager, IChannelManager channelManager, ISubtitleEncoder subtitleEncoder)
  58. : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, liveTvManager, dlnaManager, channelManager, subtitleEncoder)
  59. {
  60. }
  61. public object Get(GetMasterHlsVideoStream request)
  62. {
  63. var result = GetAsync(request, "GET").Result;
  64. return result;
  65. }
  66. public object Head(GetMasterHlsVideoStream request)
  67. {
  68. var result = GetAsync(request, "HEAD").Result;
  69. return result;
  70. }
  71. public object Get(GetMainHlsVideoStream request)
  72. {
  73. var result = GetPlaylistAsync(request, "main").Result;
  74. return result;
  75. }
  76. public object Get(GetDynamicHlsVideoSegment request)
  77. {
  78. return GetDynamicSegment(request, request.SegmentId).Result;
  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 index = 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, index);
  92. var segmentLength = state.SegmentLength;
  93. TranscodingJob job = null;
  94. if (File.Exists(segmentPath))
  95. {
  96. job = ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType.Hls);
  97. return await GetSegmentResult(playlistPath, segmentPath, index, 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.Hls);
  105. return await GetSegmentResult(playlistPath, segmentPath, index, segmentLength, job, cancellationToken).ConfigureAwait(false);
  106. }
  107. else
  108. {
  109. var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath);
  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. await ApiEntryPoint.Instance.KillTranscodingJobs(j => j.Type == TranscodingJobType.Hls && string.Equals(j.DeviceId, request.DeviceId, StringComparison.OrdinalIgnoreCase), p => !string.Equals(p, playlistPath, StringComparison.OrdinalIgnoreCase), false).ConfigureAwait(false);
  116. if (currentTranscodingIndex.HasValue)
  117. {
  118. DeleteLastFile(playlistPath, 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, 1, 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.Hls);
  144. return await GetSegmentResult(playlistPath, segmentPath, index, segmentLength, job, cancellationToken).ConfigureAwait(false);
  145. }
  146. public int? GetCurrentTranscodingIndex(string playlist)
  147. {
  148. var file = GetLastTranscodingFile(playlist, 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 path, int retryCount)
  158. {
  159. if (retryCount >= 5)
  160. {
  161. return;
  162. }
  163. var file = GetLastTranscodingFile(path, FileSystem);
  164. if (file != null)
  165. {
  166. try
  167. {
  168. File.Delete(file.FullName);
  169. }
  170. catch (IOException ex)
  171. {
  172. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, file.FullName);
  173. Thread.Sleep(100);
  174. DeleteLastFile(path, retryCount + 1);
  175. }
  176. catch (Exception ex)
  177. {
  178. Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, file.FullName);
  179. }
  180. }
  181. }
  182. private static FileInfo GetLastTranscodingFile(string playlist, IFileSystem fileSystem)
  183. {
  184. var folder = Path.GetDirectoryName(playlist);
  185. try
  186. {
  187. return new DirectoryInfo(folder)
  188. .EnumerateFiles("*", SearchOption.TopDirectoryOnly)
  189. .Where(i => string.Equals(i.Extension, ".ts", StringComparison.OrdinalIgnoreCase))
  190. .OrderByDescending(fileSystem.GetLastWriteTimeUtc)
  191. .FirstOrDefault();
  192. }
  193. catch (DirectoryNotFoundException)
  194. {
  195. return null;
  196. }
  197. }
  198. protected override int GetStartNumber(StreamState state)
  199. {
  200. return GetStartNumber(state.VideoRequest);
  201. }
  202. private int GetStartNumber(VideoStreamRequest request)
  203. {
  204. var segmentId = "0";
  205. var segmentRequest = request as GetDynamicHlsVideoSegment;
  206. if (segmentRequest != null)
  207. {
  208. segmentId = segmentRequest.SegmentId;
  209. }
  210. return int.Parse(segmentId, NumberStyles.Integer, UsCulture);
  211. }
  212. private string GetSegmentPath(string playlist, int index)
  213. {
  214. var folder = Path.GetDirectoryName(playlist);
  215. var filename = Path.GetFileNameWithoutExtension(playlist);
  216. return Path.Combine(folder, filename + index.ToString(UsCulture) + ".ts");
  217. }
  218. private async Task<object> GetSegmentResult(string playlistPath,
  219. string segmentPath,
  220. int segmentIndex,
  221. int segmentLength,
  222. TranscodingJob transcodingJob,
  223. CancellationToken cancellationToken)
  224. {
  225. // If all transcoding has completed, just return immediately
  226. if (!IsTranscoding(playlistPath))
  227. {
  228. return GetSegmentResult(segmentPath, segmentIndex, segmentLength, transcodingJob);
  229. }
  230. var segmentFilename = Path.GetFileName(segmentPath);
  231. using (var fileStream = FileSystem.GetFileStream(playlistPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  232. {
  233. using (var reader = new StreamReader(fileStream))
  234. {
  235. var text = await reader.ReadToEndAsync().ConfigureAwait(false);
  236. // If it appears in the playlist, it's done
  237. if (text.IndexOf(segmentFilename, StringComparison.OrdinalIgnoreCase) != -1)
  238. {
  239. return GetSegmentResult(segmentPath, segmentIndex, segmentLength, transcodingJob);
  240. }
  241. }
  242. }
  243. // if a different file is encoding, it's done
  244. //var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath);
  245. //if (currentTranscodingIndex > segmentIndex)
  246. //{
  247. //return GetSegmentResult(segmentPath, segmentIndex);
  248. //}
  249. // Wait for the file to stop being written to, then stream it
  250. var length = new FileInfo(segmentPath).Length;
  251. var eofCount = 0;
  252. while (eofCount < 10)
  253. {
  254. var info = new FileInfo(segmentPath);
  255. if (!info.Exists)
  256. {
  257. break;
  258. }
  259. var newLength = info.Length;
  260. if (newLength == length)
  261. {
  262. eofCount++;
  263. }
  264. else
  265. {
  266. eofCount = 0;
  267. }
  268. length = newLength;
  269. await Task.Delay(100, cancellationToken).ConfigureAwait(false);
  270. }
  271. return GetSegmentResult(segmentPath, segmentIndex, segmentLength, transcodingJob);
  272. }
  273. private object GetSegmentResult(string segmentPath, int index, int segmentLength, TranscodingJob transcodingJob)
  274. {
  275. var segmentEndingSeconds = (1 + index) * segmentLength;
  276. var segmentEndingPositionTicks = TimeSpan.FromSeconds(segmentEndingSeconds).Ticks;
  277. return ResultFactory.GetStaticFileResult(Request, new StaticFileResultOptions
  278. {
  279. Path = segmentPath,
  280. FileShare = FileShare.ReadWrite,
  281. OnComplete = () =>
  282. {
  283. if (transcodingJob != null)
  284. {
  285. transcodingJob.DownloadPositionTicks = Math.Max(transcodingJob.DownloadPositionTicks ?? segmentEndingPositionTicks, segmentEndingPositionTicks);
  286. }
  287. }
  288. });
  289. }
  290. private bool IsTranscoding(string playlistPath)
  291. {
  292. var job = ApiEntryPoint.Instance.GetTranscodingJob(playlistPath, TranscodingJobType);
  293. return job != null && !job.HasExited;
  294. }
  295. private async Task<object> GetAsync(GetMasterHlsVideoStream request, string method)
  296. {
  297. var state = await GetState(request, CancellationToken.None).ConfigureAwait(false);
  298. if (string.Equals(request.AudioCodec, "copy", StringComparison.OrdinalIgnoreCase))
  299. {
  300. throw new ArgumentException("Audio codec copy is not allowed here.");
  301. }
  302. if (string.Equals(request.VideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
  303. {
  304. throw new ArgumentException("Video codec copy is not allowed here.");
  305. }
  306. if (string.IsNullOrEmpty(request.MediaSourceId))
  307. {
  308. throw new ArgumentException("MediaSourceId is required");
  309. }
  310. var playlistText = string.Empty;
  311. if (string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase))
  312. {
  313. var audioBitrate = state.OutputAudioBitrate ?? 0;
  314. var videoBitrate = state.OutputVideoBitrate ?? 0;
  315. playlistText = GetMasterPlaylistFileText(state, videoBitrate + audioBitrate);
  316. }
  317. return ResultFactory.GetResult(playlistText, Common.Net.MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary<string, string>());
  318. }
  319. private string GetMasterPlaylistFileText(StreamState state, int totalBitrate)
  320. {
  321. var builder = new StringBuilder();
  322. builder.AppendLine("#EXTM3U");
  323. var queryStringIndex = Request.RawUrl.IndexOf('?');
  324. var queryString = queryStringIndex == -1 ? string.Empty : Request.RawUrl.Substring(queryStringIndex);
  325. // Main stream
  326. var playlistUrl = (state.RunTimeTicks ?? 0) > 0 ? "main.m3u8" : "live.m3u8";
  327. playlistUrl += queryString;
  328. var request = (GetMasterHlsVideoStream)state.Request;
  329. var subtitleStreams = state.AllMediaStreams
  330. .Where(i => i.IsTextSubtitleStream)
  331. .ToList();
  332. var subtitleGroup = subtitleStreams.Count > 0 && request.SubtitleMethod == SubtitleDeliveryMethod.Hls ?
  333. "subs" :
  334. null;
  335. AppendPlaylist(builder, playlistUrl, totalBitrate, subtitleGroup);
  336. if (EnableAdaptiveBitrateStreaming(state))
  337. {
  338. var requestedVideoBitrate = state.VideoRequest.VideoBitRate.Value;
  339. // By default, vary by just 200k
  340. var variation = GetBitrateVariation(totalBitrate);
  341. var newBitrate = totalBitrate - variation;
  342. var variantUrl = ReplaceBitrate(playlistUrl, requestedVideoBitrate, (requestedVideoBitrate - variation));
  343. AppendPlaylist(builder, variantUrl, newBitrate, subtitleGroup);
  344. variation *= 2;
  345. newBitrate = totalBitrate - variation;
  346. variantUrl = ReplaceBitrate(playlistUrl, requestedVideoBitrate, (requestedVideoBitrate - variation));
  347. AppendPlaylist(builder, variantUrl, newBitrate, subtitleGroup);
  348. }
  349. if (!string.IsNullOrWhiteSpace(subtitleGroup))
  350. {
  351. AddSubtitles(state, subtitleStreams, builder);
  352. }
  353. return builder.ToString();
  354. }
  355. private string ReplaceBitrate(string url, int oldValue, int newValue)
  356. {
  357. return url.Replace(
  358. "videobitrate=" + oldValue.ToString(UsCulture),
  359. "videobitrate=" + newValue.ToString(UsCulture),
  360. StringComparison.OrdinalIgnoreCase);
  361. }
  362. private void AddSubtitles(StreamState state, IEnumerable<MediaStream> subtitles, StringBuilder builder)
  363. {
  364. var selectedIndex = state.SubtitleStream == null ? (int?)null : state.SubtitleStream.Index;
  365. foreach (var stream in subtitles)
  366. {
  367. const string format = "#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID=\"subs\",NAME=\"{0}\",DEFAULT={1},FORCED={2},URI=\"{3}\",LANGUAGE=\"{4}\"";
  368. var name = stream.Language;
  369. var isDefault = selectedIndex.HasValue && selectedIndex.Value == stream.Index;
  370. var isForced = stream.IsForced;
  371. if (string.IsNullOrWhiteSpace(name)) name = stream.Codec ?? "Unknown";
  372. var url = string.Format("{0}/Subtitles/{1}/subtitles.m3u8?SegmentLength={2}",
  373. state.Request.MediaSourceId,
  374. stream.Index.ToString(UsCulture),
  375. 30.ToString(UsCulture));
  376. var line = string.Format(format,
  377. name,
  378. isDefault ? "YES" : "NO",
  379. isForced ? "YES" : "NO",
  380. url,
  381. stream.Language ?? "Unknown");
  382. builder.AppendLine(line);
  383. }
  384. }
  385. private bool EnableAdaptiveBitrateStreaming(StreamState state)
  386. {
  387. var request = state.Request as GetMasterHlsVideoStream;
  388. if (request != null && !request.EnableAdaptiveBitrateStreaming)
  389. {
  390. return false;
  391. }
  392. if (string.IsNullOrWhiteSpace(state.MediaPath))
  393. {
  394. // Opening live streams is so slow it's not even worth it
  395. return false;
  396. }
  397. return state.VideoRequest.VideoBitRate.HasValue;
  398. }
  399. private void AppendPlaylist(StringBuilder builder, string url, int bitrate, string subtitleGroup)
  400. {
  401. var header = "#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=" + bitrate.ToString(UsCulture);
  402. if (!string.IsNullOrWhiteSpace(subtitleGroup))
  403. {
  404. header += string.Format(",SUBTITLES=\"{0}\"", subtitleGroup);
  405. }
  406. builder.AppendLine(header);
  407. builder.AppendLine(url);
  408. }
  409. private int GetBitrateVariation(int bitrate)
  410. {
  411. // By default, vary by just 50k
  412. var variation = 50000;
  413. if (bitrate >= 10000000)
  414. {
  415. variation = 2000000;
  416. }
  417. else if (bitrate >= 5000000)
  418. {
  419. variation = 1500000;
  420. }
  421. else if (bitrate >= 3000000)
  422. {
  423. variation = 1000000;
  424. }
  425. else if (bitrate >= 2000000)
  426. {
  427. variation = 500000;
  428. }
  429. else if (bitrate >= 1000000)
  430. {
  431. variation = 300000;
  432. }
  433. else if (bitrate >= 600000)
  434. {
  435. variation = 200000;
  436. }
  437. else if (bitrate >= 400000)
  438. {
  439. variation = 100000;
  440. }
  441. return variation;
  442. }
  443. private async Task<object> GetPlaylistAsync(VideoStreamRequest request, string name)
  444. {
  445. var state = await GetState(request, CancellationToken.None).ConfigureAwait(false);
  446. var builder = new StringBuilder();
  447. builder.AppendLine("#EXTM3U");
  448. builder.AppendLine("#EXT-X-VERSION:3");
  449. builder.AppendLine("#EXT-X-TARGETDURATION:" + state.SegmentLength.ToString(UsCulture));
  450. builder.AppendLine("#EXT-X-MEDIA-SEQUENCE:0");
  451. builder.AppendLine("#EXT-X-ALLOW-CACHE:NO");
  452. var queryStringIndex = Request.RawUrl.IndexOf('?');
  453. var queryString = queryStringIndex == -1 ? string.Empty : Request.RawUrl.Substring(queryStringIndex);
  454. var seconds = TimeSpan.FromTicks(state.RunTimeTicks ?? 0).TotalSeconds;
  455. var index = 0;
  456. while (seconds > 0)
  457. {
  458. var length = seconds >= state.SegmentLength ? state.SegmentLength : seconds;
  459. builder.AppendLine("#EXTINF:" + length.ToString(UsCulture) + ",");
  460. builder.AppendLine(string.Format("hlsdynamic/{0}/{1}.ts{2}",
  461. name,
  462. index.ToString(UsCulture),
  463. queryString));
  464. seconds -= state.SegmentLength;
  465. index++;
  466. }
  467. builder.AppendLine("#EXT-X-ENDLIST");
  468. var playlistText = builder.ToString();
  469. return ResultFactory.GetResult(playlistText, Common.Net.MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary<string, string>());
  470. }
  471. protected override string GetAudioArguments(StreamState state)
  472. {
  473. var codec = state.OutputAudioCodec;
  474. if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
  475. {
  476. return "-codec:a:0 copy";
  477. }
  478. var args = "-codec:a:0 " + codec;
  479. var channels = state.OutputAudioChannels;
  480. if (channels.HasValue)
  481. {
  482. args += " -ac " + channels.Value;
  483. }
  484. var bitrate = state.OutputAudioBitrate;
  485. if (bitrate.HasValue)
  486. {
  487. args += " -ab " + bitrate.Value.ToString(UsCulture);
  488. }
  489. args += " " + GetAudioFilterParam(state, true);
  490. return args;
  491. }
  492. protected override string GetVideoArguments(StreamState state)
  493. {
  494. var codec = state.OutputVideoCodec;
  495. // See if we can save come cpu cycles by avoiding encoding
  496. if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
  497. {
  498. // TOOD: Switch to -bsf dump_extra?
  499. return IsH264(state.VideoStream) ? "-codec:v:0 copy -bsf h264_mp4toannexb" : "-codec:v:0 copy";
  500. }
  501. var keyFrameArg = string.Format(" -force_key_frames expr:gte(t,n_forced*{0})",
  502. state.SegmentLength.ToString(UsCulture));
  503. var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream;
  504. var args = "-codec:v:0 " + codec + " " + GetVideoQualityParam(state, "libx264", true) + keyFrameArg;
  505. // Add resolution params, if specified
  506. if (!hasGraphicalSubs)
  507. {
  508. args += GetOutputSizeParam(state, codec, false);
  509. }
  510. // This is for internal graphical subs
  511. if (hasGraphicalSubs)
  512. {
  513. args += GetGraphicalSubtitleParam(state, codec);
  514. }
  515. return args;
  516. }
  517. protected override string GetCommandLineArguments(string outputPath, string transcodingJobId, StreamState state, bool isEncoding)
  518. {
  519. var threads = GetNumberOfThreads(state, false);
  520. var inputModifier = GetInputModifier(state);
  521. // If isEncoding is true we're actually starting ffmpeg
  522. var startNumberParam = isEncoding ? GetStartNumber(state).ToString(UsCulture) : "0";
  523. var args = string.Format("{0} -i {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}\"",
  524. inputModifier,
  525. GetInputArgument(transcodingJobId, state),
  526. threads,
  527. GetMapArgs(state),
  528. GetVideoArguments(state),
  529. GetAudioArguments(state),
  530. state.SegmentLength.ToString(UsCulture),
  531. startNumberParam,
  532. state.HlsListSize.ToString(UsCulture),
  533. outputPath
  534. ).Trim();
  535. return args;
  536. }
  537. /// <summary>
  538. /// Gets the segment file extension.
  539. /// </summary>
  540. /// <param name="state">The state.</param>
  541. /// <returns>System.String.</returns>
  542. protected override string GetSegmentFileExtension(StreamState state)
  543. {
  544. return ".ts";
  545. }
  546. protected override TranscodingJobType TranscodingJobType
  547. {
  548. get
  549. {
  550. return TranscodingJobType.Hls;
  551. }
  552. }
  553. }
  554. }