StreamBuilder.cs 44 KB

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