EncodingJobFactory.cs 29 KB

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