StreamBuilder.cs 25 KB

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