EncodingJobFactory.cs 31 KB

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