EncodingJobFactory.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Controller.Library;
  3. using MediaBrowser.Controller.MediaEncoding;
  4. using MediaBrowser.Model.Configuration;
  5. using MediaBrowser.Model.Dlna;
  6. using MediaBrowser.Model.Dto;
  7. using MediaBrowser.Model.Entities;
  8. using MediaBrowser.Model.Logging;
  9. using MediaBrowser.Model.MediaInfo;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Globalization;
  13. using System.Linq;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. namespace MediaBrowser.MediaEncoding.Encoder
  17. {
  18. public class EncodingJobFactory
  19. {
  20. private readonly ILogger _logger;
  21. private readonly ILibraryManager _libraryManager;
  22. private readonly IMediaSourceManager _mediaSourceManager;
  23. private readonly IConfigurationManager _config;
  24. protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  25. public EncodingJobFactory(ILogger logger, ILibraryManager libraryManager, IMediaSourceManager mediaSourceManager, IConfigurationManager config)
  26. {
  27. _logger = logger;
  28. _libraryManager = libraryManager;
  29. _mediaSourceManager = mediaSourceManager;
  30. _config = config;
  31. }
  32. public async Task<EncodingJob> CreateJob(EncodingJobOptions options, bool isVideoRequest, IProgress<double> progress, CancellationToken cancellationToken)
  33. {
  34. var request = options;
  35. if (string.IsNullOrEmpty(request.AudioCodec))
  36. {
  37. request.AudioCodec = InferAudioCodec(request.OutputContainer);
  38. }
  39. var state = new EncodingJob(_logger, _mediaSourceManager)
  40. {
  41. Options = options,
  42. IsVideoRequest = isVideoRequest,
  43. Progress = progress
  44. };
  45. if (!string.IsNullOrWhiteSpace(request.AudioCodec))
  46. {
  47. state.SupportedAudioCodecs = request.AudioCodec.Split(',').Where(i => !string.IsNullOrWhiteSpace(i)).ToList();
  48. request.AudioCodec = state.SupportedAudioCodecs.FirstOrDefault();
  49. }
  50. var item = _libraryManager.GetItemById(request.ItemId);
  51. state.ItemType = item.GetType().Name;
  52. state.IsInputVideo = string.Equals(item.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
  53. var mediaSources = await _mediaSourceManager.GetPlayackMediaSources(request.ItemId, null, false, new[] { MediaType.Audio, MediaType.Video }, cancellationToken).ConfigureAwait(false);
  54. var mediaSource = string.IsNullOrEmpty(request.MediaSourceId)
  55. ? mediaSources.First()
  56. : mediaSources.First(i => string.Equals(i.Id, request.MediaSourceId));
  57. AttachMediaStreamInfo(state, mediaSource, options);
  58. state.OutputAudioBitrate = GetAudioBitrateParam(request, state.AudioStream);
  59. state.OutputAudioSampleRate = request.AudioSampleRate;
  60. state.OutputAudioCodec = GetAudioCodec(request);
  61. state.OutputAudioChannels = GetNumAudioChannelsParam(request, state.AudioStream, state.OutputAudioCodec);
  62. if (isVideoRequest)
  63. {
  64. state.OutputVideoCodec = GetVideoCodec(request);
  65. state.OutputVideoBitrate = GetVideoBitrateParamValue(request, state.VideoStream);
  66. if (state.OutputVideoBitrate.HasValue)
  67. {
  68. var resolution = ResolutionNormalizer.Normalize(state.OutputVideoBitrate.Value,
  69. state.OutputVideoCodec,
  70. request.MaxWidth,
  71. request.MaxHeight);
  72. request.MaxWidth = resolution.MaxWidth;
  73. request.MaxHeight = resolution.MaxHeight;
  74. }
  75. }
  76. ApplyDeviceProfileSettings(state);
  77. TryStreamCopy(state, request);
  78. return state;
  79. }
  80. internal static void TryStreamCopy(EncodingJob state,
  81. EncodingJobOptions videoRequest)
  82. {
  83. if (state.IsVideoRequest)
  84. {
  85. if (state.VideoStream != null && CanStreamCopyVideo(videoRequest, state.VideoStream))
  86. {
  87. state.OutputVideoCodec = "copy";
  88. }
  89. if (state.AudioStream != null && CanStreamCopyAudio(videoRequest, state.AudioStream, state.SupportedAudioCodecs))
  90. {
  91. state.OutputAudioCodec = "copy";
  92. }
  93. }
  94. }
  95. internal static void AttachMediaStreamInfo(EncodingJob state,
  96. MediaSourceInfo mediaSource,
  97. EncodingJobOptions videoRequest)
  98. {
  99. state.MediaPath = mediaSource.Path;
  100. state.InputProtocol = mediaSource.Protocol;
  101. state.InputContainer = mediaSource.Container;
  102. state.InputFileSize = mediaSource.Size;
  103. state.InputBitrate = mediaSource.Bitrate;
  104. state.RunTimeTicks = mediaSource.RunTimeTicks;
  105. state.RemoteHttpHeaders = mediaSource.RequiredHttpHeaders;
  106. if (mediaSource.ReadAtNativeFramerate)
  107. {
  108. state.ReadInputAtNativeFramerate = true;
  109. }
  110. if (mediaSource.VideoType.HasValue)
  111. {
  112. state.VideoType = mediaSource.VideoType.Value;
  113. }
  114. state.IsoType = mediaSource.IsoType;
  115. state.PlayableStreamFileNames = mediaSource.PlayableStreamFileNames.ToList();
  116. if (mediaSource.Timestamp.HasValue)
  117. {
  118. state.InputTimestamp = mediaSource.Timestamp.Value;
  119. }
  120. state.InputProtocol = mediaSource.Protocol;
  121. state.MediaPath = mediaSource.Path;
  122. state.RunTimeTicks = mediaSource.RunTimeTicks;
  123. state.RemoteHttpHeaders = mediaSource.RequiredHttpHeaders;
  124. state.InputBitrate = mediaSource.Bitrate;
  125. state.InputFileSize = mediaSource.Size;
  126. if (state.ReadInputAtNativeFramerate ||
  127. mediaSource.Protocol == MediaProtocol.File && string.Equals(mediaSource.Container, "wtv", StringComparison.OrdinalIgnoreCase))
  128. {
  129. state.OutputAudioSync = "1000";
  130. state.InputVideoSync = "-1";
  131. state.InputAudioSync = "1";
  132. }
  133. var mediaStreams = mediaSource.MediaStreams;
  134. if (videoRequest != null)
  135. {
  136. if (string.IsNullOrEmpty(videoRequest.VideoCodec))
  137. {
  138. videoRequest.VideoCodec = InferVideoCodec(videoRequest.OutputContainer);
  139. }
  140. state.VideoStream = GetMediaStream(mediaStreams, videoRequest.VideoStreamIndex, MediaStreamType.Video);
  141. state.SubtitleStream = GetMediaStream(mediaStreams, videoRequest.SubtitleStreamIndex, MediaStreamType.Subtitle, false);
  142. state.AudioStream = GetMediaStream(mediaStreams, videoRequest.AudioStreamIndex, MediaStreamType.Audio);
  143. if (state.SubtitleStream != null && !state.SubtitleStream.IsExternal)
  144. {
  145. state.InternalSubtitleStreamOffset = mediaStreams.Where(i => i.Type == MediaStreamType.Subtitle && !i.IsExternal).ToList().IndexOf(state.SubtitleStream);
  146. }
  147. if (state.VideoStream != null && state.VideoStream.IsInterlaced)
  148. {
  149. state.DeInterlace = true;
  150. }
  151. EnforceResolutionLimit(state, videoRequest);
  152. }
  153. else
  154. {
  155. state.AudioStream = GetMediaStream(mediaStreams, null, MediaStreamType.Audio, true);
  156. }
  157. state.MediaSource = mediaSource;
  158. }
  159. protected EncodingOptions GetEncodingOptions()
  160. {
  161. return _config.GetConfiguration<EncodingOptions>("encoding");
  162. }
  163. /// <summary>
  164. /// Infers the video codec.
  165. /// </summary>
  166. /// <param name="container">The container.</param>
  167. /// <returns>System.Nullable{VideoCodecs}.</returns>
  168. private static string InferVideoCodec(string container)
  169. {
  170. if (string.Equals(container, "asf", StringComparison.OrdinalIgnoreCase))
  171. {
  172. return "wmv";
  173. }
  174. if (string.Equals(container, "webm", StringComparison.OrdinalIgnoreCase))
  175. {
  176. return "vpx";
  177. }
  178. if (string.Equals(container, "ogg", StringComparison.OrdinalIgnoreCase) || string.Equals(container, "ogv", StringComparison.OrdinalIgnoreCase))
  179. {
  180. return "theora";
  181. }
  182. if (string.Equals(container, "m3u8", StringComparison.OrdinalIgnoreCase) || string.Equals(container, "ts", StringComparison.OrdinalIgnoreCase))
  183. {
  184. return "h264";
  185. }
  186. return "copy";
  187. }
  188. private string InferAudioCodec(string container)
  189. {
  190. if (string.Equals(container, "mp3", StringComparison.OrdinalIgnoreCase))
  191. {
  192. return "mp3";
  193. }
  194. if (string.Equals(container, "aac", StringComparison.OrdinalIgnoreCase))
  195. {
  196. return "aac";
  197. }
  198. if (string.Equals(container, "wma", StringComparison.OrdinalIgnoreCase))
  199. {
  200. return "wma";
  201. }
  202. if (string.Equals(container, "ogg", StringComparison.OrdinalIgnoreCase))
  203. {
  204. return "vorbis";
  205. }
  206. if (string.Equals(container, "oga", StringComparison.OrdinalIgnoreCase))
  207. {
  208. return "vorbis";
  209. }
  210. if (string.Equals(container, "ogv", StringComparison.OrdinalIgnoreCase))
  211. {
  212. return "vorbis";
  213. }
  214. if (string.Equals(container, "webm", StringComparison.OrdinalIgnoreCase))
  215. {
  216. return "vorbis";
  217. }
  218. if (string.Equals(container, "webma", StringComparison.OrdinalIgnoreCase))
  219. {
  220. return "vorbis";
  221. }
  222. return "copy";
  223. }
  224. /// <summary>
  225. /// Determines which stream will be used for playback
  226. /// </summary>
  227. /// <param name="allStream">All stream.</param>
  228. /// <param name="desiredIndex">Index of the desired.</param>
  229. /// <param name="type">The type.</param>
  230. /// <param name="returnFirstIfNoIndex">if set to <c>true</c> [return first if no index].</param>
  231. /// <returns>MediaStream.</returns>
  232. private static MediaStream GetMediaStream(IEnumerable<MediaStream> allStream, int? desiredIndex, MediaStreamType type, bool returnFirstIfNoIndex = true)
  233. {
  234. var streams = allStream.Where(s => s.Type == type).OrderBy(i => i.Index).ToList();
  235. if (desiredIndex.HasValue)
  236. {
  237. var stream = streams.FirstOrDefault(s => s.Index == desiredIndex.Value);
  238. if (stream != null)
  239. {
  240. return stream;
  241. }
  242. }
  243. if (type == MediaStreamType.Video)
  244. {
  245. streams = streams.Where(i => !string.Equals(i.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase)).ToList();
  246. }
  247. if (returnFirstIfNoIndex && type == MediaStreamType.Audio)
  248. {
  249. return streams.FirstOrDefault(i => i.Channels.HasValue && i.Channels.Value > 0) ??
  250. streams.FirstOrDefault();
  251. }
  252. // Just return the first one
  253. return returnFirstIfNoIndex ? streams.FirstOrDefault() : null;
  254. }
  255. /// <summary>
  256. /// Enforces the resolution limit.
  257. /// </summary>
  258. /// <param name="state">The state.</param>
  259. /// <param name="videoRequest">The video request.</param>
  260. private static void EnforceResolutionLimit(EncodingJob state, EncodingJobOptions videoRequest)
  261. {
  262. // Switch the incoming params to be ceilings rather than fixed values
  263. videoRequest.MaxWidth = videoRequest.MaxWidth ?? videoRequest.Width;
  264. videoRequest.MaxHeight = videoRequest.MaxHeight ?? videoRequest.Height;
  265. videoRequest.Width = null;
  266. videoRequest.Height = null;
  267. }
  268. /// <summary>
  269. /// Gets the number of audio channels to specify on the command line
  270. /// </summary>
  271. /// <param name="request">The request.</param>
  272. /// <param name="audioStream">The audio stream.</param>
  273. /// <param name="outputAudioCodec">The output audio codec.</param>
  274. /// <returns>System.Nullable{System.Int32}.</returns>
  275. private int? GetNumAudioChannelsParam(EncodingJobOptions request, MediaStream audioStream, string outputAudioCodec)
  276. {
  277. var inputChannels = audioStream == null
  278. ? null
  279. : audioStream.Channels;
  280. if (inputChannels <= 0)
  281. {
  282. inputChannels = null;
  283. }
  284. var codec = outputAudioCodec ?? string.Empty;
  285. if (codec.IndexOf("wma", StringComparison.OrdinalIgnoreCase) != -1)
  286. {
  287. // wmav2 currently only supports two channel output
  288. return Math.Min(2, inputChannels ?? 2);
  289. }
  290. if (request.MaxAudioChannels.HasValue)
  291. {
  292. if (inputChannels.HasValue)
  293. {
  294. return Math.Min(request.MaxAudioChannels.Value, inputChannels.Value);
  295. }
  296. var channelLimit = codec.IndexOf("mp3", StringComparison.OrdinalIgnoreCase) != -1
  297. ? 2
  298. : 6;
  299. // If we don't have any media info then limit it to 5 to prevent encoding errors due to asking for too many channels
  300. return Math.Min(request.MaxAudioChannels.Value, channelLimit);
  301. }
  302. return request.AudioChannels;
  303. }
  304. private int? GetVideoBitrateParamValue(EncodingJobOptions request, MediaStream videoStream)
  305. {
  306. var bitrate = request.VideoBitRate;
  307. if (videoStream != null)
  308. {
  309. var isUpscaling = request.Height.HasValue && videoStream.Height.HasValue &&
  310. request.Height.Value > videoStream.Height.Value;
  311. if (request.Width.HasValue && videoStream.Width.HasValue &&
  312. request.Width.Value > videoStream.Width.Value)
  313. {
  314. isUpscaling = true;
  315. }
  316. // Don't allow bitrate increases unless upscaling
  317. if (!isUpscaling)
  318. {
  319. if (bitrate.HasValue && videoStream.BitRate.HasValue)
  320. {
  321. bitrate = Math.Min(bitrate.Value, videoStream.BitRate.Value);
  322. }
  323. }
  324. }
  325. return bitrate;
  326. }
  327. protected string GetVideoBitrateParam(EncodingJob state, string videoCodec, bool isHls)
  328. {
  329. var bitrate = state.OutputVideoBitrate;
  330. if (bitrate.HasValue)
  331. {
  332. var hasFixedResolution = state.Options.HasFixedResolution;
  333. if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
  334. {
  335. if (hasFixedResolution)
  336. {
  337. return string.Format(" -minrate:v ({0}*.90) -maxrate:v ({0}*1.10) -bufsize:v {0} -b:v {0}", bitrate.Value.ToString(UsCulture));
  338. }
  339. // With vpx when crf is used, b:v becomes a max rate
  340. // https://trac.ffmpeg.org/wiki/vpxEncodingGuide. But higher bitrate source files -b:v causes judder so limite the bitrate but dont allow it to "saturate" the bitrate. So dont contrain it down just up.
  341. return string.Format(" -maxrate:v {0} -bufsize:v ({0}*2) -b:v {0}", bitrate.Value.ToString(UsCulture));
  342. }
  343. if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  344. {
  345. return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture));
  346. }
  347. // H264
  348. if (hasFixedResolution)
  349. {
  350. if (isHls)
  351. {
  352. return string.Format(" -b:v {0} -maxrate ({0}*.80) -bufsize {0}", bitrate.Value.ToString(UsCulture));
  353. }
  354. return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture));
  355. }
  356. return string.Format(" -maxrate {0} -bufsize {1}",
  357. bitrate.Value.ToString(UsCulture),
  358. (bitrate.Value * 2).ToString(UsCulture));
  359. }
  360. return string.Empty;
  361. }
  362. private int? GetAudioBitrateParam(EncodingJobOptions request, MediaStream audioStream)
  363. {
  364. if (request.AudioBitRate.HasValue)
  365. {
  366. // Make sure we don't request a bitrate higher than the source
  367. var currentBitrate = audioStream == null ? request.AudioBitRate.Value : audioStream.BitRate ?? request.AudioBitRate.Value;
  368. return request.AudioBitRate.Value;
  369. //return Math.Min(currentBitrate, request.AudioBitRate.Value);
  370. }
  371. return null;
  372. }
  373. /// <summary>
  374. /// Determines whether the specified stream is H264.
  375. /// </summary>
  376. /// <param name="stream">The stream.</param>
  377. /// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
  378. protected bool IsH264(MediaStream stream)
  379. {
  380. var codec = stream.Codec ?? string.Empty;
  381. return codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1 ||
  382. codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
  383. }
  384. /// <summary>
  385. /// Gets the name of the output audio codec
  386. /// </summary>
  387. /// <param name="request">The request.</param>
  388. /// <returns>System.String.</returns>
  389. private string GetAudioCodec(EncodingJobOptions request)
  390. {
  391. var codec = request.AudioCodec;
  392. if (string.Equals(codec, "aac", StringComparison.OrdinalIgnoreCase))
  393. {
  394. return "aac -strict experimental";
  395. }
  396. if (string.Equals(codec, "mp3", StringComparison.OrdinalIgnoreCase))
  397. {
  398. return "libmp3lame";
  399. }
  400. if (string.Equals(codec, "vorbis", StringComparison.OrdinalIgnoreCase))
  401. {
  402. return "libvorbis";
  403. }
  404. if (string.Equals(codec, "wma", StringComparison.OrdinalIgnoreCase))
  405. {
  406. return "wmav2";
  407. }
  408. return (codec ?? string.Empty).ToLower();
  409. }
  410. /// <summary>
  411. /// Gets the name of the output video codec
  412. /// </summary>
  413. /// <param name="request">The request.</param>
  414. /// <returns>System.String.</returns>
  415. private string GetVideoCodec(EncodingJobOptions request)
  416. {
  417. var codec = request.VideoCodec;
  418. if (string.Equals(codec, "h264", StringComparison.OrdinalIgnoreCase))
  419. {
  420. return "libx264";
  421. }
  422. if (string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase))
  423. {
  424. return "libx265";
  425. }
  426. if (string.Equals(codec, "vpx", StringComparison.OrdinalIgnoreCase))
  427. {
  428. return "libvpx";
  429. }
  430. if (string.Equals(codec, "wmv", StringComparison.OrdinalIgnoreCase))
  431. {
  432. return "wmv2";
  433. }
  434. if (string.Equals(codec, "theora", StringComparison.OrdinalIgnoreCase))
  435. {
  436. return "libtheora";
  437. }
  438. return (codec ?? string.Empty).ToLower();
  439. }
  440. internal static bool CanStreamCopyVideo(EncodingJobOptions request, MediaStream videoStream)
  441. {
  442. if (videoStream.IsInterlaced)
  443. {
  444. return false;
  445. }
  446. if (videoStream.IsAnamorphic ?? false)
  447. {
  448. return false;
  449. }
  450. // Can't stream copy if we're burning in subtitles
  451. if (request.SubtitleStreamIndex.HasValue)
  452. {
  453. if (request.SubtitleMethod == SubtitleDeliveryMethod.Encode)
  454. {
  455. return false;
  456. }
  457. }
  458. // Source and target codecs must match
  459. if (!string.Equals(request.VideoCodec, videoStream.Codec, StringComparison.OrdinalIgnoreCase))
  460. {
  461. return false;
  462. }
  463. // If client is requesting a specific video profile, it must match the source
  464. if (!string.IsNullOrEmpty(request.Profile))
  465. {
  466. if (string.IsNullOrEmpty(videoStream.Profile))
  467. {
  468. return false;
  469. }
  470. if (!string.Equals(request.Profile, videoStream.Profile, StringComparison.OrdinalIgnoreCase))
  471. {
  472. var currentScore = GetVideoProfileScore(videoStream.Profile);
  473. var requestedScore = GetVideoProfileScore(request.Profile);
  474. if (currentScore == -1 || currentScore > requestedScore)
  475. {
  476. return false;
  477. }
  478. }
  479. }
  480. // Video width must fall within requested value
  481. if (request.MaxWidth.HasValue)
  482. {
  483. if (!videoStream.Width.HasValue || videoStream.Width.Value > request.MaxWidth.Value)
  484. {
  485. return false;
  486. }
  487. }
  488. // Video height must fall within requested value
  489. if (request.MaxHeight.HasValue)
  490. {
  491. if (!videoStream.Height.HasValue || videoStream.Height.Value > request.MaxHeight.Value)
  492. {
  493. return false;
  494. }
  495. }
  496. // Video framerate must fall within requested value
  497. var requestedFramerate = request.MaxFramerate ?? request.Framerate;
  498. if (requestedFramerate.HasValue)
  499. {
  500. var videoFrameRate = videoStream.AverageFrameRate ?? videoStream.RealFrameRate;
  501. if (!videoFrameRate.HasValue || videoFrameRate.Value > requestedFramerate.Value)
  502. {
  503. return false;
  504. }
  505. }
  506. // Video bitrate must fall within requested value
  507. if (request.VideoBitRate.HasValue)
  508. {
  509. if (!videoStream.BitRate.HasValue || videoStream.BitRate.Value > request.VideoBitRate.Value)
  510. {
  511. return false;
  512. }
  513. }
  514. if (request.MaxVideoBitDepth.HasValue)
  515. {
  516. if (videoStream.BitDepth.HasValue && videoStream.BitDepth.Value > request.MaxVideoBitDepth.Value)
  517. {
  518. return false;
  519. }
  520. }
  521. if (request.MaxRefFrames.HasValue)
  522. {
  523. if (videoStream.RefFrames.HasValue && videoStream.RefFrames.Value > request.MaxRefFrames.Value)
  524. {
  525. return false;
  526. }
  527. }
  528. // If a specific level was requested, the source must match or be less than
  529. if (request.Level.HasValue)
  530. {
  531. if (!videoStream.Level.HasValue)
  532. {
  533. return false;
  534. }
  535. if (videoStream.Level.Value > request.Level.Value)
  536. {
  537. return false;
  538. }
  539. }
  540. if (request.Cabac.HasValue && request.Cabac.Value)
  541. {
  542. if (videoStream.IsCabac.HasValue && !videoStream.IsCabac.Value)
  543. {
  544. return false;
  545. }
  546. }
  547. return request.EnableAutoStreamCopy;
  548. }
  549. private static int GetVideoProfileScore(string profile)
  550. {
  551. var list = new List<string>
  552. {
  553. "Constrained Baseline",
  554. "Baseline",
  555. "Extended",
  556. "Main",
  557. "High",
  558. "Progressive High",
  559. "Constrained High"
  560. };
  561. return Array.FindIndex(list.ToArray(), t => string.Equals(t, profile, StringComparison.OrdinalIgnoreCase));
  562. }
  563. internal static bool CanStreamCopyAudio(EncodingJobOptions request, MediaStream audioStream, List<string> supportedAudioCodecs)
  564. {
  565. // Source and target codecs must match
  566. if (string.IsNullOrEmpty(audioStream.Codec) || !supportedAudioCodecs.Contains(audioStream.Codec, StringComparer.OrdinalIgnoreCase))
  567. {
  568. return false;
  569. }
  570. // Video bitrate must fall within requested value
  571. if (request.AudioBitRate.HasValue)
  572. {
  573. if (!audioStream.BitRate.HasValue || audioStream.BitRate.Value <= 0)
  574. {
  575. return false;
  576. }
  577. if (audioStream.BitRate.Value > request.AudioBitRate.Value)
  578. {
  579. return false;
  580. }
  581. }
  582. // Channels must fall within requested value
  583. var channels = request.AudioChannels ?? request.MaxAudioChannels;
  584. if (channels.HasValue)
  585. {
  586. if (!audioStream.Channels.HasValue || audioStream.Channels.Value <= 0)
  587. {
  588. return false;
  589. }
  590. if (audioStream.Channels.Value > channels.Value)
  591. {
  592. return false;
  593. }
  594. }
  595. // Sample rate must fall within requested value
  596. if (request.AudioSampleRate.HasValue)
  597. {
  598. if (!audioStream.SampleRate.HasValue || audioStream.SampleRate.Value <= 0)
  599. {
  600. return false;
  601. }
  602. if (audioStream.SampleRate.Value > request.AudioSampleRate.Value)
  603. {
  604. return false;
  605. }
  606. }
  607. return request.EnableAutoStreamCopy;
  608. }
  609. private void ApplyDeviceProfileSettings(EncodingJob state)
  610. {
  611. var profile = state.Options.DeviceProfile;
  612. if (profile == null)
  613. {
  614. // Don't use settings from the default profile.
  615. // Only use a specific profile if it was requested.
  616. return;
  617. }
  618. var audioCodec = state.ActualOutputAudioCodec;
  619. var videoCodec = state.ActualOutputVideoCodec;
  620. var outputContainer = state.Options.OutputContainer;
  621. var mediaProfile = state.IsVideoRequest ?
  622. profile.GetAudioMediaProfile(outputContainer, audioCodec, state.OutputAudioChannels, state.OutputAudioBitrate) :
  623. profile.GetVideoMediaProfile(outputContainer,
  624. audioCodec,
  625. videoCodec,
  626. state.OutputWidth,
  627. state.OutputHeight,
  628. state.TargetVideoBitDepth,
  629. state.OutputVideoBitrate,
  630. state.TargetVideoProfile,
  631. state.TargetVideoLevel,
  632. state.TargetFramerate,
  633. state.TargetPacketLength,
  634. state.TargetTimestamp,
  635. state.IsTargetAnamorphic,
  636. state.IsTargetCabac,
  637. state.TargetRefFrames,
  638. state.TargetVideoStreamCount,
  639. state.TargetAudioStreamCount,
  640. state.TargetVideoCodecTag);
  641. if (mediaProfile != null)
  642. {
  643. state.MimeType = mediaProfile.MimeType;
  644. }
  645. var transcodingProfile = state.IsVideoRequest ?
  646. profile.GetAudioTranscodingProfile(outputContainer, audioCodec) :
  647. profile.GetVideoTranscodingProfile(outputContainer, audioCodec, videoCodec);
  648. if (transcodingProfile != null)
  649. {
  650. state.EstimateContentLength = transcodingProfile.EstimateContentLength;
  651. state.EnableMpegtsM2TsMode = transcodingProfile.EnableMpegtsM2TsMode;
  652. state.TranscodeSeekInfo = transcodingProfile.TranscodeSeekInfo;
  653. }
  654. }
  655. }
  656. }