StreamBuilder.cs 44 KB

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