StreamBuilder.cs 39 KB

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