StreamBuilder.cs 42 KB

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