StreamBuilder.cs 50 KB

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