2
0

EncodingJobFactory.cs 29 KB

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