2
0

StreamBuilder.cs 50 KB

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