StreamBuilder.cs 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622
  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. using System.Globalization;
  10. using System.Linq;
  11. namespace MediaBrowser.Model.Dlna
  12. {
  13. public class StreamBuilder
  14. {
  15. private readonly ILogger _logger;
  16. private readonly ITranscoderSupport _transcoderSupport;
  17. public StreamBuilder(ITranscoderSupport transcoderSupport, ILogger logger)
  18. {
  19. _transcoderSupport = transcoderSupport;
  20. _logger = logger;
  21. }
  22. public StreamBuilder(ILogger logger)
  23. : this(new FullTranscoderSupport(), logger)
  24. {
  25. }
  26. public StreamInfo BuildAudioItem(AudioOptions options)
  27. {
  28. ValidateAudioInput(options);
  29. List<MediaSourceInfo> mediaSources = new List<MediaSourceInfo>();
  30. foreach (MediaSourceInfo i in options.MediaSources)
  31. {
  32. if (string.IsNullOrEmpty(options.MediaSourceId) ||
  33. StringHelper.EqualsIgnoreCase(i.Id, options.MediaSourceId))
  34. {
  35. mediaSources.Add(i);
  36. }
  37. }
  38. List<StreamInfo> streams = new List<StreamInfo>();
  39. foreach (MediaSourceInfo i in mediaSources)
  40. {
  41. StreamInfo streamInfo = BuildAudioItem(i, options);
  42. if (streamInfo != null)
  43. {
  44. streams.Add(streamInfo);
  45. }
  46. }
  47. foreach (StreamInfo stream in streams)
  48. {
  49. stream.DeviceId = options.DeviceId;
  50. stream.DeviceProfileId = options.Profile.Id;
  51. }
  52. return GetOptimalStream(streams, options.GetMaxBitrate(true));
  53. }
  54. public StreamInfo BuildVideoItem(VideoOptions options)
  55. {
  56. ValidateInput(options);
  57. List<MediaSourceInfo> mediaSources = new List<MediaSourceInfo>();
  58. foreach (MediaSourceInfo i in options.MediaSources)
  59. {
  60. if (string.IsNullOrEmpty(options.MediaSourceId) ||
  61. StringHelper.EqualsIgnoreCase(i.Id, options.MediaSourceId))
  62. {
  63. mediaSources.Add(i);
  64. }
  65. }
  66. List<StreamInfo> streams = new List<StreamInfo>();
  67. foreach (MediaSourceInfo i in mediaSources)
  68. {
  69. StreamInfo streamInfo = BuildVideoItem(i, options);
  70. if (streamInfo != null)
  71. {
  72. streams.Add(streamInfo);
  73. }
  74. }
  75. foreach (StreamInfo stream in streams)
  76. {
  77. stream.DeviceId = options.DeviceId;
  78. stream.DeviceProfileId = options.Profile.Id;
  79. }
  80. return GetOptimalStream(streams, options.GetMaxBitrate(false));
  81. }
  82. private StreamInfo GetOptimalStream(List<StreamInfo> streams, long? maxBitrate)
  83. {
  84. streams = StreamInfoSorter.SortMediaSources(streams, maxBitrate);
  85. foreach (StreamInfo stream in streams)
  86. {
  87. return stream;
  88. }
  89. return null;
  90. }
  91. private TranscodeReason? GetTranscodeReasonForFailedCondition(ProfileCondition condition)
  92. {
  93. switch (condition.Property)
  94. {
  95. case ProfileConditionValue.AudioBitrate:
  96. if (condition.Condition == ProfileConditionType.LessThanEqual)
  97. {
  98. return TranscodeReason.AudioBitrateNotSupported;
  99. }
  100. return TranscodeReason.AudioBitrateNotSupported;
  101. case ProfileConditionValue.AudioChannels:
  102. if (condition.Condition == ProfileConditionType.LessThanEqual)
  103. {
  104. return TranscodeReason.AudioChannelsNotSupported;
  105. }
  106. return TranscodeReason.AudioChannelsNotSupported;
  107. case ProfileConditionValue.AudioProfile:
  108. return TranscodeReason.AudioProfileNotSupported;
  109. case ProfileConditionValue.AudioSampleRate:
  110. return TranscodeReason.AudioSampleRateNotSupported;
  111. case ProfileConditionValue.Has64BitOffsets:
  112. // TODO
  113. return null;
  114. case ProfileConditionValue.Height:
  115. return TranscodeReason.VideoResolutionNotSupported;
  116. case ProfileConditionValue.IsAnamorphic:
  117. return TranscodeReason.AnamorphicVideoNotSupported;
  118. case ProfileConditionValue.IsAvc:
  119. // TODO
  120. return null;
  121. case ProfileConditionValue.IsInterlaced:
  122. return TranscodeReason.InterlacedVideoNotSupported;
  123. case ProfileConditionValue.IsSecondaryAudio:
  124. return TranscodeReason.SecondaryAudioNotSupported;
  125. case ProfileConditionValue.NumAudioStreams:
  126. // TODO
  127. return null;
  128. case ProfileConditionValue.NumVideoStreams:
  129. // TODO
  130. return null;
  131. case ProfileConditionValue.PacketLength:
  132. // TODO
  133. return null;
  134. case ProfileConditionValue.RefFrames:
  135. return TranscodeReason.RefFramesNotSupported;
  136. case ProfileConditionValue.VideoBitDepth:
  137. return TranscodeReason.VideoBitDepthNotSupported;
  138. case ProfileConditionValue.AudioBitDepth:
  139. return TranscodeReason.AudioBitDepthNotSupported;
  140. case ProfileConditionValue.VideoBitrate:
  141. return TranscodeReason.VideoBitrateNotSupported;
  142. case ProfileConditionValue.VideoCodecTag:
  143. return TranscodeReason.VideoCodecNotSupported;
  144. case ProfileConditionValue.VideoFramerate:
  145. return TranscodeReason.VideoFramerateNotSupported;
  146. case ProfileConditionValue.VideoLevel:
  147. return TranscodeReason.VideoLevelNotSupported;
  148. case ProfileConditionValue.VideoProfile:
  149. return TranscodeReason.VideoProfileNotSupported;
  150. case ProfileConditionValue.VideoTimestamp:
  151. // TODO
  152. return null;
  153. case ProfileConditionValue.Width:
  154. return TranscodeReason.VideoResolutionNotSupported;
  155. default:
  156. return null;
  157. }
  158. }
  159. private StreamInfo BuildAudioItem(MediaSourceInfo item, AudioOptions options)
  160. {
  161. List<TranscodeReason> transcodeReasons = new List<TranscodeReason>();
  162. StreamInfo playlistItem = new StreamInfo
  163. {
  164. ItemId = options.ItemId,
  165. MediaType = DlnaProfileType.Audio,
  166. MediaSource = item,
  167. RunTimeTicks = item.RunTimeTicks,
  168. Context = options.Context,
  169. DeviceProfile = options.Profile
  170. };
  171. if (options.ForceDirectPlay)
  172. {
  173. playlistItem.PlayMethod = PlayMethod.DirectPlay;
  174. playlistItem.Container = item.Container;
  175. return playlistItem;
  176. }
  177. if (options.ForceDirectStream)
  178. {
  179. playlistItem.PlayMethod = PlayMethod.DirectStream;
  180. playlistItem.Container = item.Container;
  181. return playlistItem;
  182. }
  183. MediaStream audioStream = item.GetDefaultAudioStream(null);
  184. var directPlayInfo = GetAudioDirectPlayMethods(item, audioStream, options);
  185. List<PlayMethod> directPlayMethods = directPlayInfo.Item1;
  186. transcodeReasons.AddRange(directPlayInfo.Item2);
  187. ConditionProcessor conditionProcessor = new ConditionProcessor();
  188. int? inputAudioChannels = audioStream == null ? null : audioStream.Channels;
  189. int? inputAudioBitrate = audioStream == null ? null : audioStream.BitDepth;
  190. int? inputAudioSampleRate = audioStream == null ? null : audioStream.SampleRate;
  191. int? inputAudioBitDepth = audioStream == null ? null : audioStream.BitDepth;
  192. if (directPlayMethods.Count > 0)
  193. {
  194. string audioCodec = audioStream == null ? null : audioStream.Codec;
  195. // Make sure audio codec profiles are satisfied
  196. if (!string.IsNullOrEmpty(audioCodec))
  197. {
  198. List<ProfileCondition> conditions = new List<ProfileCondition>();
  199. foreach (CodecProfile i in options.Profile.CodecProfiles)
  200. {
  201. if (i.Type == CodecType.Audio && i.ContainsCodec(audioCodec, item.Container))
  202. {
  203. bool applyConditions = true;
  204. foreach (ProfileCondition applyCondition in i.ApplyConditions)
  205. {
  206. if (!conditionProcessor.IsAudioConditionSatisfied(applyCondition, inputAudioChannels, inputAudioBitrate, inputAudioSampleRate, inputAudioBitDepth))
  207. {
  208. LogConditionFailure(options.Profile, "AudioCodecProfile", applyCondition, item);
  209. applyConditions = false;
  210. break;
  211. }
  212. }
  213. if (applyConditions)
  214. {
  215. foreach (ProfileCondition c in i.Conditions)
  216. {
  217. conditions.Add(c);
  218. }
  219. }
  220. }
  221. }
  222. bool all = true;
  223. foreach (ProfileCondition c in conditions)
  224. {
  225. if (!conditionProcessor.IsAudioConditionSatisfied(c, inputAudioChannels, inputAudioBitrate, inputAudioSampleRate, inputAudioBitDepth))
  226. {
  227. LogConditionFailure(options.Profile, "AudioCodecProfile", c, item);
  228. var transcodeReason = GetTranscodeReasonForFailedCondition(c);
  229. if (transcodeReason.HasValue)
  230. {
  231. transcodeReasons.Add(transcodeReason.Value);
  232. }
  233. all = false;
  234. break;
  235. }
  236. }
  237. if (all)
  238. {
  239. if (directPlayMethods.Contains(PlayMethod.DirectStream))
  240. {
  241. playlistItem.PlayMethod = PlayMethod.DirectStream;
  242. }
  243. playlistItem.Container = item.Container;
  244. return playlistItem;
  245. }
  246. }
  247. }
  248. TranscodingProfile transcodingProfile = null;
  249. foreach (TranscodingProfile i in options.Profile.TranscodingProfiles)
  250. {
  251. if (i.Type == playlistItem.MediaType && i.Context == options.Context)
  252. {
  253. if (_transcoderSupport.CanEncodeToAudioCodec(i.AudioCodec ?? i.Container))
  254. {
  255. transcodingProfile = i;
  256. break;
  257. }
  258. }
  259. }
  260. if (transcodingProfile != null)
  261. {
  262. if (!item.SupportsTranscoding)
  263. {
  264. return null;
  265. }
  266. playlistItem.PlayMethod = PlayMethod.Transcode;
  267. playlistItem.TranscodeSeekInfo = transcodingProfile.TranscodeSeekInfo;
  268. playlistItem.EstimateContentLength = transcodingProfile.EstimateContentLength;
  269. playlistItem.Container = transcodingProfile.Container;
  270. if (string.IsNullOrEmpty(transcodingProfile.AudioCodec))
  271. {
  272. playlistItem.AudioCodecs = new string[] { };
  273. }
  274. else
  275. {
  276. playlistItem.AudioCodecs = transcodingProfile.AudioCodec.Split(',');
  277. }
  278. playlistItem.SubProtocol = transcodingProfile.Protocol;
  279. List<CodecProfile> audioCodecProfiles = new List<CodecProfile>();
  280. foreach (CodecProfile i in options.Profile.CodecProfiles)
  281. {
  282. if (i.Type == CodecType.Audio && i.ContainsCodec(transcodingProfile.AudioCodec, transcodingProfile.Container))
  283. {
  284. audioCodecProfiles.Add(i);
  285. }
  286. if (audioCodecProfiles.Count >= 1) break;
  287. }
  288. List<ProfileCondition> audioTranscodingConditions = new List<ProfileCondition>();
  289. foreach (CodecProfile i in audioCodecProfiles)
  290. {
  291. bool applyConditions = true;
  292. foreach (ProfileCondition applyCondition in i.ApplyConditions)
  293. {
  294. if (!conditionProcessor.IsAudioConditionSatisfied(applyCondition, inputAudioChannels, inputAudioBitrate, inputAudioSampleRate, inputAudioBitDepth))
  295. {
  296. LogConditionFailure(options.Profile, "AudioCodecProfile", applyCondition, item);
  297. applyConditions = false;
  298. break;
  299. }
  300. }
  301. if (applyConditions)
  302. {
  303. foreach (ProfileCondition c in i.Conditions)
  304. {
  305. audioTranscodingConditions.Add(c);
  306. }
  307. }
  308. }
  309. ApplyTranscodingConditions(playlistItem, audioTranscodingConditions);
  310. // Honor requested max channels
  311. if (options.MaxAudioChannels.HasValue)
  312. {
  313. int currentValue = playlistItem.MaxAudioChannels ?? options.MaxAudioChannels.Value;
  314. playlistItem.MaxAudioChannels = Math.Min(options.MaxAudioChannels.Value, currentValue);
  315. }
  316. long transcodingBitrate = options.AudioTranscodingBitrate ??
  317. options.Profile.MusicStreamingTranscodingBitrate ??
  318. 128000;
  319. var configuredBitrate = options.GetMaxBitrate(true);
  320. if (configuredBitrate.HasValue)
  321. {
  322. transcodingBitrate = Math.Min(configuredBitrate.Value, transcodingBitrate);
  323. }
  324. var longBitrate = Math.Min(transcodingBitrate, playlistItem.AudioBitrate ?? transcodingBitrate);
  325. playlistItem.AudioBitrate = longBitrate > int.MaxValue ? int.MaxValue : Convert.ToInt32(longBitrate);
  326. }
  327. playlistItem.TranscodeReasons = transcodeReasons;
  328. return playlistItem;
  329. }
  330. private long? GetBitrateForDirectPlayCheck(MediaSourceInfo item, AudioOptions options, bool isAudio)
  331. {
  332. if (item.Protocol == MediaProtocol.File)
  333. {
  334. return options.Profile.MaxStaticBitrate;
  335. }
  336. return options.GetMaxBitrate(isAudio);
  337. }
  338. private Tuple<List<PlayMethod>, List<TranscodeReason>> GetAudioDirectPlayMethods(MediaSourceInfo item, MediaStream audioStream, AudioOptions options)
  339. {
  340. List<TranscodeReason> transcodeReasons = new List<TranscodeReason>();
  341. DirectPlayProfile directPlayProfile = null;
  342. foreach (DirectPlayProfile i in options.Profile.DirectPlayProfiles)
  343. {
  344. if (i.Type == DlnaProfileType.Audio && IsAudioDirectPlaySupported(i, item, audioStream))
  345. {
  346. directPlayProfile = i;
  347. break;
  348. }
  349. }
  350. List<PlayMethod> playMethods = new List<PlayMethod>();
  351. if (directPlayProfile != null)
  352. {
  353. // While options takes the network and other factors into account. Only applies to direct stream
  354. if (item.SupportsDirectStream)
  355. {
  356. if (IsAudioEligibleForDirectPlay(item, options.GetMaxBitrate(true), PlayMethod.DirectStream))
  357. {
  358. if (options.EnableDirectStream)
  359. {
  360. playMethods.Add(PlayMethod.DirectStream);
  361. }
  362. }
  363. else
  364. {
  365. transcodeReasons.Add(TranscodeReason.ContainerBitrateExceedsLimit);
  366. }
  367. }
  368. // The profile describes what the device supports
  369. // If device requirements are satisfied then allow both direct stream and direct play
  370. if (item.SupportsDirectPlay)
  371. {
  372. if (IsAudioEligibleForDirectPlay(item, GetBitrateForDirectPlayCheck(item, options, true), PlayMethod.DirectPlay))
  373. {
  374. if (options.EnableDirectPlay)
  375. {
  376. playMethods.Add(PlayMethod.DirectPlay);
  377. }
  378. }
  379. else
  380. {
  381. transcodeReasons.Add(TranscodeReason.ContainerBitrateExceedsLimit);
  382. }
  383. }
  384. }
  385. else
  386. {
  387. transcodeReasons.InsertRange(0, GetTranscodeReasonsFromDirectPlayProfile(item, null, audioStream, options.Profile.DirectPlayProfiles));
  388. _logger.Info("Profile: {0}, No direct play profiles found for Path: {1}",
  389. options.Profile.Name ?? "Unknown Profile",
  390. item.Path ?? "Unknown path");
  391. }
  392. if (playMethods.Count > 0)
  393. {
  394. transcodeReasons.Clear();
  395. }
  396. else
  397. {
  398. transcodeReasons = transcodeReasons.Distinct().ToList();
  399. }
  400. return new Tuple<List<PlayMethod>, List<TranscodeReason>>(playMethods, transcodeReasons);
  401. }
  402. private List<TranscodeReason> GetTranscodeReasonsFromDirectPlayProfile(MediaSourceInfo item, MediaStream videoStream, MediaStream audioStream, IEnumerable<DirectPlayProfile> directPlayProfiles)
  403. {
  404. var list = new List<TranscodeReason>();
  405. var containerSupported = false;
  406. var audioSupported = false;
  407. var videoSupported = false;
  408. foreach (var profile in directPlayProfiles)
  409. {
  410. if (profile.Container.Length > 0)
  411. {
  412. // Check container type
  413. string mediaContainer = item.Container ?? string.Empty;
  414. foreach (string i in profile.GetContainers())
  415. {
  416. if (StringHelper.EqualsIgnoreCase(i, mediaContainer))
  417. {
  418. containerSupported = true;
  419. if (videoStream != null)
  420. {
  421. // Check video codec
  422. List<string> videoCodecs = profile.GetVideoCodecs();
  423. if (videoCodecs.Count > 0)
  424. {
  425. string videoCodec = videoStream.Codec;
  426. if (!string.IsNullOrEmpty(videoCodec) && ListHelper.ContainsIgnoreCase(videoCodecs, videoCodec))
  427. {
  428. videoSupported = true;
  429. }
  430. }
  431. else
  432. {
  433. videoSupported = true;
  434. }
  435. }
  436. if (audioStream != null)
  437. {
  438. // Check audio codec
  439. List<string> audioCodecs = profile.GetAudioCodecs();
  440. if (audioCodecs.Count > 0)
  441. {
  442. string audioCodec = audioStream.Codec;
  443. if (!string.IsNullOrEmpty(audioCodec) && ListHelper.ContainsIgnoreCase(audioCodecs, audioCodec))
  444. {
  445. audioSupported = true;
  446. }
  447. }
  448. else
  449. {
  450. audioSupported = true;
  451. }
  452. }
  453. }
  454. }
  455. }
  456. }
  457. if (!containerSupported)
  458. {
  459. list.Add(TranscodeReason.ContainerNotSupported);
  460. }
  461. if (videoStream != null && !videoSupported)
  462. {
  463. list.Add(TranscodeReason.VideoCodecNotSupported);
  464. }
  465. if (audioStream != null && !audioSupported)
  466. {
  467. list.Add(TranscodeReason.AudioCodecNotSupported);
  468. }
  469. return list;
  470. }
  471. private int? GetDefaultSubtitleStreamIndex(MediaSourceInfo item, SubtitleProfile[] subtitleProfiles)
  472. {
  473. int highestScore = -1;
  474. foreach (MediaStream stream in item.MediaStreams)
  475. {
  476. if (stream.Type == MediaStreamType.Subtitle && stream.Score.HasValue)
  477. {
  478. if (stream.Score.Value > highestScore)
  479. {
  480. highestScore = stream.Score.Value;
  481. }
  482. }
  483. }
  484. List<MediaStream> topStreams = new List<MediaStream>();
  485. foreach (MediaStream stream in item.MediaStreams)
  486. {
  487. if (stream.Type == MediaStreamType.Subtitle && stream.Score.HasValue && stream.Score.Value == highestScore)
  488. {
  489. topStreams.Add(stream);
  490. }
  491. }
  492. // If multiple streams have an equal score, try to pick the most efficient one
  493. if (topStreams.Count > 1)
  494. {
  495. foreach (MediaStream stream in topStreams)
  496. {
  497. foreach (SubtitleProfile profile in subtitleProfiles)
  498. {
  499. if (profile.Method == SubtitleDeliveryMethod.External && StringHelper.EqualsIgnoreCase(profile.Format, stream.Codec))
  500. {
  501. return stream.Index;
  502. }
  503. }
  504. }
  505. }
  506. // If no optimization panned out, just use the original default
  507. return item.DefaultSubtitleStreamIndex;
  508. }
  509. private StreamInfo BuildVideoItem(MediaSourceInfo item, VideoOptions options)
  510. {
  511. if (item == null)
  512. {
  513. throw new ArgumentNullException("item");
  514. }
  515. List<TranscodeReason> transcodeReasons = new List<TranscodeReason>();
  516. StreamInfo playlistItem = new StreamInfo
  517. {
  518. ItemId = options.ItemId,
  519. MediaType = DlnaProfileType.Video,
  520. MediaSource = item,
  521. RunTimeTicks = item.RunTimeTicks,
  522. Context = options.Context,
  523. DeviceProfile = options.Profile
  524. };
  525. playlistItem.SubtitleStreamIndex = options.SubtitleStreamIndex ?? GetDefaultSubtitleStreamIndex(item, options.Profile.SubtitleProfiles);
  526. MediaStream subtitleStream = playlistItem.SubtitleStreamIndex.HasValue ? item.GetMediaStream(MediaStreamType.Subtitle, playlistItem.SubtitleStreamIndex.Value) : null;
  527. MediaStream audioStream = item.GetDefaultAudioStream(options.AudioStreamIndex ?? item.DefaultAudioStreamIndex);
  528. int? audioStreamIndex = null;
  529. if (audioStream != null)
  530. {
  531. audioStreamIndex = audioStream.Index;
  532. }
  533. MediaStream videoStream = item.VideoStream;
  534. // TODO: This doesn't accout for situation of device being able to handle media bitrate, but wifi connection not fast enough
  535. var directPlayEligibilityResult = IsEligibleForDirectPlay(item, GetBitrateForDirectPlayCheck(item, options, true), subtitleStream, options, PlayMethod.DirectPlay);
  536. var directStreamEligibilityResult = IsEligibleForDirectPlay(item, options.GetMaxBitrate(false), subtitleStream, options, PlayMethod.DirectStream);
  537. bool isEligibleForDirectPlay = options.EnableDirectPlay && (options.ForceDirectPlay || directPlayEligibilityResult.Item1);
  538. bool isEligibleForDirectStream = options.EnableDirectStream && (options.ForceDirectStream || directStreamEligibilityResult.Item1);
  539. _logger.Info("Profile: {0}, Path: {1}, isEligibleForDirectPlay: {2}, isEligibleForDirectStream: {3}",
  540. options.Profile.Name ?? "Unknown Profile",
  541. item.Path ?? "Unknown path",
  542. isEligibleForDirectPlay,
  543. isEligibleForDirectStream);
  544. if (isEligibleForDirectPlay || isEligibleForDirectStream)
  545. {
  546. // See if it can be direct played
  547. var directPlayInfo = GetVideoDirectPlayProfile(options, item, videoStream, audioStream, isEligibleForDirectPlay, isEligibleForDirectStream);
  548. var directPlay = directPlayInfo.Item1;
  549. if (directPlay != null)
  550. {
  551. playlistItem.PlayMethod = directPlay.Value;
  552. playlistItem.Container = item.Container;
  553. if (subtitleStream != null)
  554. {
  555. SubtitleProfile subtitleProfile = GetSubtitleProfile(subtitleStream, options.Profile.SubtitleProfiles, directPlay.Value, null, null);
  556. playlistItem.SubtitleDeliveryMethod = subtitleProfile.Method;
  557. playlistItem.SubtitleFormat = subtitleProfile.Format;
  558. }
  559. return playlistItem;
  560. }
  561. transcodeReasons.AddRange(directPlayInfo.Item2);
  562. }
  563. if (directPlayEligibilityResult.Item2.HasValue)
  564. {
  565. transcodeReasons.Add(directPlayEligibilityResult.Item2.Value);
  566. }
  567. if (directStreamEligibilityResult.Item2.HasValue)
  568. {
  569. transcodeReasons.Add(directStreamEligibilityResult.Item2.Value);
  570. }
  571. // Can't direct play, find the transcoding profile
  572. TranscodingProfile transcodingProfile = null;
  573. foreach (TranscodingProfile i in options.Profile.TranscodingProfiles)
  574. {
  575. if (i.Type == playlistItem.MediaType && i.Context == options.Context)
  576. {
  577. transcodingProfile = i;
  578. break;
  579. }
  580. }
  581. if (transcodingProfile != null)
  582. {
  583. if (!item.SupportsTranscoding)
  584. {
  585. return null;
  586. }
  587. if (subtitleStream != null)
  588. {
  589. SubtitleProfile subtitleProfile = GetSubtitleProfile(subtitleStream, options.Profile.SubtitleProfiles, PlayMethod.Transcode, transcodingProfile.Protocol, transcodingProfile.Container);
  590. playlistItem.SubtitleDeliveryMethod = subtitleProfile.Method;
  591. playlistItem.SubtitleFormat = subtitleProfile.Format;
  592. playlistItem.SubtitleCodecs = new[] { subtitleProfile.Format };
  593. }
  594. playlistItem.PlayMethod = PlayMethod.Transcode;
  595. playlistItem.Container = transcodingProfile.Container;
  596. playlistItem.EstimateContentLength = transcodingProfile.EstimateContentLength;
  597. playlistItem.TranscodeSeekInfo = transcodingProfile.TranscodeSeekInfo;
  598. playlistItem.AudioCodecs = transcodingProfile.AudioCodec.Split(',');
  599. playlistItem.VideoCodecs = transcodingProfile.VideoCodec.Split(',');
  600. playlistItem.CopyTimestamps = transcodingProfile.CopyTimestamps;
  601. playlistItem.EnableSubtitlesInManifest = transcodingProfile.EnableSubtitlesInManifest;
  602. playlistItem.BreakOnNonKeyFrames = transcodingProfile.BreakOnNonKeyFrames;
  603. if (transcodingProfile.MinSegments > 0)
  604. {
  605. playlistItem.MinSegments = transcodingProfile.MinSegments;
  606. }
  607. if (transcodingProfile.SegmentLength > 0)
  608. {
  609. playlistItem.SegmentLength = transcodingProfile.SegmentLength;
  610. }
  611. if (!string.IsNullOrEmpty(transcodingProfile.MaxAudioChannels))
  612. {
  613. int transcodingMaxAudioChannels;
  614. if (int.TryParse(transcodingProfile.MaxAudioChannels, NumberStyles.Any, CultureInfo.InvariantCulture, out transcodingMaxAudioChannels))
  615. {
  616. playlistItem.TranscodingMaxAudioChannels = transcodingMaxAudioChannels;
  617. }
  618. }
  619. playlistItem.SubProtocol = transcodingProfile.Protocol;
  620. playlistItem.AudioStreamIndex = audioStreamIndex;
  621. ConditionProcessor conditionProcessor = new ConditionProcessor();
  622. List<ProfileCondition> videoTranscodingConditions = new List<ProfileCondition>();
  623. foreach (CodecProfile i in options.Profile.CodecProfiles)
  624. {
  625. if (i.Type == CodecType.Video && i.ContainsCodec(transcodingProfile.VideoCodec, transcodingProfile.Container))
  626. {
  627. bool applyConditions = true;
  628. foreach (ProfileCondition applyCondition in i.ApplyConditions)
  629. {
  630. bool? isSecondaryAudio = audioStream == null ? null : item.IsSecondaryAudio(audioStream);
  631. int? inputAudioBitrate = audioStream == null ? null : audioStream.BitRate;
  632. int? audioChannels = audioStream == null ? null : audioStream.Channels;
  633. string audioProfile = audioStream == null ? null : audioStream.Profile;
  634. int? inputAudioSampleRate = audioStream == null ? null : audioStream.SampleRate;
  635. int? inputAudioBitDepth = audioStream == null ? null : audioStream.BitDepth;
  636. if (!conditionProcessor.IsVideoAudioConditionSatisfied(applyCondition, audioChannels, inputAudioBitrate, inputAudioSampleRate, inputAudioBitDepth, audioProfile, isSecondaryAudio))
  637. {
  638. LogConditionFailure(options.Profile, "AudioCodecProfile", applyCondition, item);
  639. applyConditions = false;
  640. break;
  641. }
  642. }
  643. if (applyConditions)
  644. {
  645. foreach (ProfileCondition c in i.Conditions)
  646. {
  647. videoTranscodingConditions.Add(c);
  648. }
  649. break;
  650. }
  651. }
  652. }
  653. ApplyTranscodingConditions(playlistItem, videoTranscodingConditions);
  654. List<ProfileCondition> audioTranscodingConditions = new List<ProfileCondition>();
  655. foreach (CodecProfile i in options.Profile.CodecProfiles)
  656. {
  657. if (i.Type == CodecType.VideoAudio && i.ContainsCodec(playlistItem.TargetAudioCodec, transcodingProfile.Container))
  658. {
  659. bool applyConditions = true;
  660. foreach (ProfileCondition applyCondition in i.ApplyConditions)
  661. {
  662. int? width = videoStream == null ? null : videoStream.Width;
  663. int? height = videoStream == null ? null : videoStream.Height;
  664. int? bitDepth = videoStream == null ? null : videoStream.BitDepth;
  665. int? videoBitrate = videoStream == null ? null : videoStream.BitRate;
  666. double? videoLevel = videoStream == null ? null : videoStream.Level;
  667. string videoProfile = videoStream == null ? null : videoStream.Profile;
  668. float? videoFramerate = videoStream == null ? null : videoStream.AverageFrameRate ?? videoStream.AverageFrameRate;
  669. bool? isAnamorphic = videoStream == null ? null : videoStream.IsAnamorphic;
  670. bool? isInterlaced = videoStream == null ? (bool?)null : videoStream.IsInterlaced;
  671. string videoCodecTag = videoStream == null ? null : videoStream.CodecTag;
  672. bool? isAvc = videoStream == null ? null : videoStream.IsAVC;
  673. TransportStreamTimestamp? timestamp = videoStream == null ? TransportStreamTimestamp.None : item.Timestamp;
  674. int? packetLength = videoStream == null ? null : videoStream.PacketLength;
  675. int? refFrames = videoStream == null ? null : videoStream.RefFrames;
  676. int? numAudioStreams = item.GetStreamCount(MediaStreamType.Audio);
  677. int? numVideoStreams = item.GetStreamCount(MediaStreamType.Video);
  678. if (!conditionProcessor.IsVideoConditionSatisfied(applyCondition, width, height, bitDepth, videoBitrate, videoProfile, videoLevel, videoFramerate, packetLength, timestamp, isAnamorphic, isInterlaced, refFrames, numVideoStreams, numAudioStreams, videoCodecTag, isAvc))
  679. {
  680. LogConditionFailure(options.Profile, "VideoCodecProfile", applyCondition, item);
  681. applyConditions = false;
  682. break;
  683. }
  684. }
  685. if (applyConditions)
  686. {
  687. foreach (ProfileCondition c in i.Conditions)
  688. {
  689. audioTranscodingConditions.Add(c);
  690. }
  691. break;
  692. }
  693. }
  694. }
  695. ApplyTranscodingConditions(playlistItem, audioTranscodingConditions);
  696. // Honor requested max channels
  697. if (options.MaxAudioChannels.HasValue)
  698. {
  699. int currentValue = playlistItem.MaxAudioChannels ?? options.MaxAudioChannels.Value;
  700. playlistItem.MaxAudioChannels = Math.Min(options.MaxAudioChannels.Value, currentValue);
  701. }
  702. int audioBitrate = GetAudioBitrate(playlistItem.SubProtocol, options.GetMaxBitrate(false), playlistItem.TargetAudioChannels, playlistItem.TargetAudioCodec, audioStream);
  703. playlistItem.AudioBitrate = Math.Min(playlistItem.AudioBitrate ?? audioBitrate, audioBitrate);
  704. var maxBitrateSetting = options.GetMaxBitrate(false);
  705. // Honor max rate
  706. if (maxBitrateSetting.HasValue)
  707. {
  708. var videoBitrate = maxBitrateSetting.Value;
  709. if (playlistItem.AudioBitrate.HasValue)
  710. {
  711. videoBitrate -= playlistItem.AudioBitrate.Value;
  712. }
  713. // Make sure the video bitrate is lower than bitrate settings but at least 64k
  714. long currentValue = playlistItem.VideoBitrate ?? videoBitrate;
  715. var longBitrate = Math.Max(Math.Min(videoBitrate, currentValue), 64000);
  716. playlistItem.VideoBitrate = longBitrate > int.MaxValue ? int.MaxValue : Convert.ToInt32(longBitrate);
  717. }
  718. }
  719. playlistItem.TranscodeReasons = transcodeReasons;
  720. return playlistItem;
  721. }
  722. private int GetDefaultAudioBitrateIfUnknown(MediaStream audioStream)
  723. {
  724. if ((audioStream.Channels ?? 0) >= 6)
  725. {
  726. return 384000;
  727. }
  728. return 192000;
  729. }
  730. private int GetAudioBitrate(string subProtocol, long? maxTotalBitrate, int? targetAudioChannels, string targetAudioCodec, MediaStream audioStream)
  731. {
  732. int defaultBitrate = audioStream == null ? 192000 : audioStream.BitRate ?? GetDefaultAudioBitrateIfUnknown(audioStream);
  733. // Reduce the bitrate if we're downmixing
  734. if (targetAudioChannels.HasValue && audioStream != null && audioStream.Channels.HasValue && targetAudioChannels.Value < audioStream.Channels.Value)
  735. {
  736. defaultBitrate = StringHelper.EqualsIgnoreCase(targetAudioCodec, "ac3") ? 192000 : 128000;
  737. }
  738. if (StringHelper.EqualsIgnoreCase(subProtocol, "hls"))
  739. {
  740. defaultBitrate = Math.Min(384000, defaultBitrate);
  741. }
  742. else
  743. {
  744. defaultBitrate = Math.Min(448000, defaultBitrate);
  745. }
  746. int encoderAudioBitrateLimit = int.MaxValue;
  747. if (audioStream != null)
  748. {
  749. // Seeing webm encoding failures when source has 1 audio channel and 22k bitrate.
  750. // Any attempts to transcode over 64k will fail
  751. if (audioStream.Channels.HasValue &&
  752. audioStream.Channels.Value == 1)
  753. {
  754. if ((audioStream.BitRate ?? 0) < 64000)
  755. {
  756. encoderAudioBitrateLimit = 64000;
  757. }
  758. }
  759. }
  760. if (maxTotalBitrate.HasValue)
  761. {
  762. if (maxTotalBitrate.Value < 640000)
  763. {
  764. defaultBitrate = Math.Min(128000, defaultBitrate);
  765. }
  766. }
  767. return Math.Min(defaultBitrate, encoderAudioBitrateLimit);
  768. }
  769. private Tuple<PlayMethod?, List<TranscodeReason>> GetVideoDirectPlayProfile(VideoOptions options,
  770. MediaSourceInfo mediaSource,
  771. MediaStream videoStream,
  772. MediaStream audioStream,
  773. bool isEligibleForDirectPlay,
  774. bool isEligibleForDirectStream)
  775. {
  776. DeviceProfile profile = options.Profile;
  777. if (options.ForceDirectPlay)
  778. {
  779. return new Tuple<PlayMethod?, List<TranscodeReason>>(PlayMethod.DirectPlay, new List<TranscodeReason>());
  780. }
  781. if (options.ForceDirectStream)
  782. {
  783. return new Tuple<PlayMethod?, List<TranscodeReason>>(PlayMethod.DirectStream, new List<TranscodeReason>());
  784. }
  785. if (videoStream == null)
  786. {
  787. _logger.Info("Profile: {0}, Cannot direct stream with no known video stream. Path: {1}",
  788. profile.Name ?? "Unknown Profile",
  789. mediaSource.Path ?? "Unknown path");
  790. return new Tuple<PlayMethod?, List<TranscodeReason>>(null, new List<TranscodeReason> { TranscodeReason.UnknownVideoStreamInfo });
  791. }
  792. // See if it can be direct played
  793. DirectPlayProfile directPlay = null;
  794. foreach (DirectPlayProfile i in profile.DirectPlayProfiles)
  795. {
  796. if (i.Type == DlnaProfileType.Video && IsVideoDirectPlaySupported(i, mediaSource, videoStream, audioStream))
  797. {
  798. directPlay = i;
  799. break;
  800. }
  801. }
  802. if (directPlay == null)
  803. {
  804. _logger.Info("Profile: {0}, No direct play profiles found for Path: {1}",
  805. profile.Name ?? "Unknown Profile",
  806. mediaSource.Path ?? "Unknown path");
  807. return new Tuple<PlayMethod?, List<TranscodeReason>>(null, GetTranscodeReasonsFromDirectPlayProfile(mediaSource, videoStream, audioStream, profile.DirectPlayProfiles));
  808. }
  809. string container = mediaSource.Container;
  810. List<ProfileCondition> conditions = new List<ProfileCondition>();
  811. foreach (ContainerProfile i in profile.ContainerProfiles)
  812. {
  813. if (i.Type == DlnaProfileType.Video &&
  814. i.ContainsContainer(container))
  815. {
  816. foreach (ProfileCondition c in i.Conditions)
  817. {
  818. conditions.Add(c);
  819. }
  820. }
  821. }
  822. ConditionProcessor conditionProcessor = new ConditionProcessor();
  823. int? width = videoStream == null ? null : videoStream.Width;
  824. int? height = videoStream == null ? null : videoStream.Height;
  825. int? bitDepth = videoStream == null ? null : videoStream.BitDepth;
  826. int? videoBitrate = videoStream == null ? null : videoStream.BitRate;
  827. double? videoLevel = videoStream == null ? null : videoStream.Level;
  828. string videoProfile = videoStream == null ? null : videoStream.Profile;
  829. float? videoFramerate = videoStream == null ? null : videoStream.AverageFrameRate ?? videoStream.AverageFrameRate;
  830. bool? isAnamorphic = videoStream == null ? null : videoStream.IsAnamorphic;
  831. bool? isInterlaced = videoStream == null ? (bool?)null : videoStream.IsInterlaced;
  832. string videoCodecTag = videoStream == null ? null : videoStream.CodecTag;
  833. bool? isAvc = videoStream == null ? null : videoStream.IsAVC;
  834. int? audioBitrate = audioStream == null ? null : audioStream.BitRate;
  835. int? audioChannels = audioStream == null ? null : audioStream.Channels;
  836. string audioProfile = audioStream == null ? null : audioStream.Profile;
  837. int? audioSampleRate = audioStream == null ? null : audioStream.SampleRate;
  838. int? audioBitDepth = audioStream == null ? null : audioStream.BitDepth;
  839. TransportStreamTimestamp? timestamp = videoStream == null ? TransportStreamTimestamp.None : mediaSource.Timestamp;
  840. int? packetLength = videoStream == null ? null : videoStream.PacketLength;
  841. int? refFrames = videoStream == null ? null : videoStream.RefFrames;
  842. int? numAudioStreams = mediaSource.GetStreamCount(MediaStreamType.Audio);
  843. int? numVideoStreams = mediaSource.GetStreamCount(MediaStreamType.Video);
  844. // Check container conditions
  845. foreach (ProfileCondition i in conditions)
  846. {
  847. if (!conditionProcessor.IsVideoConditionSatisfied(i, width, height, bitDepth, videoBitrate, videoProfile, videoLevel, videoFramerate, packetLength, timestamp, isAnamorphic, isInterlaced, refFrames, numVideoStreams, numAudioStreams, videoCodecTag, isAvc))
  848. {
  849. LogConditionFailure(profile, "VideoContainerProfile", i, mediaSource);
  850. var transcodeReason = GetTranscodeReasonForFailedCondition(i);
  851. var transcodeReasons = transcodeReason.HasValue
  852. ? new List<TranscodeReason> { transcodeReason.Value }
  853. : new List<TranscodeReason> { };
  854. return new Tuple<PlayMethod?, List<TranscodeReason>>(null, transcodeReasons);
  855. }
  856. }
  857. string videoCodec = videoStream == null ? null : videoStream.Codec;
  858. if (string.IsNullOrEmpty(videoCodec))
  859. {
  860. _logger.Info("Profile: {0}, DirectPlay=false. Reason=Unknown video codec. Path: {1}",
  861. profile.Name ?? "Unknown Profile",
  862. mediaSource.Path ?? "Unknown path");
  863. return new Tuple<PlayMethod?, List<TranscodeReason>>(null, new List<TranscodeReason> { TranscodeReason.UnknownVideoStreamInfo });
  864. }
  865. conditions = new List<ProfileCondition>();
  866. foreach (CodecProfile i in profile.CodecProfiles)
  867. {
  868. if (i.Type == CodecType.Video && i.ContainsCodec(videoCodec, container))
  869. {
  870. bool applyConditions = true;
  871. foreach (ProfileCondition applyCondition in i.ApplyConditions)
  872. {
  873. if (!conditionProcessor.IsVideoConditionSatisfied(applyCondition, width, height, bitDepth, videoBitrate, videoProfile, videoLevel, videoFramerate, packetLength, timestamp, isAnamorphic, isInterlaced, refFrames, numVideoStreams, numAudioStreams, videoCodecTag, isAvc))
  874. {
  875. LogConditionFailure(profile, "VideoCodecProfile", applyCondition, mediaSource);
  876. applyConditions = false;
  877. break;
  878. }
  879. }
  880. if (applyConditions)
  881. {
  882. foreach (ProfileCondition c in i.Conditions)
  883. {
  884. conditions.Add(c);
  885. }
  886. }
  887. }
  888. }
  889. foreach (ProfileCondition i in conditions)
  890. {
  891. if (!conditionProcessor.IsVideoConditionSatisfied(i, width, height, bitDepth, videoBitrate, videoProfile, videoLevel, videoFramerate, packetLength, timestamp, isAnamorphic, isInterlaced, refFrames, numVideoStreams, numAudioStreams, videoCodecTag, isAvc))
  892. {
  893. LogConditionFailure(profile, "VideoCodecProfile", i, mediaSource);
  894. var transcodeReason = GetTranscodeReasonForFailedCondition(i);
  895. var transcodeReasons = transcodeReason.HasValue
  896. ? new List<TranscodeReason> { transcodeReason.Value }
  897. : new List<TranscodeReason> { };
  898. return new Tuple<PlayMethod?, List<TranscodeReason>>(null, transcodeReasons);
  899. }
  900. }
  901. if (audioStream != null)
  902. {
  903. string audioCodec = audioStream.Codec;
  904. if (string.IsNullOrEmpty(audioCodec))
  905. {
  906. _logger.Info("Profile: {0}, DirectPlay=false. Reason=Unknown audio codec. Path: {1}",
  907. profile.Name ?? "Unknown Profile",
  908. mediaSource.Path ?? "Unknown path");
  909. return new Tuple<PlayMethod?, List<TranscodeReason>>(null, new List<TranscodeReason> { TranscodeReason.UnknownAudioStreamInfo });
  910. }
  911. conditions = new List<ProfileCondition>();
  912. bool? isSecondaryAudio = audioStream == null ? null : mediaSource.IsSecondaryAudio(audioStream);
  913. foreach (CodecProfile i in profile.CodecProfiles)
  914. {
  915. if (i.Type == CodecType.VideoAudio && i.ContainsCodec(audioCodec, container))
  916. {
  917. bool applyConditions = true;
  918. foreach (ProfileCondition applyCondition in i.ApplyConditions)
  919. {
  920. if (!conditionProcessor.IsVideoAudioConditionSatisfied(applyCondition, audioChannels, audioBitrate, audioSampleRate, audioBitDepth, audioProfile, isSecondaryAudio))
  921. {
  922. LogConditionFailure(profile, "VideoAudioCodecProfile", applyCondition, mediaSource);
  923. applyConditions = false;
  924. break;
  925. }
  926. }
  927. if (applyConditions)
  928. {
  929. foreach (ProfileCondition c in i.Conditions)
  930. {
  931. conditions.Add(c);
  932. }
  933. }
  934. }
  935. }
  936. foreach (ProfileCondition i in conditions)
  937. {
  938. if (!conditionProcessor.IsVideoAudioConditionSatisfied(i, audioChannels, audioBitrate, audioSampleRate, audioBitDepth, audioProfile, isSecondaryAudio))
  939. {
  940. LogConditionFailure(profile, "VideoAudioCodecProfile", i, mediaSource);
  941. var transcodeReason = GetTranscodeReasonForFailedCondition(i);
  942. var transcodeReasons = transcodeReason.HasValue
  943. ? new List<TranscodeReason> { transcodeReason.Value }
  944. : new List<TranscodeReason> { };
  945. return new Tuple<PlayMethod?, List<TranscodeReason>>(null, transcodeReasons);
  946. }
  947. }
  948. }
  949. if (isEligibleForDirectStream && mediaSource.SupportsDirectStream)
  950. {
  951. return new Tuple<PlayMethod?, List<TranscodeReason>>(PlayMethod.DirectStream, new List<TranscodeReason>());
  952. }
  953. return new Tuple<PlayMethod?, List<TranscodeReason>>(null, new List<TranscodeReason> { TranscodeReason.ContainerBitrateExceedsLimit });
  954. }
  955. private void LogConditionFailure(DeviceProfile profile, string type, ProfileCondition condition, MediaSourceInfo mediaSource)
  956. {
  957. _logger.Info("Profile: {0}, DirectPlay=false. Reason={1}.{2} Condition: {3}. ConditionValue: {4}. IsRequired: {5}. Path: {6}",
  958. type,
  959. profile.Name ?? "Unknown Profile",
  960. condition.Property,
  961. condition.Condition,
  962. condition.Value ?? string.Empty,
  963. condition.IsRequired,
  964. mediaSource.Path ?? "Unknown path");
  965. }
  966. private Tuple<bool, TranscodeReason?> IsEligibleForDirectPlay(MediaSourceInfo item,
  967. long? maxBitrate,
  968. MediaStream subtitleStream,
  969. VideoOptions options,
  970. PlayMethod playMethod)
  971. {
  972. if (subtitleStream != null)
  973. {
  974. SubtitleProfile subtitleProfile = GetSubtitleProfile(subtitleStream, options.Profile.SubtitleProfiles, playMethod, null, null);
  975. if (subtitleProfile.Method != SubtitleDeliveryMethod.External && subtitleProfile.Method != SubtitleDeliveryMethod.Embed)
  976. {
  977. _logger.Info("Not eligible for {0} due to unsupported subtitles", playMethod);
  978. return new Tuple<bool, TranscodeReason?>(false, TranscodeReason.SubtitleCodecNotSupported);
  979. }
  980. }
  981. var result = IsAudioEligibleForDirectPlay(item, maxBitrate, playMethod);
  982. if (result)
  983. {
  984. return new Tuple<bool, TranscodeReason?>(result, null);
  985. }
  986. return new Tuple<bool, TranscodeReason?>(result, TranscodeReason.ContainerBitrateExceedsLimit);
  987. }
  988. public static SubtitleProfile GetSubtitleProfile(MediaStream subtitleStream, SubtitleProfile[] subtitleProfiles, PlayMethod playMethod, string transcodingSubProtocol, string transcodingContainer)
  989. {
  990. if (!subtitleStream.IsExternal && (playMethod != PlayMethod.Transcode || !string.Equals(transcodingSubProtocol, "hls", StringComparison.OrdinalIgnoreCase)))
  991. {
  992. // Look for supported embedded subs of the same format
  993. foreach (SubtitleProfile profile in subtitleProfiles)
  994. {
  995. if (!profile.SupportsLanguage(subtitleStream.Language))
  996. {
  997. continue;
  998. }
  999. if (profile.Method != SubtitleDeliveryMethod.Embed)
  1000. {
  1001. continue;
  1002. }
  1003. if (playMethod == PlayMethod.Transcode && !IsSubtitleEmbedSupported(subtitleStream, profile, transcodingSubProtocol, transcodingContainer))
  1004. {
  1005. continue;
  1006. }
  1007. if (subtitleStream.IsTextSubtitleStream == MediaStream.IsTextFormat(profile.Format) && StringHelper.EqualsIgnoreCase(profile.Format, subtitleStream.Codec))
  1008. {
  1009. return profile;
  1010. }
  1011. }
  1012. // Look for supported embedded subs of a convertible format
  1013. foreach (SubtitleProfile profile in subtitleProfiles)
  1014. {
  1015. if (!profile.SupportsLanguage(subtitleStream.Language))
  1016. {
  1017. continue;
  1018. }
  1019. if (profile.Method != SubtitleDeliveryMethod.Embed)
  1020. {
  1021. continue;
  1022. }
  1023. if (playMethod == PlayMethod.Transcode && !IsSubtitleEmbedSupported(subtitleStream, profile, transcodingSubProtocol, transcodingContainer))
  1024. {
  1025. continue;
  1026. }
  1027. if (subtitleStream.IsTextSubtitleStream && subtitleStream.SupportsSubtitleConversionTo(profile.Format))
  1028. {
  1029. return profile;
  1030. }
  1031. }
  1032. }
  1033. // Look for an external or hls profile that matches the stream type (text/graphical) and doesn't require conversion
  1034. return GetExternalSubtitleProfile(subtitleStream, subtitleProfiles, playMethod, false) ?? GetExternalSubtitleProfile(subtitleStream, subtitleProfiles, playMethod, true) ?? new SubtitleProfile
  1035. {
  1036. Method = SubtitleDeliveryMethod.Encode,
  1037. Format = subtitleStream.Codec
  1038. };
  1039. }
  1040. private static bool IsSubtitleEmbedSupported(MediaStream subtitleStream, SubtitleProfile subtitleProfile, string transcodingSubProtocol, string transcodingContainer)
  1041. {
  1042. if (string.Equals(transcodingContainer, "ts", StringComparison.OrdinalIgnoreCase))
  1043. {
  1044. return false;
  1045. }
  1046. if (string.Equals(transcodingContainer, "mpegts", StringComparison.OrdinalIgnoreCase))
  1047. {
  1048. return false;
  1049. }
  1050. if (string.Equals(transcodingContainer, "mp4", StringComparison.OrdinalIgnoreCase))
  1051. {
  1052. return false;
  1053. }
  1054. if (string.Equals(transcodingContainer, "mkv", StringComparison.OrdinalIgnoreCase))
  1055. {
  1056. return true;
  1057. }
  1058. return false;
  1059. }
  1060. private static SubtitleProfile GetExternalSubtitleProfile(MediaStream subtitleStream, SubtitleProfile[] subtitleProfiles, PlayMethod playMethod, bool allowConversion)
  1061. {
  1062. foreach (SubtitleProfile profile in subtitleProfiles)
  1063. {
  1064. if (profile.Method != SubtitleDeliveryMethod.External && profile.Method != SubtitleDeliveryMethod.Hls)
  1065. {
  1066. continue;
  1067. }
  1068. if (profile.Method == SubtitleDeliveryMethod.Hls && playMethod != PlayMethod.Transcode)
  1069. {
  1070. continue;
  1071. }
  1072. if (!profile.SupportsLanguage(subtitleStream.Language))
  1073. {
  1074. continue;
  1075. }
  1076. if ((profile.Method == SubtitleDeliveryMethod.External && subtitleStream.IsTextSubtitleStream == MediaStream.IsTextFormat(profile.Format)) ||
  1077. (profile.Method == SubtitleDeliveryMethod.Hls && subtitleStream.IsTextSubtitleStream))
  1078. {
  1079. bool requiresConversion = !StringHelper.EqualsIgnoreCase(subtitleStream.Codec, profile.Format);
  1080. if (!requiresConversion)
  1081. {
  1082. return profile;
  1083. }
  1084. if (!allowConversion)
  1085. {
  1086. continue;
  1087. }
  1088. if (subtitleStream.IsTextSubtitleStream && subtitleStream.SupportsExternalStream && subtitleStream.SupportsSubtitleConversionTo(profile.Format))
  1089. {
  1090. return profile;
  1091. }
  1092. }
  1093. }
  1094. return null;
  1095. }
  1096. private bool IsAudioEligibleForDirectPlay(MediaSourceInfo item, long? maxBitrate, PlayMethod playMethod)
  1097. {
  1098. // Don't restrict by bitrate if coming from an external domain
  1099. if (item.IsRemote)
  1100. {
  1101. return true;
  1102. }
  1103. if (!maxBitrate.HasValue)
  1104. {
  1105. _logger.Info("Cannot " + playMethod + " due to unknown supported bitrate");
  1106. return false;
  1107. }
  1108. if (!item.Bitrate.HasValue)
  1109. {
  1110. _logger.Info("Cannot " + playMethod + " due to unknown content bitrate");
  1111. return false;
  1112. }
  1113. if (item.Bitrate.Value > maxBitrate.Value)
  1114. {
  1115. _logger.Info("Bitrate exceeds " + playMethod + " limit: media bitrate: {0}, max bitrate: {1}", item.Bitrate.Value.ToString(CultureInfo.InvariantCulture), maxBitrate.Value.ToString(CultureInfo.InvariantCulture));
  1116. return false;
  1117. }
  1118. return true;
  1119. }
  1120. private void ValidateInput(VideoOptions options)
  1121. {
  1122. ValidateAudioInput(options);
  1123. if (options.AudioStreamIndex.HasValue && string.IsNullOrEmpty(options.MediaSourceId))
  1124. {
  1125. throw new ArgumentException("MediaSourceId is required when a specific audio stream is requested");
  1126. }
  1127. if (options.SubtitleStreamIndex.HasValue && string.IsNullOrEmpty(options.MediaSourceId))
  1128. {
  1129. throw new ArgumentException("MediaSourceId is required when a specific subtitle stream is requested");
  1130. }
  1131. }
  1132. private void ValidateAudioInput(AudioOptions options)
  1133. {
  1134. if (string.IsNullOrEmpty(options.ItemId))
  1135. {
  1136. throw new ArgumentException("ItemId is required");
  1137. }
  1138. if (string.IsNullOrEmpty(options.DeviceId))
  1139. {
  1140. throw new ArgumentException("DeviceId is required");
  1141. }
  1142. if (options.Profile == null)
  1143. {
  1144. throw new ArgumentException("Profile is required");
  1145. }
  1146. if (options.MediaSources == null)
  1147. {
  1148. throw new ArgumentException("MediaSources is required");
  1149. }
  1150. }
  1151. private void ApplyTranscodingConditions(StreamInfo item, IEnumerable<ProfileCondition> conditions)
  1152. {
  1153. foreach (ProfileCondition condition in conditions)
  1154. {
  1155. string value = condition.Value;
  1156. if (string.IsNullOrEmpty(value))
  1157. {
  1158. continue;
  1159. }
  1160. // No way to express this
  1161. if (condition.Condition == ProfileConditionType.GreaterThanEqual)
  1162. {
  1163. continue;
  1164. }
  1165. switch (condition.Property)
  1166. {
  1167. case ProfileConditionValue.AudioBitrate:
  1168. {
  1169. int num;
  1170. if (int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out num))
  1171. {
  1172. item.AudioBitrate = num;
  1173. }
  1174. break;
  1175. }
  1176. case ProfileConditionValue.AudioChannels:
  1177. {
  1178. int num;
  1179. if (int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out num))
  1180. {
  1181. item.MaxAudioChannels = num;
  1182. }
  1183. break;
  1184. }
  1185. case ProfileConditionValue.IsAvc:
  1186. {
  1187. bool isAvc;
  1188. if (bool.TryParse(value, out isAvc))
  1189. {
  1190. if (isAvc && condition.Condition == ProfileConditionType.Equals)
  1191. {
  1192. item.RequireAvc = true;
  1193. }
  1194. else if (!isAvc && condition.Condition == ProfileConditionType.NotEquals)
  1195. {
  1196. item.RequireAvc = true;
  1197. }
  1198. }
  1199. break;
  1200. }
  1201. case ProfileConditionValue.IsAnamorphic:
  1202. {
  1203. bool isAnamorphic;
  1204. if (bool.TryParse(value, out isAnamorphic))
  1205. {
  1206. if (isAnamorphic && condition.Condition == ProfileConditionType.Equals)
  1207. {
  1208. item.RequireNonAnamorphic = true;
  1209. }
  1210. else if (!isAnamorphic && condition.Condition == ProfileConditionType.NotEquals)
  1211. {
  1212. item.RequireNonAnamorphic = true;
  1213. }
  1214. }
  1215. break;
  1216. }
  1217. case ProfileConditionValue.IsInterlaced:
  1218. {
  1219. bool isInterlaced;
  1220. if (bool.TryParse(value, out isInterlaced))
  1221. {
  1222. if (!isInterlaced && condition.Condition == ProfileConditionType.Equals)
  1223. {
  1224. item.DeInterlace = true;
  1225. }
  1226. else if (isInterlaced && condition.Condition == ProfileConditionType.NotEquals)
  1227. {
  1228. item.DeInterlace = true;
  1229. }
  1230. }
  1231. break;
  1232. }
  1233. case ProfileConditionValue.AudioProfile:
  1234. case ProfileConditionValue.Has64BitOffsets:
  1235. case ProfileConditionValue.PacketLength:
  1236. case ProfileConditionValue.NumAudioStreams:
  1237. case ProfileConditionValue.NumVideoStreams:
  1238. case ProfileConditionValue.IsSecondaryAudio:
  1239. case ProfileConditionValue.VideoTimestamp:
  1240. {
  1241. // Not supported yet
  1242. break;
  1243. }
  1244. case ProfileConditionValue.RefFrames:
  1245. {
  1246. int num;
  1247. if (int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out num))
  1248. {
  1249. item.MaxRefFrames = num;
  1250. }
  1251. break;
  1252. }
  1253. case ProfileConditionValue.VideoBitDepth:
  1254. {
  1255. int num;
  1256. if (int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out num))
  1257. {
  1258. item.MaxVideoBitDepth = num;
  1259. }
  1260. break;
  1261. }
  1262. case ProfileConditionValue.VideoProfile:
  1263. {
  1264. item.VideoProfile = (value ?? string.Empty).Split('|')[0];
  1265. break;
  1266. }
  1267. case ProfileConditionValue.Height:
  1268. {
  1269. int num;
  1270. if (int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out num))
  1271. {
  1272. item.MaxHeight = num;
  1273. }
  1274. break;
  1275. }
  1276. case ProfileConditionValue.VideoBitrate:
  1277. {
  1278. int num;
  1279. if (int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out num))
  1280. {
  1281. item.VideoBitrate = num;
  1282. }
  1283. break;
  1284. }
  1285. case ProfileConditionValue.VideoFramerate:
  1286. {
  1287. float num;
  1288. if (float.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out num))
  1289. {
  1290. item.MaxFramerate = num;
  1291. }
  1292. break;
  1293. }
  1294. case ProfileConditionValue.VideoLevel:
  1295. {
  1296. int num;
  1297. if (int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out num))
  1298. {
  1299. item.VideoLevel = num;
  1300. }
  1301. break;
  1302. }
  1303. case ProfileConditionValue.Width:
  1304. {
  1305. int num;
  1306. if (int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out num))
  1307. {
  1308. item.MaxWidth = num;
  1309. }
  1310. break;
  1311. }
  1312. default:
  1313. break;
  1314. }
  1315. }
  1316. }
  1317. private bool IsAudioDirectPlaySupported(DirectPlayProfile profile, MediaSourceInfo item, MediaStream audioStream)
  1318. {
  1319. if (profile.Container.Length > 0)
  1320. {
  1321. // Check container type
  1322. string mediaContainer = item.Container ?? string.Empty;
  1323. bool any = false;
  1324. foreach (string i in profile.GetContainers())
  1325. {
  1326. if (StringHelper.EqualsIgnoreCase(i, mediaContainer))
  1327. {
  1328. any = true;
  1329. break;
  1330. }
  1331. }
  1332. if (!any)
  1333. {
  1334. return false;
  1335. }
  1336. }
  1337. // Check audio codec
  1338. List<string> audioCodecs = profile.GetAudioCodecs();
  1339. if (audioCodecs.Count > 0)
  1340. {
  1341. // Check audio codecs
  1342. string audioCodec = audioStream == null ? null : audioStream.Codec;
  1343. if (string.IsNullOrEmpty(audioCodec) || !ListHelper.ContainsIgnoreCase(audioCodecs, audioCodec))
  1344. {
  1345. return false;
  1346. }
  1347. }
  1348. return true;
  1349. }
  1350. private bool IsVideoDirectPlaySupported(DirectPlayProfile profile, MediaSourceInfo item, MediaStream videoStream, MediaStream audioStream)
  1351. {
  1352. if (profile.Container.Length > 0)
  1353. {
  1354. // Check container type
  1355. string mediaContainer = item.Container ?? string.Empty;
  1356. bool any = false;
  1357. foreach (string i in profile.GetContainers())
  1358. {
  1359. if (StringHelper.EqualsIgnoreCase(i, mediaContainer))
  1360. {
  1361. any = true;
  1362. break;
  1363. }
  1364. }
  1365. if (!any)
  1366. {
  1367. return false;
  1368. }
  1369. }
  1370. // Check video codec
  1371. List<string> videoCodecs = profile.GetVideoCodecs();
  1372. if (videoCodecs.Count > 0)
  1373. {
  1374. string videoCodec = videoStream == null ? null : videoStream.Codec;
  1375. if (string.IsNullOrEmpty(videoCodec) || !ListHelper.ContainsIgnoreCase(videoCodecs, videoCodec))
  1376. {
  1377. return false;
  1378. }
  1379. }
  1380. // Check audio codec
  1381. List<string> audioCodecs = profile.GetAudioCodecs();
  1382. if (audioCodecs.Count > 0)
  1383. {
  1384. // Check audio codecs
  1385. string audioCodec = audioStream == null ? null : audioStream.Codec;
  1386. if (string.IsNullOrEmpty(audioCodec) || !ListHelper.ContainsIgnoreCase(audioCodecs, audioCodec))
  1387. {
  1388. return false;
  1389. }
  1390. }
  1391. return true;
  1392. }
  1393. }
  1394. }