StreamBuilder.cs 40 KB

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