StreamBuilder.cs 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072
  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, options.Context, 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, options.Context, 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.SubProtocol = transcodingProfile.Protocol;
  377. playlistItem.AudioStreamIndex = audioStreamIndex;
  378. List<ProfileCondition> videoTranscodingConditions = new List<ProfileCondition>();
  379. foreach (CodecProfile i in options.Profile.CodecProfiles)
  380. {
  381. if (i.Type == CodecType.Video && i.ContainsCodec(transcodingProfile.VideoCodec, transcodingProfile.Container))
  382. {
  383. foreach (ProfileCondition c in i.Conditions)
  384. {
  385. videoTranscodingConditions.Add(c);
  386. }
  387. break;
  388. }
  389. }
  390. ApplyTranscodingConditions(playlistItem, videoTranscodingConditions);
  391. List<ProfileCondition> audioTranscodingConditions = new List<ProfileCondition>();
  392. foreach (CodecProfile i in options.Profile.CodecProfiles)
  393. {
  394. if (i.Type == CodecType.VideoAudio && i.ContainsCodec(playlistItem.AudioCodec, transcodingProfile.Container))
  395. {
  396. foreach (ProfileCondition c in i.Conditions)
  397. {
  398. audioTranscodingConditions.Add(c);
  399. }
  400. break;
  401. }
  402. }
  403. ApplyTranscodingConditions(playlistItem, audioTranscodingConditions);
  404. // Honor requested max channels
  405. if (options.MaxAudioChannels.HasValue)
  406. {
  407. int currentValue = playlistItem.MaxAudioChannels ?? options.MaxAudioChannels.Value;
  408. playlistItem.MaxAudioChannels = Math.Min(options.MaxAudioChannels.Value, currentValue);
  409. }
  410. int audioBitrate = GetAudioBitrate(options.GetMaxBitrate(), playlistItem.TargetAudioChannels, playlistItem.TargetAudioCodec, audioStream);
  411. playlistItem.AudioBitrate = Math.Min(playlistItem.AudioBitrate ?? audioBitrate, audioBitrate);
  412. int? maxBitrateSetting = options.GetMaxBitrate();
  413. // Honor max rate
  414. if (maxBitrateSetting.HasValue)
  415. {
  416. int videoBitrate = maxBitrateSetting.Value;
  417. if (playlistItem.AudioBitrate.HasValue)
  418. {
  419. videoBitrate -= playlistItem.AudioBitrate.Value;
  420. }
  421. // Make sure the video bitrate is lower than bitrate settings but at least 64k
  422. int currentValue = playlistItem.VideoBitrate ?? videoBitrate;
  423. playlistItem.VideoBitrate = Math.Max(Math.Min(videoBitrate, currentValue), 64000);
  424. }
  425. }
  426. return playlistItem;
  427. }
  428. private int GetAudioBitrate(int? maxTotalBitrate, int? targetAudioChannels, string targetAudioCodec, MediaStream audioStream)
  429. {
  430. var defaultBitrate = 128000;
  431. if (targetAudioChannels.HasValue)
  432. {
  433. if (targetAudioChannels.Value >= 5 && (maxTotalBitrate ?? 0) >= 2000000)
  434. {
  435. defaultBitrate = 320000;
  436. }
  437. }
  438. int encoderAudioBitrateLimit = int.MaxValue;
  439. if (audioStream != null)
  440. {
  441. // Seeing webm encoding failures when source has 1 audio channel and 22k bitrate.
  442. // Any attempts to transcode over 64k will fail
  443. if (audioStream.Channels.HasValue &&
  444. audioStream.Channels.Value == 1)
  445. {
  446. if ((audioStream.BitRate ?? 0) < 64000)
  447. {
  448. encoderAudioBitrateLimit = 64000;
  449. }
  450. }
  451. }
  452. return Math.Min(defaultBitrate, encoderAudioBitrateLimit);
  453. }
  454. private PlayMethod? GetVideoDirectPlayProfile(DeviceProfile profile,
  455. MediaSourceInfo mediaSource,
  456. MediaStream videoStream,
  457. MediaStream audioStream,
  458. bool isEligibleForDirectPlay,
  459. bool isEligibleForDirectStream)
  460. {
  461. if (videoStream == null)
  462. {
  463. _logger.Info("Profile: {0}, Cannot direct stream with no known video stream. Path: {1}",
  464. profile.Name ?? "Unknown Profile",
  465. mediaSource.Path ?? "Unknown path");
  466. return null;
  467. }
  468. // See if it can be direct played
  469. DirectPlayProfile directPlay = null;
  470. foreach (DirectPlayProfile i in profile.DirectPlayProfiles)
  471. {
  472. if (i.Type == DlnaProfileType.Video && IsVideoDirectPlaySupported(i, mediaSource, videoStream, audioStream))
  473. {
  474. directPlay = i;
  475. break;
  476. }
  477. }
  478. if (directPlay == null)
  479. {
  480. _logger.Info("Profile: {0}, No direct play profiles found for Path: {1}",
  481. profile.Name ?? "Unknown Profile",
  482. mediaSource.Path ?? "Unknown path");
  483. return null;
  484. }
  485. string container = mediaSource.Container;
  486. List<ProfileCondition> conditions = new List<ProfileCondition>();
  487. foreach (ContainerProfile i in profile.ContainerProfiles)
  488. {
  489. if (i.Type == DlnaProfileType.Video &&
  490. ListHelper.ContainsIgnoreCase(i.GetContainers(), container))
  491. {
  492. foreach (ProfileCondition c in i.Conditions)
  493. {
  494. conditions.Add(c);
  495. }
  496. }
  497. }
  498. ConditionProcessor conditionProcessor = new ConditionProcessor();
  499. int? width = videoStream == null ? null : videoStream.Width;
  500. int? height = videoStream == null ? null : videoStream.Height;
  501. int? bitDepth = videoStream == null ? null : videoStream.BitDepth;
  502. int? videoBitrate = videoStream == null ? null : videoStream.BitRate;
  503. double? videoLevel = videoStream == null ? null : videoStream.Level;
  504. string videoProfile = videoStream == null ? null : videoStream.Profile;
  505. float? videoFramerate = videoStream == null ? null : videoStream.AverageFrameRate ?? videoStream.AverageFrameRate;
  506. bool? isAnamorphic = videoStream == null ? null : videoStream.IsAnamorphic;
  507. bool? isCabac = videoStream == null ? null : videoStream.IsCabac;
  508. string videoCodecTag = videoStream == null ? null : videoStream.CodecTag;
  509. int? audioBitrate = audioStream == null ? null : audioStream.BitRate;
  510. int? audioChannels = audioStream == null ? null : audioStream.Channels;
  511. string audioProfile = audioStream == null ? null : audioStream.Profile;
  512. TransportStreamTimestamp? timestamp = videoStream == null ? TransportStreamTimestamp.None : mediaSource.Timestamp;
  513. int? packetLength = videoStream == null ? null : videoStream.PacketLength;
  514. int? refFrames = videoStream == null ? null : videoStream.RefFrames;
  515. int? numAudioStreams = mediaSource.GetStreamCount(MediaStreamType.Audio);
  516. int? numVideoStreams = mediaSource.GetStreamCount(MediaStreamType.Video);
  517. // Check container conditions
  518. foreach (ProfileCondition i in conditions)
  519. {
  520. if (!conditionProcessor.IsVideoConditionSatisfied(i, width, height, bitDepth, videoBitrate, videoProfile, videoLevel, videoFramerate, packetLength, timestamp, isAnamorphic, isCabac, refFrames, numVideoStreams, numAudioStreams, videoCodecTag))
  521. {
  522. LogConditionFailure(profile, "VideoContainerProfile", i, mediaSource);
  523. return null;
  524. }
  525. }
  526. string videoCodec = videoStream == null ? null : videoStream.Codec;
  527. if (string.IsNullOrEmpty(videoCodec))
  528. {
  529. _logger.Info("Profile: {0}, DirectPlay=false. Reason=Unknown video codec. Path: {1}",
  530. profile.Name ?? "Unknown Profile",
  531. mediaSource.Path ?? "Unknown path");
  532. return null;
  533. }
  534. conditions = new List<ProfileCondition>();
  535. foreach (CodecProfile i in profile.CodecProfiles)
  536. {
  537. if (i.Type == CodecType.Video && i.ContainsCodec(videoCodec, container))
  538. {
  539. foreach (ProfileCondition c in i.Conditions)
  540. {
  541. conditions.Add(c);
  542. }
  543. }
  544. }
  545. foreach (ProfileCondition i in conditions)
  546. {
  547. if (!conditionProcessor.IsVideoConditionSatisfied(i, width, height, bitDepth, videoBitrate, videoProfile, videoLevel, videoFramerate, packetLength, timestamp, isAnamorphic, isCabac, refFrames, numVideoStreams, numAudioStreams, videoCodecTag))
  548. {
  549. LogConditionFailure(profile, "VideoCodecProfile", i, mediaSource);
  550. return null;
  551. }
  552. }
  553. if (audioStream != null)
  554. {
  555. string audioCodec = audioStream.Codec;
  556. if (string.IsNullOrEmpty(audioCodec))
  557. {
  558. _logger.Info("Profile: {0}, DirectPlay=false. Reason=Unknown audio codec. Path: {1}",
  559. profile.Name ?? "Unknown Profile",
  560. mediaSource.Path ?? "Unknown path");
  561. return null;
  562. }
  563. conditions = new List<ProfileCondition>();
  564. foreach (CodecProfile i in profile.CodecProfiles)
  565. {
  566. if (i.Type == CodecType.VideoAudio && i.ContainsCodec(audioCodec, container))
  567. {
  568. foreach (ProfileCondition c in i.Conditions)
  569. {
  570. conditions.Add(c);
  571. }
  572. }
  573. }
  574. foreach (ProfileCondition i in conditions)
  575. {
  576. bool? isSecondaryAudio = audioStream == null ? null : mediaSource.IsSecondaryAudio(audioStream);
  577. if (!conditionProcessor.IsVideoAudioConditionSatisfied(i, audioChannels, audioBitrate, audioProfile, isSecondaryAudio))
  578. {
  579. LogConditionFailure(profile, "VideoAudioCodecProfile", i, mediaSource);
  580. return null;
  581. }
  582. }
  583. }
  584. if (isEligibleForDirectPlay && mediaSource.SupportsDirectPlay)
  585. {
  586. if (mediaSource.Protocol == MediaProtocol.Http)
  587. {
  588. if (_localPlayer.CanAccessUrl(mediaSource.Path, mediaSource.RequiredHttpHeaders.Count > 0))
  589. {
  590. return PlayMethod.DirectPlay;
  591. }
  592. }
  593. else if (mediaSource.Protocol == MediaProtocol.File)
  594. {
  595. if (_localPlayer.CanAccessFile(mediaSource.Path))
  596. {
  597. return PlayMethod.DirectPlay;
  598. }
  599. }
  600. }
  601. if (isEligibleForDirectStream && mediaSource.SupportsDirectStream)
  602. {
  603. return PlayMethod.DirectStream;
  604. }
  605. return null;
  606. }
  607. private void LogConditionFailure(DeviceProfile profile, string type, ProfileCondition condition, MediaSourceInfo mediaSource)
  608. {
  609. _logger.Info("Profile: {0}, DirectPlay=false. Reason={1}.{2} Condition: {3}. ConditionValue: {4}. IsRequired: {5}. Path: {6}",
  610. type,
  611. profile.Name ?? "Unknown Profile",
  612. condition.Property,
  613. condition.Condition,
  614. condition.Value ?? string.Empty,
  615. condition.IsRequired,
  616. mediaSource.Path ?? "Unknown path");
  617. }
  618. private bool IsEligibleForDirectPlay(MediaSourceInfo item,
  619. int? maxBitrate,
  620. MediaStream subtitleStream,
  621. VideoOptions options,
  622. PlayMethod playMethod)
  623. {
  624. if (subtitleStream != null)
  625. {
  626. SubtitleProfile subtitleProfile = GetSubtitleProfile(subtitleStream, options.Profile.SubtitleProfiles, options.Context, playMethod);
  627. if (subtitleProfile.Method != SubtitleDeliveryMethod.External && subtitleProfile.Method != SubtitleDeliveryMethod.Embed)
  628. {
  629. _logger.Info("Not eligible for {0} due to unsupported subtitles", playMethod);
  630. return false;
  631. }
  632. }
  633. return IsAudioEligibleForDirectPlay(item, maxBitrate);
  634. }
  635. public static SubtitleProfile GetSubtitleProfile(MediaStream subtitleStream, SubtitleProfile[] subtitleProfiles, EncodingContext context, PlayMethod playMethod)
  636. {
  637. if (playMethod != PlayMethod.Transcode && !subtitleStream.IsExternal)
  638. {
  639. // Look for supported embedded subs
  640. foreach (SubtitleProfile profile in subtitleProfiles)
  641. {
  642. if (!profile.SupportsLanguage(subtitleStream.Language))
  643. {
  644. continue;
  645. }
  646. if (profile.Method != SubtitleDeliveryMethod.Embed)
  647. {
  648. continue;
  649. }
  650. if (subtitleStream.IsTextSubtitleStream == MediaStream.IsTextFormat(profile.Format) && StringHelper.EqualsIgnoreCase(profile.Format, subtitleStream.Codec))
  651. {
  652. return profile;
  653. }
  654. }
  655. }
  656. // Look for an external profile that matches the stream type (text/graphical)
  657. foreach (SubtitleProfile profile in subtitleProfiles)
  658. {
  659. if (profile.Method != SubtitleDeliveryMethod.External && profile.Method != SubtitleDeliveryMethod.Hls)
  660. {
  661. continue;
  662. }
  663. if (!profile.SupportsLanguage(subtitleStream.Language))
  664. {
  665. continue;
  666. }
  667. if ((profile.Method == SubtitleDeliveryMethod.External && subtitleStream.IsTextSubtitleStream == MediaStream.IsTextFormat(profile.Format)) ||
  668. (profile.Method == SubtitleDeliveryMethod.Hls && subtitleStream.IsTextSubtitleStream))
  669. {
  670. bool requiresConversion = !StringHelper.EqualsIgnoreCase(subtitleStream.Codec, profile.Format);
  671. if (subtitleStream.IsTextSubtitleStream || !requiresConversion)
  672. {
  673. if (subtitleStream.SupportsExternalStream)
  674. {
  675. return profile;
  676. }
  677. // For sync we can handle the longer extraction times
  678. if (context == EncodingContext.Static && subtitleStream.IsTextSubtitleStream)
  679. {
  680. return profile;
  681. }
  682. }
  683. }
  684. }
  685. return new SubtitleProfile
  686. {
  687. Method = SubtitleDeliveryMethod.Encode,
  688. Format = subtitleStream.Codec
  689. };
  690. }
  691. private bool IsAudioEligibleForDirectPlay(MediaSourceInfo item, int? maxBitrate)
  692. {
  693. if (!maxBitrate.HasValue || (item.Bitrate.HasValue && item.Bitrate.Value <= maxBitrate.Value))
  694. {
  695. return true;
  696. }
  697. _logger.Info("Bitrate exceeds DirectPlay limit");
  698. return false;
  699. }
  700. private void ValidateInput(VideoOptions options)
  701. {
  702. ValidateAudioInput(options);
  703. if (options.AudioStreamIndex.HasValue && string.IsNullOrEmpty(options.MediaSourceId))
  704. {
  705. throw new ArgumentException("MediaSourceId is required when a specific audio stream is requested");
  706. }
  707. if (options.SubtitleStreamIndex.HasValue && string.IsNullOrEmpty(options.MediaSourceId))
  708. {
  709. throw new ArgumentException("MediaSourceId is required when a specific subtitle stream is requested");
  710. }
  711. }
  712. private void ValidateAudioInput(AudioOptions options)
  713. {
  714. if (string.IsNullOrEmpty(options.ItemId))
  715. {
  716. throw new ArgumentException("ItemId is required");
  717. }
  718. if (string.IsNullOrEmpty(options.DeviceId))
  719. {
  720. throw new ArgumentException("DeviceId is required");
  721. }
  722. if (options.Profile == null)
  723. {
  724. throw new ArgumentException("Profile is required");
  725. }
  726. if (options.MediaSources == null)
  727. {
  728. throw new ArgumentException("MediaSources is required");
  729. }
  730. }
  731. private void ApplyTranscodingConditions(StreamInfo item, IEnumerable<ProfileCondition> conditions)
  732. {
  733. foreach (ProfileCondition condition in conditions)
  734. {
  735. string value = condition.Value;
  736. if (string.IsNullOrEmpty(value))
  737. {
  738. continue;
  739. }
  740. // No way to express this
  741. if (condition.Condition == ProfileConditionType.GreaterThanEqual)
  742. {
  743. continue;
  744. }
  745. switch (condition.Property)
  746. {
  747. case ProfileConditionValue.AudioBitrate:
  748. {
  749. int num;
  750. if (IntHelper.TryParseCultureInvariant(value, out num))
  751. {
  752. item.AudioBitrate = num;
  753. }
  754. break;
  755. }
  756. case ProfileConditionValue.AudioChannels:
  757. {
  758. int num;
  759. if (IntHelper.TryParseCultureInvariant(value, out num))
  760. {
  761. item.MaxAudioChannels = num;
  762. }
  763. break;
  764. }
  765. case ProfileConditionValue.IsCabac:
  766. {
  767. bool val;
  768. if (BoolHelper.TryParseCultureInvariant(value, out val))
  769. {
  770. if (condition.Condition == ProfileConditionType.Equals)
  771. {
  772. item.Cabac = val;
  773. }
  774. else if (condition.Condition == ProfileConditionType.NotEquals)
  775. {
  776. item.Cabac = !val;
  777. }
  778. }
  779. break;
  780. }
  781. case ProfileConditionValue.IsAnamorphic:
  782. case ProfileConditionValue.AudioProfile:
  783. case ProfileConditionValue.Has64BitOffsets:
  784. case ProfileConditionValue.PacketLength:
  785. case ProfileConditionValue.NumAudioStreams:
  786. case ProfileConditionValue.NumVideoStreams:
  787. case ProfileConditionValue.IsSecondaryAudio:
  788. case ProfileConditionValue.VideoTimestamp:
  789. {
  790. // Not supported yet
  791. break;
  792. }
  793. case ProfileConditionValue.RefFrames:
  794. {
  795. int num;
  796. if (IntHelper.TryParseCultureInvariant(value, out num))
  797. {
  798. item.MaxRefFrames = num;
  799. }
  800. break;
  801. }
  802. case ProfileConditionValue.VideoBitDepth:
  803. {
  804. int num;
  805. if (IntHelper.TryParseCultureInvariant(value, out num))
  806. {
  807. item.MaxVideoBitDepth = num;
  808. }
  809. break;
  810. }
  811. case ProfileConditionValue.VideoProfile:
  812. {
  813. item.VideoProfile = (value ?? string.Empty).Split('|')[0];
  814. break;
  815. }
  816. case ProfileConditionValue.Height:
  817. {
  818. int num;
  819. if (IntHelper.TryParseCultureInvariant(value, out num))
  820. {
  821. item.MaxHeight = num;
  822. }
  823. break;
  824. }
  825. case ProfileConditionValue.VideoBitrate:
  826. {
  827. int num;
  828. if (IntHelper.TryParseCultureInvariant(value, out num))
  829. {
  830. item.VideoBitrate = num;
  831. }
  832. break;
  833. }
  834. case ProfileConditionValue.VideoFramerate:
  835. {
  836. float num;
  837. if (FloatHelper.TryParseCultureInvariant(value, out num))
  838. {
  839. item.MaxFramerate = num;
  840. }
  841. break;
  842. }
  843. case ProfileConditionValue.VideoLevel:
  844. {
  845. int num;
  846. if (IntHelper.TryParseCultureInvariant(value, out num))
  847. {
  848. item.VideoLevel = num;
  849. }
  850. break;
  851. }
  852. case ProfileConditionValue.Width:
  853. {
  854. int num;
  855. if (IntHelper.TryParseCultureInvariant(value, out num))
  856. {
  857. item.MaxWidth = num;
  858. }
  859. break;
  860. }
  861. }
  862. }
  863. }
  864. private bool IsAudioDirectPlaySupported(DirectPlayProfile profile, MediaSourceInfo item, MediaStream audioStream)
  865. {
  866. if (profile.Container.Length > 0)
  867. {
  868. // Check container type
  869. string mediaContainer = item.Container ?? string.Empty;
  870. bool any = false;
  871. foreach (string i in profile.GetContainers())
  872. {
  873. if (StringHelper.EqualsIgnoreCase(i, mediaContainer))
  874. {
  875. any = true;
  876. break;
  877. }
  878. }
  879. if (!any)
  880. {
  881. return false;
  882. }
  883. }
  884. return true;
  885. }
  886. private bool IsVideoDirectPlaySupported(DirectPlayProfile profile, MediaSourceInfo item, MediaStream videoStream, MediaStream audioStream)
  887. {
  888. if (profile.Container.Length > 0)
  889. {
  890. // Check container type
  891. string mediaContainer = item.Container ?? string.Empty;
  892. bool any = false;
  893. foreach (string i in profile.GetContainers())
  894. {
  895. if (StringHelper.EqualsIgnoreCase(i, mediaContainer))
  896. {
  897. any = true;
  898. break;
  899. }
  900. }
  901. if (!any)
  902. {
  903. return false;
  904. }
  905. }
  906. // Check video codec
  907. List<string> videoCodecs = profile.GetVideoCodecs();
  908. if (videoCodecs.Count > 0)
  909. {
  910. string videoCodec = videoStream == null ? null : videoStream.Codec;
  911. if (string.IsNullOrEmpty(videoCodec) || !ListHelper.ContainsIgnoreCase(videoCodecs, videoCodec))
  912. {
  913. return false;
  914. }
  915. }
  916. List<string> audioCodecs = profile.GetAudioCodecs();
  917. if (audioCodecs.Count > 0)
  918. {
  919. // Check audio codecs
  920. string audioCodec = audioStream == null ? null : audioStream.Codec;
  921. if (string.IsNullOrEmpty(audioCodec) || !ListHelper.ContainsIgnoreCase(audioCodecs, audioCodec))
  922. {
  923. return false;
  924. }
  925. }
  926. return true;
  927. }
  928. }
  929. }