EncodingJobFactory.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  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. if (audioStream != null)
  278. {
  279. var codec = outputAudioCodec ?? string.Empty;
  280. if (audioStream.Channels > 2 && codec.IndexOf("wma", StringComparison.OrdinalIgnoreCase) != -1)
  281. {
  282. // wmav2 currently only supports two channel output
  283. return 2;
  284. }
  285. }
  286. if (request.MaxAudioChannels.HasValue)
  287. {
  288. if (audioStream != null && audioStream.Channels.HasValue)
  289. {
  290. return Math.Min(request.MaxAudioChannels.Value, audioStream.Channels.Value);
  291. }
  292. // If we don't have any media info then limit it to 5 to prevent encoding errors due to asking for too many channels
  293. return Math.Min(request.MaxAudioChannels.Value, 5);
  294. }
  295. return request.AudioChannels;
  296. }
  297. private int? GetVideoBitrateParamValue(EncodingJobOptions request, MediaStream videoStream)
  298. {
  299. var bitrate = request.VideoBitRate;
  300. if (videoStream != null)
  301. {
  302. var isUpscaling = request.Height.HasValue && videoStream.Height.HasValue &&
  303. request.Height.Value > videoStream.Height.Value;
  304. if (request.Width.HasValue && videoStream.Width.HasValue &&
  305. request.Width.Value > videoStream.Width.Value)
  306. {
  307. isUpscaling = true;
  308. }
  309. // Don't allow bitrate increases unless upscaling
  310. if (!isUpscaling)
  311. {
  312. if (bitrate.HasValue && videoStream.BitRate.HasValue)
  313. {
  314. bitrate = Math.Min(bitrate.Value, videoStream.BitRate.Value);
  315. }
  316. }
  317. }
  318. return bitrate;
  319. }
  320. protected string GetVideoBitrateParam(EncodingJob state, string videoCodec, bool isHls)
  321. {
  322. var bitrate = state.OutputVideoBitrate;
  323. if (bitrate.HasValue)
  324. {
  325. var hasFixedResolution = state.Options.HasFixedResolution;
  326. if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase))
  327. {
  328. if (hasFixedResolution)
  329. {
  330. return string.Format(" -minrate:v ({0}*.90) -maxrate:v ({0}*1.10) -bufsize:v {0} -b:v {0}", bitrate.Value.ToString(UsCulture));
  331. }
  332. // With vpx when crf is used, b:v becomes a max rate
  333. // 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.
  334. return string.Format(" -maxrate:v {0} -bufsize:v ({0}*2) -b:v {0}", bitrate.Value.ToString(UsCulture));
  335. }
  336. if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase))
  337. {
  338. return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture));
  339. }
  340. // H264
  341. if (hasFixedResolution)
  342. {
  343. if (isHls)
  344. {
  345. return string.Format(" -b:v {0} -maxrate ({0}*.80) -bufsize {0}", bitrate.Value.ToString(UsCulture));
  346. }
  347. return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture));
  348. }
  349. return string.Format(" -maxrate {0} -bufsize {1}",
  350. bitrate.Value.ToString(UsCulture),
  351. (bitrate.Value * 2).ToString(UsCulture));
  352. }
  353. return string.Empty;
  354. }
  355. private int? GetAudioBitrateParam(EncodingJobOptions request, MediaStream audioStream)
  356. {
  357. if (request.AudioBitRate.HasValue)
  358. {
  359. // Make sure we don't request a bitrate higher than the source
  360. var currentBitrate = audioStream == null ? request.AudioBitRate.Value : audioStream.BitRate ?? request.AudioBitRate.Value;
  361. return request.AudioBitRate.Value;
  362. //return Math.Min(currentBitrate, request.AudioBitRate.Value);
  363. }
  364. return null;
  365. }
  366. /// <summary>
  367. /// Determines whether the specified stream is H264.
  368. /// </summary>
  369. /// <param name="stream">The stream.</param>
  370. /// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
  371. protected bool IsH264(MediaStream stream)
  372. {
  373. var codec = stream.Codec ?? string.Empty;
  374. return codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1 ||
  375. codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
  376. }
  377. /// <summary>
  378. /// Gets the name of the output audio codec
  379. /// </summary>
  380. /// <param name="request">The request.</param>
  381. /// <returns>System.String.</returns>
  382. private string GetAudioCodec(EncodingJobOptions request)
  383. {
  384. var codec = request.AudioCodec;
  385. if (string.Equals(codec, "aac", StringComparison.OrdinalIgnoreCase))
  386. {
  387. return "aac -strict experimental";
  388. }
  389. if (string.Equals(codec, "mp3", StringComparison.OrdinalIgnoreCase))
  390. {
  391. return "libmp3lame";
  392. }
  393. if (string.Equals(codec, "vorbis", StringComparison.OrdinalIgnoreCase))
  394. {
  395. return "libvorbis";
  396. }
  397. if (string.Equals(codec, "wma", StringComparison.OrdinalIgnoreCase))
  398. {
  399. return "wmav2";
  400. }
  401. return (codec ?? string.Empty).ToLower();
  402. }
  403. /// <summary>
  404. /// Gets the name of the output video codec
  405. /// </summary>
  406. /// <param name="request">The request.</param>
  407. /// <returns>System.String.</returns>
  408. private string GetVideoCodec(EncodingJobOptions request)
  409. {
  410. var codec = request.VideoCodec;
  411. if (string.Equals(codec, "h264", StringComparison.OrdinalIgnoreCase))
  412. {
  413. return "libx264";
  414. }
  415. if (string.Equals(codec, "h265", StringComparison.OrdinalIgnoreCase))
  416. {
  417. return "libx265";
  418. }
  419. if (string.Equals(codec, "vpx", StringComparison.OrdinalIgnoreCase))
  420. {
  421. return "libvpx";
  422. }
  423. if (string.Equals(codec, "wmv", StringComparison.OrdinalIgnoreCase))
  424. {
  425. return "wmv2";
  426. }
  427. if (string.Equals(codec, "theora", StringComparison.OrdinalIgnoreCase))
  428. {
  429. return "libtheora";
  430. }
  431. return (codec ?? string.Empty).ToLower();
  432. }
  433. internal static bool CanStreamCopyVideo(EncodingJobOptions request, MediaStream videoStream)
  434. {
  435. if (videoStream.IsInterlaced)
  436. {
  437. return false;
  438. }
  439. // Can't stream copy if we're burning in subtitles
  440. if (request.SubtitleStreamIndex.HasValue)
  441. {
  442. if (request.SubtitleMethod == SubtitleDeliveryMethod.Encode)
  443. {
  444. return false;
  445. }
  446. }
  447. // Source and target codecs must match
  448. if (!string.Equals(request.VideoCodec, videoStream.Codec, StringComparison.OrdinalIgnoreCase))
  449. {
  450. return false;
  451. }
  452. // If client is requesting a specific video profile, it must match the source
  453. if (!string.IsNullOrEmpty(request.Profile))
  454. {
  455. if (string.IsNullOrEmpty(videoStream.Profile))
  456. {
  457. return false;
  458. }
  459. if (!string.Equals(request.Profile, videoStream.Profile, StringComparison.OrdinalIgnoreCase))
  460. {
  461. var currentScore = GetVideoProfileScore(videoStream.Profile);
  462. var requestedScore = GetVideoProfileScore(request.Profile);
  463. if (currentScore == -1 || currentScore > requestedScore)
  464. {
  465. return false;
  466. }
  467. }
  468. }
  469. // Video width must fall within requested value
  470. if (request.MaxWidth.HasValue)
  471. {
  472. if (!videoStream.Width.HasValue || videoStream.Width.Value > request.MaxWidth.Value)
  473. {
  474. return false;
  475. }
  476. }
  477. // Video height must fall within requested value
  478. if (request.MaxHeight.HasValue)
  479. {
  480. if (!videoStream.Height.HasValue || videoStream.Height.Value > request.MaxHeight.Value)
  481. {
  482. return false;
  483. }
  484. }
  485. // Video framerate must fall within requested value
  486. var requestedFramerate = request.MaxFramerate ?? request.Framerate;
  487. if (requestedFramerate.HasValue)
  488. {
  489. var videoFrameRate = videoStream.AverageFrameRate ?? videoStream.RealFrameRate;
  490. if (!videoFrameRate.HasValue || videoFrameRate.Value > requestedFramerate.Value)
  491. {
  492. return false;
  493. }
  494. }
  495. // Video bitrate must fall within requested value
  496. if (request.VideoBitRate.HasValue)
  497. {
  498. if (!videoStream.BitRate.HasValue || videoStream.BitRate.Value > request.VideoBitRate.Value)
  499. {
  500. return false;
  501. }
  502. }
  503. if (request.MaxVideoBitDepth.HasValue)
  504. {
  505. if (videoStream.BitDepth.HasValue && videoStream.BitDepth.Value > request.MaxVideoBitDepth.Value)
  506. {
  507. return false;
  508. }
  509. }
  510. if (request.MaxRefFrames.HasValue)
  511. {
  512. if (videoStream.RefFrames.HasValue && videoStream.RefFrames.Value > request.MaxRefFrames.Value)
  513. {
  514. return false;
  515. }
  516. }
  517. // If a specific level was requested, the source must match or be less than
  518. if (request.Level.HasValue)
  519. {
  520. if (!videoStream.Level.HasValue)
  521. {
  522. return false;
  523. }
  524. if (videoStream.Level.Value > request.Level.Value)
  525. {
  526. return false;
  527. }
  528. }
  529. if (request.Cabac.HasValue && request.Cabac.Value)
  530. {
  531. if (videoStream.IsCabac.HasValue && !videoStream.IsCabac.Value)
  532. {
  533. return false;
  534. }
  535. }
  536. return request.EnableAutoStreamCopy;
  537. }
  538. private static int GetVideoProfileScore(string profile)
  539. {
  540. var list = new List<string>
  541. {
  542. "Constrained Baseline",
  543. "Baseline",
  544. "Extended",
  545. "Main",
  546. "High",
  547. "Progressive High",
  548. "Constrained High"
  549. };
  550. return Array.FindIndex(list.ToArray(), t => string.Equals(t, profile, StringComparison.OrdinalIgnoreCase));
  551. }
  552. internal static bool CanStreamCopyAudio(EncodingJobOptions request, MediaStream audioStream, List<string> supportedAudioCodecs)
  553. {
  554. // Source and target codecs must match
  555. if (string.IsNullOrEmpty(audioStream.Codec) || !supportedAudioCodecs.Contains(audioStream.Codec, StringComparer.OrdinalIgnoreCase))
  556. {
  557. return false;
  558. }
  559. // Video bitrate must fall within requested value
  560. if (request.AudioBitRate.HasValue)
  561. {
  562. if (!audioStream.BitRate.HasValue || audioStream.BitRate.Value <= 0)
  563. {
  564. return false;
  565. }
  566. if (audioStream.BitRate.Value > request.AudioBitRate.Value)
  567. {
  568. return false;
  569. }
  570. }
  571. // Channels must fall within requested value
  572. var channels = request.AudioChannels ?? request.MaxAudioChannels;
  573. if (channels.HasValue)
  574. {
  575. if (!audioStream.Channels.HasValue || audioStream.Channels.Value <= 0)
  576. {
  577. return false;
  578. }
  579. if (audioStream.Channels.Value > channels.Value)
  580. {
  581. return false;
  582. }
  583. }
  584. // Sample rate must fall within requested value
  585. if (request.AudioSampleRate.HasValue)
  586. {
  587. if (!audioStream.SampleRate.HasValue || audioStream.SampleRate.Value <= 0)
  588. {
  589. return false;
  590. }
  591. if (audioStream.SampleRate.Value > request.AudioSampleRate.Value)
  592. {
  593. return false;
  594. }
  595. }
  596. return request.EnableAutoStreamCopy;
  597. }
  598. private void ApplyDeviceProfileSettings(EncodingJob state)
  599. {
  600. var profile = state.Options.DeviceProfile;
  601. if (profile == null)
  602. {
  603. // Don't use settings from the default profile.
  604. // Only use a specific profile if it was requested.
  605. return;
  606. }
  607. var audioCodec = state.ActualOutputAudioCodec;
  608. var videoCodec = state.ActualOutputVideoCodec;
  609. var outputContainer = state.Options.OutputContainer;
  610. var mediaProfile = state.IsVideoRequest ?
  611. profile.GetAudioMediaProfile(outputContainer, audioCodec, state.OutputAudioChannels, state.OutputAudioBitrate) :
  612. profile.GetVideoMediaProfile(outputContainer,
  613. audioCodec,
  614. videoCodec,
  615. state.OutputWidth,
  616. state.OutputHeight,
  617. state.TargetVideoBitDepth,
  618. state.OutputVideoBitrate,
  619. state.TargetVideoProfile,
  620. state.TargetVideoLevel,
  621. state.TargetFramerate,
  622. state.TargetPacketLength,
  623. state.TargetTimestamp,
  624. state.IsTargetAnamorphic,
  625. state.IsTargetCabac,
  626. state.TargetRefFrames,
  627. state.TargetVideoStreamCount,
  628. state.TargetAudioStreamCount);
  629. if (mediaProfile != null)
  630. {
  631. state.MimeType = mediaProfile.MimeType;
  632. }
  633. var transcodingProfile = state.IsVideoRequest ?
  634. profile.GetAudioTranscodingProfile(outputContainer, audioCodec) :
  635. profile.GetVideoTranscodingProfile(outputContainer, audioCodec, videoCodec);
  636. if (transcodingProfile != null)
  637. {
  638. state.EstimateContentLength = transcodingProfile.EstimateContentLength;
  639. state.EnableMpegtsM2TsMode = transcodingProfile.EnableMpegtsM2TsMode;
  640. state.TranscodeSeekInfo = transcodingProfile.TranscodeSeekInfo;
  641. }
  642. }
  643. }
  644. }