StreamBuilder.cs 43 KB

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