StreamBuilder.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. using MediaBrowser.Model.Dto;
  2. using MediaBrowser.Model.Entities;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. using System.Linq;
  7. namespace MediaBrowser.Model.Dlna
  8. {
  9. public class StreamBuilder
  10. {
  11. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  12. public StreamInfo BuildAudioItem(AudioOptions options)
  13. {
  14. ValidateAudioInput(options);
  15. var mediaSources = options.MediaSources;
  16. // If the client wants a specific media soure, filter now
  17. if (!string.IsNullOrEmpty(options.MediaSourceId))
  18. {
  19. // Avoid implicitly captured closure
  20. var mediaSourceId = options.MediaSourceId;
  21. mediaSources = mediaSources
  22. .Where(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase))
  23. .ToList();
  24. }
  25. var streams = mediaSources.Select(i => BuildAudioItem(i, options)).ToList();
  26. foreach (var stream in streams)
  27. {
  28. stream.DeviceId = options.DeviceId;
  29. stream.DeviceProfileId = options.Profile.Id;
  30. }
  31. return GetOptimalStream(streams);
  32. }
  33. public StreamInfo BuildVideoItem(VideoOptions options)
  34. {
  35. ValidateInput(options);
  36. var mediaSources = options.MediaSources;
  37. // If the client wants a specific media soure, filter now
  38. if (!string.IsNullOrEmpty(options.MediaSourceId))
  39. {
  40. // Avoid implicitly captured closure
  41. var mediaSourceId = options.MediaSourceId;
  42. mediaSources = mediaSources
  43. .Where(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase))
  44. .ToList();
  45. }
  46. var streams = mediaSources.Select(i => BuildVideoItem(i, options)).ToList();
  47. foreach (var stream in streams)
  48. {
  49. stream.DeviceId = options.DeviceId;
  50. stream.DeviceProfileId = options.Profile.Id;
  51. }
  52. return GetOptimalStream(streams);
  53. }
  54. private StreamInfo GetOptimalStream(List<StreamInfo> streams)
  55. {
  56. // Grab the first one that can be direct streamed
  57. // If that doesn't produce anything, just take the first
  58. return streams.FirstOrDefault(i => i.IsDirectStream) ??
  59. streams.FirstOrDefault();
  60. }
  61. private StreamInfo BuildAudioItem(MediaSourceInfo item, AudioOptions options)
  62. {
  63. var playlistItem = new StreamInfo
  64. {
  65. ItemId = options.ItemId,
  66. MediaType = DlnaProfileType.Audio,
  67. MediaSourceId = item.Id
  68. };
  69. var audioStream = item.MediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);
  70. // Honor the max bitrate setting
  71. if (IsAudioEligibleForDirectPlay(item, options))
  72. {
  73. var directPlay = options.Profile.DirectPlayProfiles
  74. .FirstOrDefault(i => i.Type == playlistItem.MediaType && IsAudioDirectPlaySupported(i, item, audioStream));
  75. if (directPlay != null)
  76. {
  77. var audioCodec = audioStream == null ? null : audioStream.Codec;
  78. // Make sure audio codec profiles are satisfied
  79. if (!string.IsNullOrEmpty(audioCodec) && options.Profile.CodecProfiles.Where(i => i.Type == CodecType.Audio && i.ContainsCodec(audioCodec))
  80. .All(i => AreConditionsSatisfied(i.Conditions, item.Path, null, audioStream)))
  81. {
  82. playlistItem.IsDirectStream = true;
  83. playlistItem.Container = item.Container;
  84. return playlistItem;
  85. }
  86. }
  87. }
  88. var transcodingProfile = options.Profile.TranscodingProfiles
  89. .FirstOrDefault(i => i.Type == playlistItem.MediaType);
  90. if (transcodingProfile != null)
  91. {
  92. playlistItem.IsDirectStream = false;
  93. playlistItem.Container = transcodingProfile.Container;
  94. playlistItem.AudioCodec = transcodingProfile.AudioCodec;
  95. var audioTranscodingConditions = options.Profile.CodecProfiles
  96. .Where(i => i.Type == CodecType.Audio && i.ContainsCodec(transcodingProfile.AudioCodec))
  97. .Take(1)
  98. .SelectMany(i => i.Conditions);
  99. ApplyTranscodingConditions(playlistItem, audioTranscodingConditions);
  100. // Honor requested max channels
  101. if (options.MaxAudioChannels.HasValue)
  102. {
  103. var currentValue = playlistItem.MaxAudioChannels ?? options.MaxAudioChannels.Value;
  104. playlistItem.MaxAudioChannels = Math.Min(options.MaxAudioChannels.Value, currentValue);
  105. }
  106. // Honor requested max bitrate
  107. if (options.MaxBitrate.HasValue)
  108. {
  109. var currentValue = playlistItem.AudioBitrate ?? options.MaxBitrate.Value;
  110. playlistItem.AudioBitrate = Math.Min(options.MaxBitrate.Value, currentValue);
  111. }
  112. }
  113. return playlistItem;
  114. }
  115. private StreamInfo BuildVideoItem(MediaSourceInfo item, VideoOptions options)
  116. {
  117. var playlistItem = new StreamInfo
  118. {
  119. ItemId = options.ItemId,
  120. MediaType = DlnaProfileType.Video,
  121. MediaSourceId = item.Id
  122. };
  123. var audioStream = item.MediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);
  124. var videoStream = item.MediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video);
  125. if (IsEligibleForDirectPlay(item, options))
  126. {
  127. // See if it can be direct played
  128. var directPlay = options.Profile.DirectPlayProfiles
  129. .FirstOrDefault(i => i.Type == playlistItem.MediaType && IsVideoDirectPlaySupported(i, item, videoStream, audioStream));
  130. if (directPlay != null)
  131. {
  132. var videoCodec = videoStream == null ? null : videoStream.Codec;
  133. // Make sure video codec profiles are satisfied
  134. if (!string.IsNullOrEmpty(videoCodec) && options.Profile.CodecProfiles.Where(i => i.Type == CodecType.Video && i.ContainsCodec(videoCodec))
  135. .All(i => AreConditionsSatisfied(i.Conditions, item.Path, videoStream, audioStream)))
  136. {
  137. var audioCodec = audioStream == null ? null : audioStream.Codec;
  138. // Make sure audio codec profiles are satisfied
  139. if (string.IsNullOrEmpty(audioCodec) || options.Profile.CodecProfiles.Where(i => i.Type == CodecType.VideoAudio && i.ContainsCodec(audioCodec))
  140. .All(i => AreConditionsSatisfied(i.Conditions, item.Path, videoStream, audioStream)))
  141. {
  142. playlistItem.IsDirectStream = true;
  143. playlistItem.Container = item.Container;
  144. return playlistItem;
  145. }
  146. }
  147. }
  148. }
  149. // Can't direct play, find the transcoding profile
  150. var transcodingProfile = options.Profile.TranscodingProfiles
  151. .FirstOrDefault(i => i.Type == playlistItem.MediaType);
  152. if (transcodingProfile != null)
  153. {
  154. playlistItem.IsDirectStream = false;
  155. playlistItem.Container = transcodingProfile.Container;
  156. playlistItem.AudioCodec = transcodingProfile.AudioCodec.Split(',').FirstOrDefault();
  157. playlistItem.VideoCodec = transcodingProfile.VideoCodec;
  158. var videoTranscodingConditions = options.Profile.CodecProfiles
  159. .Where(i => i.Type == CodecType.Video && i.ContainsCodec(transcodingProfile.VideoCodec))
  160. .Take(1)
  161. .SelectMany(i => i.Conditions);
  162. ApplyTranscodingConditions(playlistItem, videoTranscodingConditions);
  163. var audioTranscodingConditions = options.Profile.CodecProfiles
  164. .Where(i => i.Type == CodecType.VideoAudio && i.ContainsCodec(transcodingProfile.AudioCodec))
  165. .Take(1)
  166. .SelectMany(i => i.Conditions);
  167. ApplyTranscodingConditions(playlistItem, audioTranscodingConditions);
  168. // Honor requested max channels
  169. if (options.MaxAudioChannels.HasValue)
  170. {
  171. var currentValue = playlistItem.MaxAudioChannels ?? options.MaxAudioChannels.Value;
  172. playlistItem.MaxAudioChannels = Math.Min(options.MaxAudioChannels.Value, currentValue);
  173. }
  174. // Honor requested max bitrate
  175. if (options.MaxAudioTranscodingBitrate.HasValue)
  176. {
  177. var currentValue = playlistItem.AudioBitrate ?? options.MaxAudioTranscodingBitrate.Value;
  178. playlistItem.AudioBitrate = Math.Min(options.MaxAudioTranscodingBitrate.Value, currentValue);
  179. }
  180. // Honor max rate
  181. if (options.MaxBitrate.HasValue)
  182. {
  183. var videoBitrate = options.MaxBitrate.Value;
  184. if (playlistItem.AudioBitrate.HasValue)
  185. {
  186. videoBitrate -= playlistItem.AudioBitrate.Value;
  187. }
  188. var currentValue = playlistItem.VideoBitrate ?? videoBitrate;
  189. playlistItem.VideoBitrate = Math.Min(videoBitrate, currentValue);
  190. }
  191. }
  192. return playlistItem;
  193. }
  194. private bool IsEligibleForDirectPlay(MediaSourceInfo item, VideoOptions options)
  195. {
  196. if (options.SubtitleStreamIndex.HasValue)
  197. {
  198. return false;
  199. }
  200. if (options.AudioStreamIndex.HasValue &&
  201. item.MediaStreams.Count(i => i.Type == MediaStreamType.Audio) > 1)
  202. {
  203. return false;
  204. }
  205. return IsAudioEligibleForDirectPlay(item, options);
  206. }
  207. private bool IsAudioEligibleForDirectPlay(MediaSourceInfo item, AudioOptions options)
  208. {
  209. // Honor the max bitrate setting
  210. return !options.MaxBitrate.HasValue || (item.Bitrate.HasValue && item.Bitrate.Value <= options.MaxBitrate.Value);
  211. }
  212. private void ValidateInput(VideoOptions options)
  213. {
  214. ValidateAudioInput(options);
  215. if (options.AudioStreamIndex.HasValue && string.IsNullOrEmpty(options.MediaSourceId))
  216. {
  217. throw new ArgumentException("MediaSourceId is required when a specific audio stream is requested");
  218. }
  219. if (options.SubtitleStreamIndex.HasValue && string.IsNullOrEmpty(options.MediaSourceId))
  220. {
  221. throw new ArgumentException("MediaSourceId is required when a specific subtitle stream is requested");
  222. }
  223. }
  224. private void ValidateAudioInput(AudioOptions options)
  225. {
  226. if (string.IsNullOrEmpty(options.ItemId))
  227. {
  228. throw new ArgumentException("ItemId is required");
  229. }
  230. if (string.IsNullOrEmpty(options.DeviceId))
  231. {
  232. throw new ArgumentException("DeviceId is required");
  233. }
  234. if (options.Profile == null)
  235. {
  236. throw new ArgumentException("Profile is required");
  237. }
  238. if (options.MediaSources == null)
  239. {
  240. throw new ArgumentException("MediaSources is required");
  241. }
  242. }
  243. private void ApplyTranscodingConditions(StreamInfo item, IEnumerable<ProfileCondition> conditions)
  244. {
  245. foreach (var condition in conditions
  246. .Where(i => !string.IsNullOrEmpty(i.Value)))
  247. {
  248. var value = condition.Value;
  249. switch (condition.Property)
  250. {
  251. case ProfileConditionValue.AudioBitrate:
  252. {
  253. int num;
  254. if (int.TryParse(value, NumberStyles.Any, _usCulture, out num))
  255. {
  256. item.AudioBitrate = num;
  257. }
  258. break;
  259. }
  260. case ProfileConditionValue.AudioChannels:
  261. {
  262. int num;
  263. if (int.TryParse(value, NumberStyles.Any, _usCulture, out num))
  264. {
  265. item.MaxAudioChannels = num;
  266. }
  267. break;
  268. }
  269. case ProfileConditionValue.AudioProfile:
  270. case ProfileConditionValue.Has64BitOffsets:
  271. case ProfileConditionValue.VideoBitDepth:
  272. case ProfileConditionValue.VideoProfile:
  273. {
  274. // Not supported yet
  275. break;
  276. }
  277. case ProfileConditionValue.Height:
  278. {
  279. int num;
  280. if (int.TryParse(value, NumberStyles.Any, _usCulture, out num))
  281. {
  282. item.MaxHeight = num;
  283. }
  284. break;
  285. }
  286. case ProfileConditionValue.VideoBitrate:
  287. {
  288. int num;
  289. if (int.TryParse(value, NumberStyles.Any, _usCulture, out num))
  290. {
  291. item.VideoBitrate = num;
  292. }
  293. break;
  294. }
  295. case ProfileConditionValue.VideoFramerate:
  296. {
  297. int num;
  298. if (int.TryParse(value, NumberStyles.Any, _usCulture, out num))
  299. {
  300. item.MaxFramerate = num;
  301. }
  302. break;
  303. }
  304. case ProfileConditionValue.VideoLevel:
  305. {
  306. int num;
  307. if (int.TryParse(value, NumberStyles.Any, _usCulture, out num))
  308. {
  309. item.VideoLevel = num;
  310. }
  311. break;
  312. }
  313. case ProfileConditionValue.Width:
  314. {
  315. int num;
  316. if (int.TryParse(value, NumberStyles.Any, _usCulture, out num))
  317. {
  318. item.MaxWidth = num;
  319. }
  320. break;
  321. }
  322. default:
  323. throw new ArgumentException("Unrecognized ProfileConditionValue");
  324. }
  325. }
  326. }
  327. private bool IsAudioDirectPlaySupported(DirectPlayProfile profile, MediaSourceInfo item, MediaStream audioStream)
  328. {
  329. if (profile.Container.Length > 0)
  330. {
  331. // Check container type
  332. var mediaContainer = item.Container ?? string.Empty;
  333. if (!profile.GetContainers().Any(i => string.Equals(i, mediaContainer, StringComparison.OrdinalIgnoreCase)))
  334. {
  335. return false;
  336. }
  337. }
  338. return true;
  339. }
  340. private bool IsVideoDirectPlaySupported(DirectPlayProfile profile, MediaSourceInfo item, MediaStream videoStream, MediaStream audioStream)
  341. {
  342. // Only plain video files can be direct played
  343. if (item.VideoType != VideoType.VideoFile)
  344. {
  345. return false;
  346. }
  347. if (profile.Container.Length > 0)
  348. {
  349. // Check container type
  350. var mediaContainer = item.Container ?? string.Empty;
  351. if (!profile.GetContainers().Any(i => string.Equals(i, mediaContainer, StringComparison.OrdinalIgnoreCase)))
  352. {
  353. return false;
  354. }
  355. }
  356. // Check video codec
  357. var videoCodecs = profile.GetVideoCodecs();
  358. if (videoCodecs.Count > 0)
  359. {
  360. var videoCodec = videoStream == null ? null : videoStream.Codec;
  361. if (string.IsNullOrEmpty(videoCodec) || !videoCodecs.Contains(videoCodec, StringComparer.OrdinalIgnoreCase))
  362. {
  363. return false;
  364. }
  365. }
  366. var audioCodecs = profile.GetAudioCodecs();
  367. if (audioCodecs.Count > 0)
  368. {
  369. // Check audio codecs
  370. var audioCodec = audioStream == null ? null : audioStream.Codec;
  371. if (string.IsNullOrEmpty(audioCodec) || !audioCodecs.Contains(audioCodec, StringComparer.OrdinalIgnoreCase))
  372. {
  373. return false;
  374. }
  375. }
  376. return true;
  377. }
  378. private bool AreConditionsSatisfied(IEnumerable<ProfileCondition> conditions, string mediaPath, MediaStream videoStream, MediaStream audioStream)
  379. {
  380. return conditions.All(i => IsConditionSatisfied(i, mediaPath, videoStream, audioStream));
  381. }
  382. /// <summary>
  383. /// Determines whether [is condition satisfied] [the specified condition].
  384. /// </summary>
  385. /// <param name="condition">The condition.</param>
  386. /// <param name="mediaPath">The media path.</param>
  387. /// <param name="videoStream">The video stream.</param>
  388. /// <param name="audioStream">The audio stream.</param>
  389. /// <returns><c>true</c> if [is condition satisfied] [the specified condition]; otherwise, <c>false</c>.</returns>
  390. /// <exception cref="System.InvalidOperationException">Unexpected ProfileConditionType</exception>
  391. private bool IsConditionSatisfied(ProfileCondition condition, string mediaPath, MediaStream videoStream, MediaStream audioStream)
  392. {
  393. if (condition.Property == ProfileConditionValue.Has64BitOffsets)
  394. {
  395. // TODO: Determine how to evaluate this
  396. }
  397. if (condition.Property == ProfileConditionValue.VideoProfile)
  398. {
  399. var profile = videoStream == null ? null : videoStream.Profile;
  400. if (!string.IsNullOrEmpty(profile))
  401. {
  402. switch (condition.Condition)
  403. {
  404. case ProfileConditionType.Equals:
  405. return string.Equals(profile, condition.Value, StringComparison.OrdinalIgnoreCase);
  406. case ProfileConditionType.NotEquals:
  407. return !string.Equals(profile, condition.Value, StringComparison.OrdinalIgnoreCase);
  408. default:
  409. throw new InvalidOperationException("Unexpected ProfileConditionType");
  410. }
  411. }
  412. }
  413. else if (condition.Property == ProfileConditionValue.AudioProfile)
  414. {
  415. var profile = audioStream == null ? null : audioStream.Profile;
  416. if (!string.IsNullOrEmpty(profile))
  417. {
  418. switch (condition.Condition)
  419. {
  420. case ProfileConditionType.Equals:
  421. return string.Equals(profile, condition.Value, StringComparison.OrdinalIgnoreCase);
  422. case ProfileConditionType.NotEquals:
  423. return !string.Equals(profile, condition.Value, StringComparison.OrdinalIgnoreCase);
  424. default:
  425. throw new InvalidOperationException("Unexpected ProfileConditionType");
  426. }
  427. }
  428. }
  429. else
  430. {
  431. var actualValue = GetConditionValue(condition, mediaPath, videoStream, audioStream);
  432. if (actualValue.HasValue)
  433. {
  434. double expected;
  435. if (double.TryParse(condition.Value, NumberStyles.Any, _usCulture, out expected))
  436. {
  437. switch (condition.Condition)
  438. {
  439. case ProfileConditionType.Equals:
  440. return actualValue.Value.Equals(expected);
  441. case ProfileConditionType.GreaterThanEqual:
  442. return actualValue.Value >= expected;
  443. case ProfileConditionType.LessThanEqual:
  444. return actualValue.Value <= expected;
  445. case ProfileConditionType.NotEquals:
  446. return !actualValue.Value.Equals(expected);
  447. default:
  448. throw new InvalidOperationException("Unexpected ProfileConditionType");
  449. }
  450. }
  451. }
  452. }
  453. // Value doesn't exist in metadata. Fail it if required.
  454. return !condition.IsRequired;
  455. }
  456. /// <summary>
  457. /// Gets the condition value.
  458. /// </summary>
  459. /// <param name="condition">The condition.</param>
  460. /// <param name="mediaPath">The media path.</param>
  461. /// <param name="videoStream">The video stream.</param>
  462. /// <param name="audioStream">The audio stream.</param>
  463. /// <returns>System.Nullable{System.Int64}.</returns>
  464. /// <exception cref="System.InvalidOperationException">Unexpected Property</exception>
  465. private double? GetConditionValue(ProfileCondition condition, string mediaPath, MediaStream videoStream, MediaStream audioStream)
  466. {
  467. switch (condition.Property)
  468. {
  469. case ProfileConditionValue.AudioBitrate:
  470. return audioStream == null ? null : audioStream.BitRate;
  471. case ProfileConditionValue.AudioChannels:
  472. return audioStream == null ? null : audioStream.Channels;
  473. case ProfileConditionValue.VideoBitrate:
  474. return videoStream == null ? null : videoStream.BitRate;
  475. case ProfileConditionValue.VideoFramerate:
  476. return videoStream == null ? null : (videoStream.AverageFrameRate ?? videoStream.RealFrameRate);
  477. case ProfileConditionValue.Height:
  478. return videoStream == null ? null : videoStream.Height;
  479. case ProfileConditionValue.Width:
  480. return videoStream == null ? null : videoStream.Width;
  481. case ProfileConditionValue.VideoLevel:
  482. return videoStream == null ? null : videoStream.Level;
  483. case ProfileConditionValue.VideoBitDepth:
  484. return videoStream == null ? null : GetBitDepth(videoStream);
  485. default:
  486. throw new InvalidOperationException("Unexpected Property");
  487. }
  488. }
  489. private int? GetBitDepth(MediaStream videoStream)
  490. {
  491. var eightBit = new List<string>
  492. {
  493. "yuv420p",
  494. "yuv411p",
  495. "yuvj420p",
  496. "uyyvyy411",
  497. "nv12",
  498. "nv21",
  499. "rgb444le",
  500. "rgb444be",
  501. "bgr444le",
  502. "bgr444be",
  503. "yuvj411p"
  504. };
  505. if (!string.IsNullOrEmpty(videoStream.PixelFormat))
  506. {
  507. if (eightBit.Contains(videoStream.PixelFormat, StringComparer.OrdinalIgnoreCase))
  508. {
  509. return 8;
  510. }
  511. }
  512. return null;
  513. }
  514. }
  515. }