StreamBuilder.cs 40 KB

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