EncodingJobFactory.cs 28 KB

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