StreamBuilder.cs 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215
  1. using MediaBrowser.Model.Dto;
  2. using MediaBrowser.Model.Entities;
  3. using MediaBrowser.Model.Extensions;
  4. using MediaBrowser.Model.Logging;
  5. using MediaBrowser.Model.MediaInfo;
  6. using MediaBrowser.Model.Session;
  7. using System;
  8. using System.Collections.Generic;
  9. namespace MediaBrowser.Model.Dlna
  10. {
  11. public class StreamBuilder
  12. {
  13. private readonly ILogger _logger;
  14. private readonly ITranscoderSupport _transcoderSupport;
  15. public StreamBuilder(ITranscoderSupport transcoderSupport, ILogger logger)
  16. {
  17. _transcoderSupport = transcoderSupport;
  18. _logger = logger;
  19. }
  20. public StreamBuilder(ILogger logger)
  21. : this(new FullTranscoderSupport(), logger)
  22. {
  23. }
  24. public StreamInfo BuildAudioItem(AudioOptions options)
  25. {
  26. ValidateAudioInput(options);
  27. List<MediaSourceInfo> mediaSources = new List<MediaSourceInfo>();
  28. foreach (MediaSourceInfo i in options.MediaSources)
  29. {
  30. if (string.IsNullOrEmpty(options.MediaSourceId) ||
  31. StringHelper.EqualsIgnoreCase(i.Id, options.MediaSourceId))
  32. {
  33. mediaSources.Add(i);
  34. }
  35. }
  36. List<StreamInfo> streams = new List<StreamInfo>();
  37. foreach (MediaSourceInfo i in mediaSources)
  38. {
  39. StreamInfo streamInfo = BuildAudioItem(i, options);
  40. if (streamInfo != null)
  41. {
  42. streams.Add(streamInfo);
  43. }
  44. }
  45. foreach (StreamInfo stream in streams)
  46. {
  47. stream.DeviceId = options.DeviceId;
  48. stream.DeviceProfileId = options.Profile.Id;
  49. }
  50. return GetOptimalStream(streams, options.GetMaxBitrate());
  51. }
  52. public StreamInfo BuildVideoItem(VideoOptions options)
  53. {
  54. ValidateInput(options);
  55. List<MediaSourceInfo> mediaSources = new List<MediaSourceInfo>();
  56. foreach (MediaSourceInfo i in options.MediaSources)
  57. {
  58. if (string.IsNullOrEmpty(options.MediaSourceId) ||
  59. StringHelper.EqualsIgnoreCase(i.Id, options.MediaSourceId))
  60. {
  61. mediaSources.Add(i);
  62. }
  63. }
  64. List<StreamInfo> streams = new List<StreamInfo>();
  65. foreach (MediaSourceInfo i in mediaSources)
  66. {
  67. StreamInfo streamInfo = BuildVideoItem(i, options);
  68. if (streamInfo != null)
  69. {
  70. streams.Add(streamInfo);
  71. }
  72. }
  73. foreach (StreamInfo stream in streams)
  74. {
  75. stream.DeviceId = options.DeviceId;
  76. stream.DeviceProfileId = options.Profile.Id;
  77. }
  78. return GetOptimalStream(streams, options.GetMaxBitrate());
  79. }
  80. private StreamInfo GetOptimalStream(List<StreamInfo> streams, int? maxBitrate)
  81. {
  82. streams = StreamInfoSorter.SortMediaSources(streams, maxBitrate);
  83. foreach (StreamInfo stream in streams)
  84. {
  85. return stream;
  86. }
  87. return null;
  88. }
  89. private StreamInfo BuildAudioItem(MediaSourceInfo item, AudioOptions options)
  90. {
  91. StreamInfo playlistItem = new StreamInfo
  92. {
  93. ItemId = options.ItemId,
  94. MediaType = DlnaProfileType.Audio,
  95. MediaSource = item,
  96. RunTimeTicks = item.RunTimeTicks,
  97. Context = options.Context,
  98. DeviceProfile = options.Profile
  99. };
  100. if (options.ForceDirectPlay)
  101. {
  102. playlistItem.PlayMethod = PlayMethod.DirectPlay;
  103. playlistItem.Container = item.Container;
  104. return playlistItem;
  105. }
  106. if (options.ForceDirectStream)
  107. {
  108. playlistItem.PlayMethod = PlayMethod.DirectStream;
  109. playlistItem.Container = item.Container;
  110. return playlistItem;
  111. }
  112. MediaStream audioStream = item.GetDefaultAudioStream(null);
  113. List<PlayMethod> directPlayMethods = GetAudioDirectPlayMethods(item, audioStream, options);
  114. ConditionProcessor conditionProcessor = new ConditionProcessor();
  115. int? inputAudioChannels = audioStream == null ? null : audioStream.Channels;
  116. int? inputAudioBitrate = audioStream == null ? null : audioStream.BitDepth;
  117. if (directPlayMethods.Count > 0)
  118. {
  119. string audioCodec = audioStream == null ? null : audioStream.Codec;
  120. // Make sure audio codec profiles are satisfied
  121. if (!string.IsNullOrEmpty(audioCodec))
  122. {
  123. List<ProfileCondition> conditions = new List<ProfileCondition>();
  124. foreach (CodecProfile i in options.Profile.CodecProfiles)
  125. {
  126. if (i.Type == CodecType.Audio && i.ContainsCodec(audioCodec, item.Container))
  127. {
  128. bool applyConditions = true;
  129. foreach (ProfileCondition applyCondition in i.ApplyConditions)
  130. {
  131. if (!conditionProcessor.IsAudioConditionSatisfied(applyCondition, inputAudioChannels, inputAudioBitrate))
  132. {
  133. LogConditionFailure(options.Profile, "AudioCodecProfile", applyCondition, item);
  134. applyConditions = false;
  135. break;
  136. }
  137. }
  138. if (applyConditions)
  139. {
  140. foreach (ProfileCondition c in i.Conditions)
  141. {
  142. conditions.Add(c);
  143. }
  144. }
  145. }
  146. }
  147. bool all = true;
  148. foreach (ProfileCondition c in conditions)
  149. {
  150. if (!conditionProcessor.IsAudioConditionSatisfied(c, inputAudioChannels, inputAudioBitrate))
  151. {
  152. LogConditionFailure(options.Profile, "AudioCodecProfile", c, item);
  153. all = false;
  154. break;
  155. }
  156. }
  157. if (all)
  158. {
  159. if (directPlayMethods.Contains(PlayMethod.DirectStream))
  160. {
  161. playlistItem.PlayMethod = PlayMethod.DirectStream;
  162. }
  163. playlistItem.Container = item.Container;
  164. return playlistItem;
  165. }
  166. }
  167. }
  168. TranscodingProfile transcodingProfile = null;
  169. foreach (TranscodingProfile i in options.Profile.TranscodingProfiles)
  170. {
  171. if (i.Type == playlistItem.MediaType && i.Context == options.Context)
  172. {
  173. if (_transcoderSupport.CanEncodeToAudioCodec(i.AudioCodec ?? i.Container))
  174. {
  175. transcodingProfile = i;
  176. break;
  177. }
  178. }
  179. }
  180. if (transcodingProfile != null)
  181. {
  182. if (!item.SupportsTranscoding)
  183. {
  184. return null;
  185. }
  186. playlistItem.PlayMethod = PlayMethod.Transcode;
  187. playlistItem.TranscodeSeekInfo = transcodingProfile.TranscodeSeekInfo;
  188. playlistItem.EstimateContentLength = transcodingProfile.EstimateContentLength;
  189. playlistItem.Container = transcodingProfile.Container;
  190. if (string.IsNullOrEmpty(transcodingProfile.AudioCodec))
  191. {
  192. playlistItem.AudioCodecs = new string[] { };
  193. }
  194. else
  195. {
  196. playlistItem.AudioCodecs = transcodingProfile.AudioCodec.Split(',');
  197. }
  198. playlistItem.SubProtocol = transcodingProfile.Protocol;
  199. List<CodecProfile> audioCodecProfiles = new List<CodecProfile>();
  200. foreach (CodecProfile i in options.Profile.CodecProfiles)
  201. {
  202. if (i.Type == CodecType.Audio && i.ContainsCodec(transcodingProfile.AudioCodec, transcodingProfile.Container))
  203. {
  204. audioCodecProfiles.Add(i);
  205. }
  206. if (audioCodecProfiles.Count >= 1) break;
  207. }
  208. List<ProfileCondition> audioTranscodingConditions = new List<ProfileCondition>();
  209. foreach (CodecProfile i in audioCodecProfiles)
  210. {
  211. bool applyConditions = true;
  212. foreach (ProfileCondition applyCondition in i.ApplyConditions)
  213. {
  214. if (!conditionProcessor.IsAudioConditionSatisfied(applyCondition, inputAudioChannels, inputAudioBitrate))
  215. {
  216. LogConditionFailure(options.Profile, "AudioCodecProfile", applyCondition, item);
  217. applyConditions = false;
  218. break;
  219. }
  220. }
  221. if (applyConditions)
  222. {
  223. foreach (ProfileCondition c in i.Conditions)
  224. {
  225. audioTranscodingConditions.Add(c);
  226. }
  227. }
  228. }
  229. ApplyTranscodingConditions(playlistItem, audioTranscodingConditions);
  230. // Honor requested max channels
  231. if (options.MaxAudioChannels.HasValue)
  232. {
  233. int currentValue = playlistItem.MaxAudioChannels ?? options.MaxAudioChannels.Value;
  234. playlistItem.MaxAudioChannels = Math.Min(options.MaxAudioChannels.Value, currentValue);
  235. }
  236. int configuredBitrate = options.AudioTranscodingBitrate ??
  237. (options.Context == EncodingContext.Static ? options.Profile.MusicSyncBitrate : options.Profile.MusicStreamingTranscodingBitrate) ??
  238. 128000;
  239. playlistItem.AudioBitrate = Math.Min(configuredBitrate, playlistItem.AudioBitrate ?? configuredBitrate);
  240. }
  241. return playlistItem;
  242. }
  243. private int? GetBitrateForDirectPlayCheck(MediaSourceInfo item, AudioOptions options)
  244. {
  245. if (item.Protocol == MediaProtocol.File)
  246. {
  247. return options.Profile.MaxStaticBitrate;
  248. }
  249. return options.GetMaxBitrate();
  250. }
  251. private List<PlayMethod> GetAudioDirectPlayMethods(MediaSourceInfo item, MediaStream audioStream, AudioOptions options)
  252. {
  253. DirectPlayProfile directPlayProfile = null;
  254. foreach (DirectPlayProfile i in options.Profile.DirectPlayProfiles)
  255. {
  256. if (i.Type == DlnaProfileType.Audio && IsAudioDirectPlaySupported(i, item, audioStream))
  257. {
  258. directPlayProfile = i;
  259. break;
  260. }
  261. }
  262. List<PlayMethod> playMethods = new List<PlayMethod>();
  263. if (directPlayProfile != null)
  264. {
  265. // While options takes the network and other factors into account. Only applies to direct stream
  266. if (item.SupportsDirectStream && IsAudioEligibleForDirectPlay(item, options.GetMaxBitrate()) && options.EnableDirectStream)
  267. {
  268. playMethods.Add(PlayMethod.DirectStream);
  269. }
  270. // The profile describes what the device supports
  271. // If device requirements are satisfied then allow both direct stream and direct play
  272. if (item.SupportsDirectPlay &&
  273. IsAudioEligibleForDirectPlay(item, GetBitrateForDirectPlayCheck(item, options)) && options.EnableDirectPlay)
  274. {
  275. playMethods.Add(PlayMethod.DirectPlay);
  276. }
  277. }
  278. else
  279. {
  280. _logger.Info("Profile: {0}, No direct play profiles found for Path: {1}",
  281. options.Profile.Name ?? "Unknown Profile",
  282. item.Path ?? "Unknown path");
  283. }
  284. return playMethods;
  285. }
  286. private int? GetDefaultSubtitleStreamIndex(MediaSourceInfo item, SubtitleProfile[] subtitleProfiles)
  287. {
  288. int highestScore = -1;
  289. foreach (MediaStream stream in item.MediaStreams)
  290. {
  291. if (stream.Type == MediaStreamType.Subtitle && stream.Score.HasValue)
  292. {
  293. if (stream.Score.Value > highestScore)
  294. {
  295. highestScore = stream.Score.Value;
  296. }
  297. }
  298. }
  299. List<MediaStream> topStreams = new List<MediaStream>();
  300. foreach (MediaStream stream in item.MediaStreams)
  301. {
  302. if (stream.Type == MediaStreamType.Subtitle && stream.Score.HasValue && stream.Score.Value == highestScore)
  303. {
  304. topStreams.Add(stream);
  305. }
  306. }
  307. // If multiple streams have an equal score, try to pick the most efficient one
  308. if (topStreams.Count > 1)
  309. {
  310. foreach (MediaStream stream in topStreams)
  311. {
  312. foreach (SubtitleProfile profile in subtitleProfiles)
  313. {
  314. if (profile.Method == SubtitleDeliveryMethod.External && StringHelper.EqualsIgnoreCase(profile.Format, stream.Codec))
  315. {
  316. return stream.Index;
  317. }
  318. }
  319. }
  320. }
  321. // If no optimization panned out, just use the original default
  322. return item.DefaultSubtitleStreamIndex;
  323. }
  324. private StreamInfo BuildVideoItem(MediaSourceInfo item, VideoOptions options)
  325. {
  326. StreamInfo playlistItem = new StreamInfo
  327. {
  328. ItemId = options.ItemId,
  329. MediaType = DlnaProfileType.Video,
  330. MediaSource = item,
  331. RunTimeTicks = item.RunTimeTicks,
  332. Context = options.Context,
  333. DeviceProfile = options.Profile
  334. };
  335. playlistItem.SubtitleStreamIndex = options.SubtitleStreamIndex ?? GetDefaultSubtitleStreamIndex(item, options.Profile.SubtitleProfiles);
  336. MediaStream subtitleStream = playlistItem.SubtitleStreamIndex.HasValue ? item.GetMediaStream(MediaStreamType.Subtitle, playlistItem.SubtitleStreamIndex.Value) : null;
  337. MediaStream audioStream = item.GetDefaultAudioStream(options.AudioStreamIndex ?? item.DefaultAudioStreamIndex);
  338. int? audioStreamIndex = null;
  339. if (audioStream != null)
  340. {
  341. audioStreamIndex = audioStream.Index;
  342. }
  343. MediaStream videoStream = item.VideoStream;
  344. // TODO: This doesn't accout for situation of device being able to handle media bitrate, but wifi connection not fast enough
  345. bool isEligibleForDirectPlay = options.EnableDirectPlay && (options.ForceDirectPlay || IsEligibleForDirectPlay(item, GetBitrateForDirectPlayCheck(item, options), subtitleStream, options, PlayMethod.DirectPlay));
  346. bool isEligibleForDirectStream = options.EnableDirectStream && (options.ForceDirectStream || IsEligibleForDirectPlay(item, options.GetMaxBitrate(), subtitleStream, options, PlayMethod.DirectStream));
  347. _logger.Info("Profile: {0}, Path: {1}, isEligibleForDirectPlay: {2}, isEligibleForDirectStream: {3}",
  348. options.Profile.Name ?? "Unknown Profile",
  349. item.Path ?? "Unknown path",
  350. isEligibleForDirectPlay,
  351. isEligibleForDirectStream);
  352. if (isEligibleForDirectPlay || isEligibleForDirectStream)
  353. {
  354. // See if it can be direct played
  355. PlayMethod? directPlay = GetVideoDirectPlayProfile(options, item, videoStream, audioStream, isEligibleForDirectPlay, isEligibleForDirectStream);
  356. if (directPlay != null)
  357. {
  358. playlistItem.PlayMethod = directPlay.Value;
  359. playlistItem.Container = item.Container;
  360. if (subtitleStream != null)
  361. {
  362. SubtitleProfile subtitleProfile = GetSubtitleProfile(subtitleStream, options.Profile.SubtitleProfiles, directPlay.Value);
  363. playlistItem.SubtitleDeliveryMethod = subtitleProfile.Method;
  364. playlistItem.SubtitleFormat = subtitleProfile.Format;
  365. }
  366. return playlistItem;
  367. }
  368. }
  369. // Can't direct play, find the transcoding profile
  370. TranscodingProfile transcodingProfile = null;
  371. foreach (TranscodingProfile i in options.Profile.TranscodingProfiles)
  372. {
  373. if (i.Type == playlistItem.MediaType && i.Context == options.Context)
  374. {
  375. transcodingProfile = i;
  376. break;
  377. }
  378. }
  379. if (transcodingProfile != null)
  380. {
  381. if (!item.SupportsTranscoding)
  382. {
  383. return null;
  384. }
  385. if (subtitleStream != null)
  386. {
  387. SubtitleProfile subtitleProfile = GetSubtitleProfile(subtitleStream, options.Profile.SubtitleProfiles, PlayMethod.Transcode);
  388. playlistItem.SubtitleDeliveryMethod = subtitleProfile.Method;
  389. playlistItem.SubtitleFormat = subtitleProfile.Format;
  390. }
  391. playlistItem.PlayMethod = PlayMethod.Transcode;
  392. playlistItem.Container = transcodingProfile.Container;
  393. playlistItem.EstimateContentLength = transcodingProfile.EstimateContentLength;
  394. playlistItem.TranscodeSeekInfo = transcodingProfile.TranscodeSeekInfo;
  395. playlistItem.AudioCodecs = transcodingProfile.AudioCodec.Split(',');
  396. playlistItem.VideoCodec = transcodingProfile.VideoCodec;
  397. playlistItem.CopyTimestamps = transcodingProfile.CopyTimestamps;
  398. playlistItem.ForceLiveStream = transcodingProfile.ForceLiveStream;
  399. playlistItem.EnableSubtitlesInManifest = transcodingProfile.EnableSubtitlesInManifest;
  400. if (!string.IsNullOrEmpty(transcodingProfile.MaxAudioChannels))
  401. {
  402. int transcodingMaxAudioChannels;
  403. if (IntHelper.TryParseCultureInvariant(transcodingProfile.MaxAudioChannels, out transcodingMaxAudioChannels))
  404. {
  405. playlistItem.TranscodingMaxAudioChannels = transcodingMaxAudioChannels;
  406. }
  407. }
  408. playlistItem.SubProtocol = transcodingProfile.Protocol;
  409. playlistItem.AudioStreamIndex = audioStreamIndex;
  410. ConditionProcessor conditionProcessor = new ConditionProcessor();
  411. List<ProfileCondition> videoTranscodingConditions = new List<ProfileCondition>();
  412. foreach (CodecProfile i in options.Profile.CodecProfiles)
  413. {
  414. if (i.Type == CodecType.Video && i.ContainsCodec(transcodingProfile.VideoCodec, transcodingProfile.Container))
  415. {
  416. bool applyConditions = true;
  417. foreach (ProfileCondition applyCondition in i.ApplyConditions)
  418. {
  419. bool? isSecondaryAudio = audioStream == null ? null : item.IsSecondaryAudio(audioStream);
  420. int? inputAudioBitrate = audioStream == null ? null : audioStream.BitRate;
  421. int? audioChannels = audioStream == null ? null : audioStream.Channels;
  422. string audioProfile = audioStream == null ? null : audioStream.Profile;
  423. if (!conditionProcessor.IsVideoAudioConditionSatisfied(applyCondition, audioChannels, inputAudioBitrate, audioProfile, isSecondaryAudio))
  424. {
  425. LogConditionFailure(options.Profile, "AudioCodecProfile", applyCondition, item);
  426. applyConditions = false;
  427. break;
  428. }
  429. }
  430. if (applyConditions)
  431. {
  432. foreach (ProfileCondition c in i.Conditions)
  433. {
  434. videoTranscodingConditions.Add(c);
  435. }
  436. break;
  437. }
  438. }
  439. }
  440. ApplyTranscodingConditions(playlistItem, videoTranscodingConditions);
  441. List<ProfileCondition> audioTranscodingConditions = new List<ProfileCondition>();
  442. foreach (CodecProfile i in options.Profile.CodecProfiles)
  443. {
  444. if (i.Type == CodecType.VideoAudio && i.ContainsCodec(playlistItem.TargetAudioCodec, transcodingProfile.Container))
  445. {
  446. bool applyConditions = true;
  447. foreach (ProfileCondition applyCondition in i.ApplyConditions)
  448. {
  449. int? width = videoStream == null ? null : videoStream.Width;
  450. int? height = videoStream == null ? null : videoStream.Height;
  451. int? bitDepth = videoStream == null ? null : videoStream.BitDepth;
  452. int? videoBitrate = videoStream == null ? null : videoStream.BitRate;
  453. double? videoLevel = videoStream == null ? null : videoStream.Level;
  454. string videoProfile = videoStream == null ? null : videoStream.Profile;
  455. float? videoFramerate = videoStream == null ? null : videoStream.AverageFrameRate ?? videoStream.AverageFrameRate;
  456. bool? isAnamorphic = videoStream == null ? null : videoStream.IsAnamorphic;
  457. string videoCodecTag = videoStream == null ? null : videoStream.CodecTag;
  458. TransportStreamTimestamp? timestamp = videoStream == null ? TransportStreamTimestamp.None : item.Timestamp;
  459. int? packetLength = videoStream == null ? null : videoStream.PacketLength;
  460. int? refFrames = videoStream == null ? null : videoStream.RefFrames;
  461. int? numAudioStreams = item.GetStreamCount(MediaStreamType.Audio);
  462. int? numVideoStreams = item.GetStreamCount(MediaStreamType.Video);
  463. if (!conditionProcessor.IsVideoConditionSatisfied(applyCondition, width, height, bitDepth, videoBitrate, videoProfile, videoLevel, videoFramerate, packetLength, timestamp, isAnamorphic, refFrames, numVideoStreams, numAudioStreams, videoCodecTag))
  464. {
  465. LogConditionFailure(options.Profile, "VideoCodecProfile", applyCondition, item);
  466. applyConditions = false;
  467. break;
  468. }
  469. }
  470. if (applyConditions)
  471. {
  472. foreach (ProfileCondition c in i.Conditions)
  473. {
  474. audioTranscodingConditions.Add(c);
  475. }
  476. break;
  477. }
  478. }
  479. }
  480. ApplyTranscodingConditions(playlistItem, audioTranscodingConditions);
  481. // Honor requested max channels
  482. if (options.MaxAudioChannels.HasValue)
  483. {
  484. int currentValue = playlistItem.MaxAudioChannels ?? options.MaxAudioChannels.Value;
  485. playlistItem.MaxAudioChannels = Math.Min(options.MaxAudioChannels.Value, currentValue);
  486. }
  487. int audioBitrate = GetAudioBitrate(options.GetMaxBitrate(), playlistItem.TargetAudioChannels, playlistItem.TargetAudioCodec, audioStream);
  488. playlistItem.AudioBitrate = Math.Min(playlistItem.AudioBitrate ?? audioBitrate, audioBitrate);
  489. int? maxBitrateSetting = options.GetMaxBitrate();
  490. // Honor max rate
  491. if (maxBitrateSetting.HasValue)
  492. {
  493. int videoBitrate = maxBitrateSetting.Value;
  494. if (playlistItem.AudioBitrate.HasValue)
  495. {
  496. videoBitrate -= playlistItem.AudioBitrate.Value;
  497. }
  498. // Make sure the video bitrate is lower than bitrate settings but at least 64k
  499. int currentValue = playlistItem.VideoBitrate ?? videoBitrate;
  500. playlistItem.VideoBitrate = Math.Max(Math.Min(videoBitrate, currentValue), 64000);
  501. }
  502. }
  503. return playlistItem;
  504. }
  505. private int GetAudioBitrate(int? maxTotalBitrate, int? targetAudioChannels, string targetAudioCodec, MediaStream audioStream)
  506. {
  507. var defaultBitrate = 128000;
  508. if (StringHelper.EqualsIgnoreCase(targetAudioCodec, "ac3"))
  509. {
  510. defaultBitrate = 192000;
  511. }
  512. if (!string.IsNullOrEmpty(targetAudioCodec) && audioStream != null && StringHelper.EqualsIgnoreCase(audioStream.Codec, targetAudioCodec))
  513. {
  514. defaultBitrate = audioStream.BitRate ?? defaultBitrate;
  515. }
  516. if (targetAudioChannels.HasValue)
  517. {
  518. if (targetAudioChannels.Value >= 5 && (maxTotalBitrate ?? 0) >= 1500000)
  519. {
  520. if (StringHelper.EqualsIgnoreCase(targetAudioCodec, "ac3"))
  521. {
  522. defaultBitrate = Math.Max(448000, defaultBitrate);
  523. }
  524. else
  525. {
  526. defaultBitrate = Math.Max(320000, defaultBitrate);
  527. }
  528. }
  529. }
  530. int encoderAudioBitrateLimit = int.MaxValue;
  531. if (audioStream != null)
  532. {
  533. // Seeing webm encoding failures when source has 1 audio channel and 22k bitrate.
  534. // Any attempts to transcode over 64k will fail
  535. if (audioStream.Channels.HasValue &&
  536. audioStream.Channels.Value == 1)
  537. {
  538. if ((audioStream.BitRate ?? 0) < 64000)
  539. {
  540. encoderAudioBitrateLimit = 64000;
  541. }
  542. }
  543. }
  544. return Math.Min(defaultBitrate, encoderAudioBitrateLimit);
  545. }
  546. private PlayMethod? GetVideoDirectPlayProfile(VideoOptions options,
  547. MediaSourceInfo mediaSource,
  548. MediaStream videoStream,
  549. MediaStream audioStream,
  550. bool isEligibleForDirectPlay,
  551. bool isEligibleForDirectStream)
  552. {
  553. DeviceProfile profile = options.Profile;
  554. if (options.ForceDirectPlay)
  555. {
  556. return PlayMethod.DirectPlay;
  557. }
  558. if (options.ForceDirectStream)
  559. {
  560. return PlayMethod.DirectStream;
  561. }
  562. if (videoStream == null)
  563. {
  564. _logger.Info("Profile: {0}, Cannot direct stream with no known video stream. Path: {1}",
  565. profile.Name ?? "Unknown Profile",
  566. mediaSource.Path ?? "Unknown path");
  567. return null;
  568. }
  569. // See if it can be direct played
  570. DirectPlayProfile directPlay = null;
  571. foreach (DirectPlayProfile i in profile.DirectPlayProfiles)
  572. {
  573. if (i.Type == DlnaProfileType.Video && IsVideoDirectPlaySupported(i, mediaSource, videoStream, audioStream))
  574. {
  575. directPlay = i;
  576. break;
  577. }
  578. }
  579. if (directPlay == null)
  580. {
  581. _logger.Info("Profile: {0}, No direct play profiles found for Path: {1}",
  582. profile.Name ?? "Unknown Profile",
  583. mediaSource.Path ?? "Unknown path");
  584. return null;
  585. }
  586. string container = mediaSource.Container;
  587. List<ProfileCondition> conditions = new List<ProfileCondition>();
  588. foreach (ContainerProfile i in profile.ContainerProfiles)
  589. {
  590. if (i.Type == DlnaProfileType.Video &&
  591. ListHelper.ContainsIgnoreCase(i.GetContainers(), container))
  592. {
  593. foreach (ProfileCondition c in i.Conditions)
  594. {
  595. conditions.Add(c);
  596. }
  597. }
  598. }
  599. ConditionProcessor conditionProcessor = new ConditionProcessor();
  600. int? width = videoStream == null ? null : videoStream.Width;
  601. int? height = videoStream == null ? null : videoStream.Height;
  602. int? bitDepth = videoStream == null ? null : videoStream.BitDepth;
  603. int? videoBitrate = videoStream == null ? null : videoStream.BitRate;
  604. double? videoLevel = videoStream == null ? null : videoStream.Level;
  605. string videoProfile = videoStream == null ? null : videoStream.Profile;
  606. float? videoFramerate = videoStream == null ? null : videoStream.AverageFrameRate ?? videoStream.AverageFrameRate;
  607. bool? isAnamorphic = videoStream == null ? null : videoStream.IsAnamorphic;
  608. string videoCodecTag = videoStream == null ? null : videoStream.CodecTag;
  609. int? audioBitrate = audioStream == null ? null : audioStream.BitRate;
  610. int? audioChannels = audioStream == null ? null : audioStream.Channels;
  611. string audioProfile = audioStream == null ? null : audioStream.Profile;
  612. TransportStreamTimestamp? timestamp = videoStream == null ? TransportStreamTimestamp.None : mediaSource.Timestamp;
  613. int? packetLength = videoStream == null ? null : videoStream.PacketLength;
  614. int? refFrames = videoStream == null ? null : videoStream.RefFrames;
  615. int? numAudioStreams = mediaSource.GetStreamCount(MediaStreamType.Audio);
  616. int? numVideoStreams = mediaSource.GetStreamCount(MediaStreamType.Video);
  617. // Check container conditions
  618. foreach (ProfileCondition i in conditions)
  619. {
  620. if (!conditionProcessor.IsVideoConditionSatisfied(i, width, height, bitDepth, videoBitrate, videoProfile, videoLevel, videoFramerate, packetLength, timestamp, isAnamorphic, refFrames, numVideoStreams, numAudioStreams, videoCodecTag))
  621. {
  622. LogConditionFailure(profile, "VideoContainerProfile", i, mediaSource);
  623. return null;
  624. }
  625. }
  626. string videoCodec = videoStream == null ? null : videoStream.Codec;
  627. if (string.IsNullOrEmpty(videoCodec))
  628. {
  629. _logger.Info("Profile: {0}, DirectPlay=false. Reason=Unknown video codec. Path: {1}",
  630. profile.Name ?? "Unknown Profile",
  631. mediaSource.Path ?? "Unknown path");
  632. return null;
  633. }
  634. conditions = new List<ProfileCondition>();
  635. foreach (CodecProfile i in profile.CodecProfiles)
  636. {
  637. if (i.Type == CodecType.Video && i.ContainsCodec(videoCodec, container))
  638. {
  639. bool applyConditions = true;
  640. foreach (ProfileCondition applyCondition in i.ApplyConditions)
  641. {
  642. if (!conditionProcessor.IsVideoConditionSatisfied(applyCondition, width, height, bitDepth, videoBitrate, videoProfile, videoLevel, videoFramerate, packetLength, timestamp, isAnamorphic, refFrames, numVideoStreams, numAudioStreams, videoCodecTag))
  643. {
  644. LogConditionFailure(profile, "VideoCodecProfile", applyCondition, mediaSource);
  645. applyConditions = false;
  646. break;
  647. }
  648. }
  649. if (applyConditions)
  650. {
  651. foreach (ProfileCondition c in i.Conditions)
  652. {
  653. conditions.Add(c);
  654. }
  655. }
  656. }
  657. }
  658. foreach (ProfileCondition i in conditions)
  659. {
  660. if (!conditionProcessor.IsVideoConditionSatisfied(i, width, height, bitDepth, videoBitrate, videoProfile, videoLevel, videoFramerate, packetLength, timestamp, isAnamorphic, refFrames, numVideoStreams, numAudioStreams, videoCodecTag))
  661. {
  662. LogConditionFailure(profile, "VideoCodecProfile", i, mediaSource);
  663. return null;
  664. }
  665. }
  666. if (audioStream != null)
  667. {
  668. string audioCodec = audioStream.Codec;
  669. if (string.IsNullOrEmpty(audioCodec))
  670. {
  671. _logger.Info("Profile: {0}, DirectPlay=false. Reason=Unknown audio codec. Path: {1}",
  672. profile.Name ?? "Unknown Profile",
  673. mediaSource.Path ?? "Unknown path");
  674. return null;
  675. }
  676. conditions = new List<ProfileCondition>();
  677. bool? isSecondaryAudio = audioStream == null ? null : mediaSource.IsSecondaryAudio(audioStream);
  678. foreach (CodecProfile i in profile.CodecProfiles)
  679. {
  680. if (i.Type == CodecType.VideoAudio && i.ContainsCodec(audioCodec, container))
  681. {
  682. bool applyConditions = true;
  683. foreach (ProfileCondition applyCondition in i.ApplyConditions)
  684. {
  685. if (!conditionProcessor.IsVideoAudioConditionSatisfied(applyCondition, audioChannels, audioBitrate, audioProfile, isSecondaryAudio))
  686. {
  687. LogConditionFailure(profile, "VideoAudioCodecProfile", applyCondition, mediaSource);
  688. applyConditions = false;
  689. break;
  690. }
  691. }
  692. if (applyConditions)
  693. {
  694. foreach (ProfileCondition c in i.Conditions)
  695. {
  696. conditions.Add(c);
  697. }
  698. }
  699. }
  700. }
  701. foreach (ProfileCondition i in conditions)
  702. {
  703. if (!conditionProcessor.IsVideoAudioConditionSatisfied(i, audioChannels, audioBitrate, audioProfile, isSecondaryAudio))
  704. {
  705. LogConditionFailure(profile, "VideoAudioCodecProfile", i, mediaSource);
  706. return null;
  707. }
  708. }
  709. }
  710. if (isEligibleForDirectStream && mediaSource.SupportsDirectStream)
  711. {
  712. return PlayMethod.DirectStream;
  713. }
  714. return null;
  715. }
  716. private void LogConditionFailure(DeviceProfile profile, string type, ProfileCondition condition, MediaSourceInfo mediaSource)
  717. {
  718. _logger.Info("Profile: {0}, DirectPlay=false. Reason={1}.{2} Condition: {3}. ConditionValue: {4}. IsRequired: {5}. Path: {6}",
  719. type,
  720. profile.Name ?? "Unknown Profile",
  721. condition.Property,
  722. condition.Condition,
  723. condition.Value ?? string.Empty,
  724. condition.IsRequired,
  725. mediaSource.Path ?? "Unknown path");
  726. }
  727. private bool IsEligibleForDirectPlay(MediaSourceInfo item,
  728. int? maxBitrate,
  729. MediaStream subtitleStream,
  730. VideoOptions options,
  731. PlayMethod playMethod)
  732. {
  733. if (subtitleStream != null)
  734. {
  735. SubtitleProfile subtitleProfile = GetSubtitleProfile(subtitleStream, options.Profile.SubtitleProfiles, playMethod);
  736. if (subtitleProfile.Method != SubtitleDeliveryMethod.External && subtitleProfile.Method != SubtitleDeliveryMethod.Embed)
  737. {
  738. _logger.Info("Not eligible for {0} due to unsupported subtitles", playMethod);
  739. return false;
  740. }
  741. }
  742. return IsAudioEligibleForDirectPlay(item, maxBitrate);
  743. }
  744. public static SubtitleProfile GetSubtitleProfile(MediaStream subtitleStream, SubtitleProfile[] subtitleProfiles, PlayMethod playMethod)
  745. {
  746. if (playMethod != PlayMethod.Transcode && !subtitleStream.IsExternal)
  747. {
  748. // Look for supported embedded subs
  749. foreach (SubtitleProfile profile in subtitleProfiles)
  750. {
  751. if (!profile.SupportsLanguage(subtitleStream.Language))
  752. {
  753. continue;
  754. }
  755. if (profile.Method != SubtitleDeliveryMethod.Embed)
  756. {
  757. continue;
  758. }
  759. if (subtitleStream.IsTextSubtitleStream == MediaStream.IsTextFormat(profile.Format) && StringHelper.EqualsIgnoreCase(profile.Format, subtitleStream.Codec))
  760. {
  761. return profile;
  762. }
  763. }
  764. }
  765. // Look for an external or hls profile that matches the stream type (text/graphical) and doesn't require conversion
  766. return GetExternalSubtitleProfile(subtitleStream, subtitleProfiles, playMethod, false) ?? GetExternalSubtitleProfile(subtitleStream, subtitleProfiles, playMethod, true) ?? new SubtitleProfile
  767. {
  768. Method = SubtitleDeliveryMethod.Encode,
  769. Format = subtitleStream.Codec
  770. };
  771. }
  772. private static SubtitleProfile GetExternalSubtitleProfile(MediaStream subtitleStream, SubtitleProfile[] subtitleProfiles, PlayMethod playMethod, bool allowConversion)
  773. {
  774. foreach (SubtitleProfile profile in subtitleProfiles)
  775. {
  776. if (profile.Method != SubtitleDeliveryMethod.External && profile.Method != SubtitleDeliveryMethod.Hls)
  777. {
  778. continue;
  779. }
  780. if (profile.Method == SubtitleDeliveryMethod.Hls && playMethod != PlayMethod.Transcode)
  781. {
  782. continue;
  783. }
  784. if (!profile.SupportsLanguage(subtitleStream.Language))
  785. {
  786. continue;
  787. }
  788. if ((profile.Method == SubtitleDeliveryMethod.External && subtitleStream.IsTextSubtitleStream == MediaStream.IsTextFormat(profile.Format)) ||
  789. (profile.Method == SubtitleDeliveryMethod.Hls && subtitleStream.IsTextSubtitleStream))
  790. {
  791. bool requiresConversion = !StringHelper.EqualsIgnoreCase(subtitleStream.Codec, profile.Format);
  792. if (!requiresConversion)
  793. {
  794. return profile;
  795. }
  796. if (!allowConversion)
  797. {
  798. continue;
  799. }
  800. if (subtitleStream.IsTextSubtitleStream && subtitleStream.SupportsExternalStream && subtitleStream.SupportsSubtitleConversionTo(profile.Format))
  801. {
  802. return profile;
  803. }
  804. }
  805. }
  806. return null;
  807. }
  808. private bool IsAudioEligibleForDirectPlay(MediaSourceInfo item, int? maxBitrate)
  809. {
  810. if (!maxBitrate.HasValue)
  811. {
  812. _logger.Info("Cannot direct play due to unknown supported bitrate");
  813. return false;
  814. }
  815. if (!item.Bitrate.HasValue)
  816. {
  817. _logger.Info("Cannot direct play due to unknown content bitrate");
  818. return false;
  819. }
  820. if (item.Bitrate.Value > maxBitrate.Value)
  821. {
  822. _logger.Info("Bitrate exceeds DirectPlay limit");
  823. return false;
  824. }
  825. return true;
  826. }
  827. private void ValidateInput(VideoOptions options)
  828. {
  829. ValidateAudioInput(options);
  830. if (options.AudioStreamIndex.HasValue && string.IsNullOrEmpty(options.MediaSourceId))
  831. {
  832. throw new ArgumentException("MediaSourceId is required when a specific audio stream is requested");
  833. }
  834. if (options.SubtitleStreamIndex.HasValue && string.IsNullOrEmpty(options.MediaSourceId))
  835. {
  836. throw new ArgumentException("MediaSourceId is required when a specific subtitle stream is requested");
  837. }
  838. }
  839. private void ValidateAudioInput(AudioOptions options)
  840. {
  841. if (string.IsNullOrEmpty(options.ItemId))
  842. {
  843. throw new ArgumentException("ItemId is required");
  844. }
  845. if (string.IsNullOrEmpty(options.DeviceId))
  846. {
  847. throw new ArgumentException("DeviceId is required");
  848. }
  849. if (options.Profile == null)
  850. {
  851. throw new ArgumentException("Profile is required");
  852. }
  853. if (options.MediaSources == null)
  854. {
  855. throw new ArgumentException("MediaSources is required");
  856. }
  857. }
  858. private void ApplyTranscodingConditions(StreamInfo item, IEnumerable<ProfileCondition> conditions)
  859. {
  860. foreach (ProfileCondition condition in conditions)
  861. {
  862. string value = condition.Value;
  863. if (string.IsNullOrEmpty(value))
  864. {
  865. continue;
  866. }
  867. // No way to express this
  868. if (condition.Condition == ProfileConditionType.GreaterThanEqual)
  869. {
  870. continue;
  871. }
  872. switch (condition.Property)
  873. {
  874. case ProfileConditionValue.AudioBitrate:
  875. {
  876. int num;
  877. if (IntHelper.TryParseCultureInvariant(value, out num))
  878. {
  879. item.AudioBitrate = num;
  880. }
  881. break;
  882. }
  883. case ProfileConditionValue.AudioChannels:
  884. {
  885. int num;
  886. if (IntHelper.TryParseCultureInvariant(value, out num))
  887. {
  888. item.MaxAudioChannels = num;
  889. }
  890. break;
  891. }
  892. case ProfileConditionValue.IsAnamorphic:
  893. case ProfileConditionValue.AudioProfile:
  894. case ProfileConditionValue.Has64BitOffsets:
  895. case ProfileConditionValue.PacketLength:
  896. case ProfileConditionValue.NumAudioStreams:
  897. case ProfileConditionValue.NumVideoStreams:
  898. case ProfileConditionValue.IsSecondaryAudio:
  899. case ProfileConditionValue.VideoTimestamp:
  900. {
  901. // Not supported yet
  902. break;
  903. }
  904. case ProfileConditionValue.RefFrames:
  905. {
  906. int num;
  907. if (IntHelper.TryParseCultureInvariant(value, out num))
  908. {
  909. item.MaxRefFrames = num;
  910. }
  911. break;
  912. }
  913. case ProfileConditionValue.VideoBitDepth:
  914. {
  915. int num;
  916. if (IntHelper.TryParseCultureInvariant(value, out num))
  917. {
  918. item.MaxVideoBitDepth = num;
  919. }
  920. break;
  921. }
  922. case ProfileConditionValue.VideoProfile:
  923. {
  924. item.VideoProfile = (value ?? string.Empty).Split('|')[0];
  925. break;
  926. }
  927. case ProfileConditionValue.Height:
  928. {
  929. int num;
  930. if (IntHelper.TryParseCultureInvariant(value, out num))
  931. {
  932. item.MaxHeight = num;
  933. }
  934. break;
  935. }
  936. case ProfileConditionValue.VideoBitrate:
  937. {
  938. int num;
  939. if (IntHelper.TryParseCultureInvariant(value, out num))
  940. {
  941. item.VideoBitrate = num;
  942. }
  943. break;
  944. }
  945. case ProfileConditionValue.VideoFramerate:
  946. {
  947. float num;
  948. if (FloatHelper.TryParseCultureInvariant(value, out num))
  949. {
  950. item.MaxFramerate = num;
  951. }
  952. break;
  953. }
  954. case ProfileConditionValue.VideoLevel:
  955. {
  956. int num;
  957. if (IntHelper.TryParseCultureInvariant(value, out num))
  958. {
  959. item.VideoLevel = num;
  960. }
  961. break;
  962. }
  963. case ProfileConditionValue.Width:
  964. {
  965. int num;
  966. if (IntHelper.TryParseCultureInvariant(value, out num))
  967. {
  968. item.MaxWidth = num;
  969. }
  970. break;
  971. }
  972. }
  973. }
  974. }
  975. private bool IsAudioDirectPlaySupported(DirectPlayProfile profile, MediaSourceInfo item, MediaStream audioStream)
  976. {
  977. if (profile.Container.Length > 0)
  978. {
  979. // Check container type
  980. string mediaContainer = item.Container ?? string.Empty;
  981. bool any = false;
  982. foreach (string i in profile.GetContainers())
  983. {
  984. if (StringHelper.EqualsIgnoreCase(i, mediaContainer))
  985. {
  986. any = true;
  987. break;
  988. }
  989. }
  990. if (!any)
  991. {
  992. return false;
  993. }
  994. }
  995. // Check audio codec
  996. List<string> audioCodecs = profile.GetAudioCodecs();
  997. if (audioCodecs.Count > 0)
  998. {
  999. // Check audio codecs
  1000. string audioCodec = audioStream == null ? null : audioStream.Codec;
  1001. if (string.IsNullOrEmpty(audioCodec) || !ListHelper.ContainsIgnoreCase(audioCodecs, audioCodec))
  1002. {
  1003. return false;
  1004. }
  1005. }
  1006. return true;
  1007. }
  1008. private bool IsVideoDirectPlaySupported(DirectPlayProfile profile, MediaSourceInfo item, MediaStream videoStream, MediaStream audioStream)
  1009. {
  1010. if (profile.Container.Length > 0)
  1011. {
  1012. // Check container type
  1013. string mediaContainer = item.Container ?? string.Empty;
  1014. bool any = false;
  1015. foreach (string i in profile.GetContainers())
  1016. {
  1017. if (StringHelper.EqualsIgnoreCase(i, mediaContainer))
  1018. {
  1019. any = true;
  1020. break;
  1021. }
  1022. }
  1023. if (!any)
  1024. {
  1025. return false;
  1026. }
  1027. }
  1028. // Check video codec
  1029. List<string> videoCodecs = profile.GetVideoCodecs();
  1030. if (videoCodecs.Count > 0)
  1031. {
  1032. string videoCodec = videoStream == null ? null : videoStream.Codec;
  1033. if (string.IsNullOrEmpty(videoCodec) || !ListHelper.ContainsIgnoreCase(videoCodecs, videoCodec))
  1034. {
  1035. return false;
  1036. }
  1037. }
  1038. // Check audio codec
  1039. List<string> audioCodecs = profile.GetAudioCodecs();
  1040. if (audioCodecs.Count > 0)
  1041. {
  1042. // Check audio codecs
  1043. string audioCodec = audioStream == null ? null : audioStream.Codec;
  1044. if (string.IsNullOrEmpty(audioCodec) || !ListHelper.ContainsIgnoreCase(audioCodecs, audioCodec))
  1045. {
  1046. return false;
  1047. }
  1048. }
  1049. return true;
  1050. }
  1051. }
  1052. }