StreamBuilder.cs 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589
  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. // Check container type
  411. if (profile.SupportsContainer(item.Container))
  412. {
  413. containerSupported = true;
  414. if (videoStream != null)
  415. {
  416. // Check video codec
  417. List<string> videoCodecs = profile.GetVideoCodecs();
  418. if (videoCodecs.Count > 0)
  419. {
  420. string videoCodec = videoStream.Codec;
  421. if (!string.IsNullOrEmpty(videoCodec) && ListHelper.ContainsIgnoreCase(videoCodecs, videoCodec))
  422. {
  423. videoSupported = true;
  424. }
  425. }
  426. else
  427. {
  428. videoSupported = true;
  429. }
  430. }
  431. if (audioStream != null)
  432. {
  433. // Check audio codec
  434. List<string> audioCodecs = profile.GetAudioCodecs();
  435. if (audioCodecs.Count > 0)
  436. {
  437. string audioCodec = audioStream.Codec;
  438. if (!string.IsNullOrEmpty(audioCodec) && ListHelper.ContainsIgnoreCase(audioCodecs, audioCodec))
  439. {
  440. audioSupported = true;
  441. }
  442. }
  443. else
  444. {
  445. audioSupported = true;
  446. }
  447. }
  448. }
  449. }
  450. if (!containerSupported)
  451. {
  452. list.Add(TranscodeReason.ContainerNotSupported);
  453. }
  454. if (videoStream != null && !videoSupported)
  455. {
  456. list.Add(TranscodeReason.VideoCodecNotSupported);
  457. }
  458. if (audioStream != null && !audioSupported)
  459. {
  460. list.Add(TranscodeReason.AudioCodecNotSupported);
  461. }
  462. return list;
  463. }
  464. private int? GetDefaultSubtitleStreamIndex(MediaSourceInfo item, SubtitleProfile[] subtitleProfiles)
  465. {
  466. int highestScore = -1;
  467. foreach (MediaStream stream in item.MediaStreams)
  468. {
  469. if (stream.Type == MediaStreamType.Subtitle && stream.Score.HasValue)
  470. {
  471. if (stream.Score.Value > highestScore)
  472. {
  473. highestScore = stream.Score.Value;
  474. }
  475. }
  476. }
  477. List<MediaStream> topStreams = new List<MediaStream>();
  478. foreach (MediaStream stream in item.MediaStreams)
  479. {
  480. if (stream.Type == MediaStreamType.Subtitle && stream.Score.HasValue && stream.Score.Value == highestScore)
  481. {
  482. topStreams.Add(stream);
  483. }
  484. }
  485. // If multiple streams have an equal score, try to pick the most efficient one
  486. if (topStreams.Count > 1)
  487. {
  488. foreach (MediaStream stream in topStreams)
  489. {
  490. foreach (SubtitleProfile profile in subtitleProfiles)
  491. {
  492. if (profile.Method == SubtitleDeliveryMethod.External && StringHelper.EqualsIgnoreCase(profile.Format, stream.Codec))
  493. {
  494. return stream.Index;
  495. }
  496. }
  497. }
  498. }
  499. // If no optimization panned out, just use the original default
  500. return item.DefaultSubtitleStreamIndex;
  501. }
  502. private StreamInfo BuildVideoItem(MediaSourceInfo item, VideoOptions options)
  503. {
  504. if (item == null)
  505. {
  506. throw new ArgumentNullException("item");
  507. }
  508. List<TranscodeReason> transcodeReasons = new List<TranscodeReason>();
  509. StreamInfo playlistItem = new StreamInfo
  510. {
  511. ItemId = options.ItemId,
  512. MediaType = DlnaProfileType.Video,
  513. MediaSource = item,
  514. RunTimeTicks = item.RunTimeTicks,
  515. Context = options.Context,
  516. DeviceProfile = options.Profile
  517. };
  518. playlistItem.SubtitleStreamIndex = options.SubtitleStreamIndex ?? GetDefaultSubtitleStreamIndex(item, options.Profile.SubtitleProfiles);
  519. MediaStream subtitleStream = playlistItem.SubtitleStreamIndex.HasValue ? item.GetMediaStream(MediaStreamType.Subtitle, playlistItem.SubtitleStreamIndex.Value) : null;
  520. MediaStream audioStream = item.GetDefaultAudioStream(options.AudioStreamIndex ?? item.DefaultAudioStreamIndex);
  521. int? audioStreamIndex = null;
  522. if (audioStream != null)
  523. {
  524. audioStreamIndex = audioStream.Index;
  525. }
  526. MediaStream videoStream = item.VideoStream;
  527. // TODO: This doesn't accout for situation of device being able to handle media bitrate, but wifi connection not fast enough
  528. var directPlayEligibilityResult = IsEligibleForDirectPlay(item, GetBitrateForDirectPlayCheck(item, options, true), subtitleStream, options, PlayMethod.DirectPlay);
  529. var directStreamEligibilityResult = IsEligibleForDirectPlay(item, options.GetMaxBitrate(false), subtitleStream, options, PlayMethod.DirectStream);
  530. bool isEligibleForDirectPlay = options.EnableDirectPlay && (options.ForceDirectPlay || directPlayEligibilityResult.Item1);
  531. bool isEligibleForDirectStream = options.EnableDirectStream && (options.ForceDirectStream || directStreamEligibilityResult.Item1);
  532. _logger.Info("Profile: {0}, Path: {1}, isEligibleForDirectPlay: {2}, isEligibleForDirectStream: {3}",
  533. options.Profile.Name ?? "Unknown Profile",
  534. item.Path ?? "Unknown path",
  535. isEligibleForDirectPlay,
  536. isEligibleForDirectStream);
  537. if (isEligibleForDirectPlay || isEligibleForDirectStream)
  538. {
  539. // See if it can be direct played
  540. var directPlayInfo = GetVideoDirectPlayProfile(options, item, videoStream, audioStream, isEligibleForDirectPlay, isEligibleForDirectStream);
  541. var directPlay = directPlayInfo.Item1;
  542. if (directPlay != null)
  543. {
  544. playlistItem.PlayMethod = directPlay.Value;
  545. playlistItem.Container = item.Container;
  546. if (subtitleStream != null)
  547. {
  548. SubtitleProfile subtitleProfile = GetSubtitleProfile(subtitleStream, options.Profile.SubtitleProfiles, directPlay.Value, null, null);
  549. playlistItem.SubtitleDeliveryMethod = subtitleProfile.Method;
  550. playlistItem.SubtitleFormat = subtitleProfile.Format;
  551. }
  552. return playlistItem;
  553. }
  554. transcodeReasons.AddRange(directPlayInfo.Item2);
  555. }
  556. if (directPlayEligibilityResult.Item2.HasValue)
  557. {
  558. transcodeReasons.Add(directPlayEligibilityResult.Item2.Value);
  559. }
  560. if (directStreamEligibilityResult.Item2.HasValue)
  561. {
  562. transcodeReasons.Add(directStreamEligibilityResult.Item2.Value);
  563. }
  564. // Can't direct play, find the transcoding profile
  565. TranscodingProfile transcodingProfile = null;
  566. foreach (TranscodingProfile i in options.Profile.TranscodingProfiles)
  567. {
  568. if (i.Type == playlistItem.MediaType && i.Context == options.Context)
  569. {
  570. transcodingProfile = i;
  571. break;
  572. }
  573. }
  574. if (transcodingProfile != null)
  575. {
  576. if (!item.SupportsTranscoding)
  577. {
  578. return null;
  579. }
  580. if (subtitleStream != null)
  581. {
  582. SubtitleProfile subtitleProfile = GetSubtitleProfile(subtitleStream, options.Profile.SubtitleProfiles, PlayMethod.Transcode, transcodingProfile.Protocol, transcodingProfile.Container);
  583. playlistItem.SubtitleDeliveryMethod = subtitleProfile.Method;
  584. playlistItem.SubtitleFormat = subtitleProfile.Format;
  585. playlistItem.SubtitleCodecs = new[] { subtitleProfile.Format };
  586. }
  587. playlistItem.PlayMethod = PlayMethod.Transcode;
  588. playlistItem.Container = transcodingProfile.Container;
  589. playlistItem.EstimateContentLength = transcodingProfile.EstimateContentLength;
  590. playlistItem.TranscodeSeekInfo = transcodingProfile.TranscodeSeekInfo;
  591. playlistItem.AudioCodecs = transcodingProfile.AudioCodec.Split(',');
  592. playlistItem.VideoCodecs = transcodingProfile.VideoCodec.Split(',');
  593. playlistItem.CopyTimestamps = transcodingProfile.CopyTimestamps;
  594. playlistItem.EnableSubtitlesInManifest = transcodingProfile.EnableSubtitlesInManifest;
  595. playlistItem.BreakOnNonKeyFrames = transcodingProfile.BreakOnNonKeyFrames;
  596. if (transcodingProfile.MinSegments > 0)
  597. {
  598. playlistItem.MinSegments = transcodingProfile.MinSegments;
  599. }
  600. if (transcodingProfile.SegmentLength > 0)
  601. {
  602. playlistItem.SegmentLength = transcodingProfile.SegmentLength;
  603. }
  604. if (!string.IsNullOrEmpty(transcodingProfile.MaxAudioChannels))
  605. {
  606. int transcodingMaxAudioChannels;
  607. if (int.TryParse(transcodingProfile.MaxAudioChannels, NumberStyles.Any, CultureInfo.InvariantCulture, out transcodingMaxAudioChannels))
  608. {
  609. playlistItem.TranscodingMaxAudioChannels = transcodingMaxAudioChannels;
  610. }
  611. }
  612. playlistItem.SubProtocol = transcodingProfile.Protocol;
  613. playlistItem.AudioStreamIndex = audioStreamIndex;
  614. ConditionProcessor conditionProcessor = new ConditionProcessor();
  615. List<ProfileCondition> videoTranscodingConditions = new List<ProfileCondition>();
  616. foreach (CodecProfile i in options.Profile.CodecProfiles)
  617. {
  618. if (i.Type == CodecType.Video && i.ContainsCodec(transcodingProfile.VideoCodec, transcodingProfile.Container))
  619. {
  620. bool applyConditions = true;
  621. foreach (ProfileCondition applyCondition in i.ApplyConditions)
  622. {
  623. bool? isSecondaryAudio = audioStream == null ? null : item.IsSecondaryAudio(audioStream);
  624. int? inputAudioBitrate = audioStream == null ? null : audioStream.BitRate;
  625. int? audioChannels = audioStream == null ? null : audioStream.Channels;
  626. string audioProfile = audioStream == null ? null : audioStream.Profile;
  627. int? inputAudioSampleRate = audioStream == null ? null : audioStream.SampleRate;
  628. int? inputAudioBitDepth = audioStream == null ? null : audioStream.BitDepth;
  629. if (!conditionProcessor.IsVideoAudioConditionSatisfied(applyCondition, audioChannels, inputAudioBitrate, inputAudioSampleRate, inputAudioBitDepth, audioProfile, isSecondaryAudio))
  630. {
  631. LogConditionFailure(options.Profile, "AudioCodecProfile", applyCondition, item);
  632. applyConditions = false;
  633. break;
  634. }
  635. }
  636. if (applyConditions)
  637. {
  638. foreach (ProfileCondition c in i.Conditions)
  639. {
  640. videoTranscodingConditions.Add(c);
  641. }
  642. break;
  643. }
  644. }
  645. }
  646. ApplyTranscodingConditions(playlistItem, videoTranscodingConditions);
  647. List<ProfileCondition> audioTranscodingConditions = new List<ProfileCondition>();
  648. foreach (CodecProfile i in options.Profile.CodecProfiles)
  649. {
  650. if (i.Type == CodecType.VideoAudio && i.ContainsCodec(playlistItem.TargetAudioCodec, transcodingProfile.Container))
  651. {
  652. bool applyConditions = true;
  653. foreach (ProfileCondition applyCondition in i.ApplyConditions)
  654. {
  655. int? width = videoStream == null ? null : videoStream.Width;
  656. int? height = videoStream == null ? null : videoStream.Height;
  657. int? bitDepth = videoStream == null ? null : videoStream.BitDepth;
  658. int? videoBitrate = videoStream == null ? null : videoStream.BitRate;
  659. double? videoLevel = videoStream == null ? null : videoStream.Level;
  660. string videoProfile = videoStream == null ? null : videoStream.Profile;
  661. float? videoFramerate = videoStream == null ? null : videoStream.AverageFrameRate ?? videoStream.AverageFrameRate;
  662. bool? isAnamorphic = videoStream == null ? null : videoStream.IsAnamorphic;
  663. bool? isInterlaced = videoStream == null ? (bool?)null : videoStream.IsInterlaced;
  664. string videoCodecTag = videoStream == null ? null : videoStream.CodecTag;
  665. bool? isAvc = videoStream == null ? null : videoStream.IsAVC;
  666. TransportStreamTimestamp? timestamp = videoStream == null ? TransportStreamTimestamp.None : item.Timestamp;
  667. int? packetLength = videoStream == null ? null : videoStream.PacketLength;
  668. int? refFrames = videoStream == null ? null : videoStream.RefFrames;
  669. int? numAudioStreams = item.GetStreamCount(MediaStreamType.Audio);
  670. int? numVideoStreams = item.GetStreamCount(MediaStreamType.Video);
  671. if (!conditionProcessor.IsVideoConditionSatisfied(applyCondition, width, height, bitDepth, videoBitrate, videoProfile, videoLevel, videoFramerate, packetLength, timestamp, isAnamorphic, isInterlaced, refFrames, numVideoStreams, numAudioStreams, videoCodecTag, isAvc))
  672. {
  673. LogConditionFailure(options.Profile, "VideoCodecProfile", applyCondition, item);
  674. applyConditions = false;
  675. break;
  676. }
  677. }
  678. if (applyConditions)
  679. {
  680. foreach (ProfileCondition c in i.Conditions)
  681. {
  682. audioTranscodingConditions.Add(c);
  683. }
  684. break;
  685. }
  686. }
  687. }
  688. ApplyTranscodingConditions(playlistItem, audioTranscodingConditions);
  689. // Honor requested max channels
  690. if (options.MaxAudioChannels.HasValue)
  691. {
  692. int currentValue = playlistItem.MaxAudioChannels ?? options.MaxAudioChannels.Value;
  693. playlistItem.MaxAudioChannels = Math.Min(options.MaxAudioChannels.Value, currentValue);
  694. }
  695. int audioBitrate = GetAudioBitrate(playlistItem.SubProtocol, options.GetMaxBitrate(false), playlistItem.TargetAudioChannels, playlistItem.TargetAudioCodec, audioStream);
  696. playlistItem.AudioBitrate = Math.Min(playlistItem.AudioBitrate ?? audioBitrate, audioBitrate);
  697. var maxBitrateSetting = options.GetMaxBitrate(false);
  698. // Honor max rate
  699. if (maxBitrateSetting.HasValue)
  700. {
  701. var videoBitrate = maxBitrateSetting.Value;
  702. if (playlistItem.AudioBitrate.HasValue)
  703. {
  704. videoBitrate -= playlistItem.AudioBitrate.Value;
  705. }
  706. // Make sure the video bitrate is lower than bitrate settings but at least 64k
  707. long currentValue = playlistItem.VideoBitrate ?? videoBitrate;
  708. var longBitrate = Math.Max(Math.Min(videoBitrate, currentValue), 64000);
  709. playlistItem.VideoBitrate = longBitrate > int.MaxValue ? int.MaxValue : Convert.ToInt32(longBitrate);
  710. }
  711. }
  712. playlistItem.TranscodeReasons = transcodeReasons;
  713. return playlistItem;
  714. }
  715. private int GetDefaultAudioBitrateIfUnknown(MediaStream audioStream)
  716. {
  717. if ((audioStream.Channels ?? 0) >= 6)
  718. {
  719. return 384000;
  720. }
  721. return 192000;
  722. }
  723. private int GetAudioBitrate(string subProtocol, long? maxTotalBitrate, int? targetAudioChannels, string targetAudioCodec, MediaStream audioStream)
  724. {
  725. int defaultBitrate = audioStream == null ? 192000 : audioStream.BitRate ?? GetDefaultAudioBitrateIfUnknown(audioStream);
  726. // Reduce the bitrate if we're downmixing
  727. if (targetAudioChannels.HasValue && audioStream != null && audioStream.Channels.HasValue && targetAudioChannels.Value < audioStream.Channels.Value)
  728. {
  729. defaultBitrate = StringHelper.EqualsIgnoreCase(targetAudioCodec, "ac3") ? 192000 : 128000;
  730. }
  731. if (StringHelper.EqualsIgnoreCase(subProtocol, "hls"))
  732. {
  733. defaultBitrate = Math.Min(384000, defaultBitrate);
  734. }
  735. else
  736. {
  737. defaultBitrate = Math.Min(448000, defaultBitrate);
  738. }
  739. int encoderAudioBitrateLimit = int.MaxValue;
  740. if (audioStream != null)
  741. {
  742. // Seeing webm encoding failures when source has 1 audio channel and 22k bitrate.
  743. // Any attempts to transcode over 64k will fail
  744. if (audioStream.Channels.HasValue &&
  745. audioStream.Channels.Value == 1)
  746. {
  747. if ((audioStream.BitRate ?? 0) < 64000)
  748. {
  749. encoderAudioBitrateLimit = 64000;
  750. }
  751. }
  752. }
  753. if (maxTotalBitrate.HasValue)
  754. {
  755. if (maxTotalBitrate.Value < 640000)
  756. {
  757. defaultBitrate = Math.Min(128000, defaultBitrate);
  758. }
  759. }
  760. return Math.Min(defaultBitrate, encoderAudioBitrateLimit);
  761. }
  762. private Tuple<PlayMethod?, List<TranscodeReason>> GetVideoDirectPlayProfile(VideoOptions options,
  763. MediaSourceInfo mediaSource,
  764. MediaStream videoStream,
  765. MediaStream audioStream,
  766. bool isEligibleForDirectPlay,
  767. bool isEligibleForDirectStream)
  768. {
  769. DeviceProfile profile = options.Profile;
  770. if (options.ForceDirectPlay)
  771. {
  772. return new Tuple<PlayMethod?, List<TranscodeReason>>(PlayMethod.DirectPlay, new List<TranscodeReason>());
  773. }
  774. if (options.ForceDirectStream)
  775. {
  776. return new Tuple<PlayMethod?, List<TranscodeReason>>(PlayMethod.DirectStream, new List<TranscodeReason>());
  777. }
  778. if (videoStream == null)
  779. {
  780. _logger.Info("Profile: {0}, Cannot direct stream with no known video stream. Path: {1}",
  781. profile.Name ?? "Unknown Profile",
  782. mediaSource.Path ?? "Unknown path");
  783. return new Tuple<PlayMethod?, List<TranscodeReason>>(null, new List<TranscodeReason> { TranscodeReason.UnknownVideoStreamInfo });
  784. }
  785. // See if it can be direct played
  786. DirectPlayProfile directPlay = null;
  787. foreach (DirectPlayProfile i in profile.DirectPlayProfiles)
  788. {
  789. if (i.Type == DlnaProfileType.Video && IsVideoDirectPlaySupported(i, mediaSource, videoStream, audioStream))
  790. {
  791. directPlay = i;
  792. break;
  793. }
  794. }
  795. if (directPlay == null)
  796. {
  797. _logger.Info("Profile: {0}, No direct play profiles found for Path: {1}",
  798. profile.Name ?? "Unknown Profile",
  799. mediaSource.Path ?? "Unknown path");
  800. return new Tuple<PlayMethod?, List<TranscodeReason>>(null, GetTranscodeReasonsFromDirectPlayProfile(mediaSource, videoStream, audioStream, profile.DirectPlayProfiles));
  801. }
  802. string container = mediaSource.Container;
  803. List<ProfileCondition> conditions = new List<ProfileCondition>();
  804. foreach (ContainerProfile i in profile.ContainerProfiles)
  805. {
  806. if (i.Type == DlnaProfileType.Video &&
  807. i.ContainsContainer(container))
  808. {
  809. foreach (ProfileCondition c in i.Conditions)
  810. {
  811. conditions.Add(c);
  812. }
  813. }
  814. }
  815. ConditionProcessor conditionProcessor = new ConditionProcessor();
  816. int? width = videoStream == null ? null : videoStream.Width;
  817. int? height = videoStream == null ? null : videoStream.Height;
  818. int? bitDepth = videoStream == null ? null : videoStream.BitDepth;
  819. int? videoBitrate = videoStream == null ? null : videoStream.BitRate;
  820. double? videoLevel = videoStream == null ? null : videoStream.Level;
  821. string videoProfile = videoStream == null ? null : videoStream.Profile;
  822. float? videoFramerate = videoStream == null ? null : videoStream.AverageFrameRate ?? videoStream.AverageFrameRate;
  823. bool? isAnamorphic = videoStream == null ? null : videoStream.IsAnamorphic;
  824. bool? isInterlaced = videoStream == null ? (bool?)null : videoStream.IsInterlaced;
  825. string videoCodecTag = videoStream == null ? null : videoStream.CodecTag;
  826. bool? isAvc = videoStream == null ? null : videoStream.IsAVC;
  827. int? audioBitrate = audioStream == null ? null : audioStream.BitRate;
  828. int? audioChannels = audioStream == null ? null : audioStream.Channels;
  829. string audioProfile = audioStream == null ? null : audioStream.Profile;
  830. int? audioSampleRate = audioStream == null ? null : audioStream.SampleRate;
  831. int? audioBitDepth = audioStream == null ? null : audioStream.BitDepth;
  832. TransportStreamTimestamp? timestamp = videoStream == null ? TransportStreamTimestamp.None : mediaSource.Timestamp;
  833. int? packetLength = videoStream == null ? null : videoStream.PacketLength;
  834. int? refFrames = videoStream == null ? null : videoStream.RefFrames;
  835. int? numAudioStreams = mediaSource.GetStreamCount(MediaStreamType.Audio);
  836. int? numVideoStreams = mediaSource.GetStreamCount(MediaStreamType.Video);
  837. // Check container conditions
  838. foreach (ProfileCondition i in conditions)
  839. {
  840. if (!conditionProcessor.IsVideoConditionSatisfied(i, width, height, bitDepth, videoBitrate, videoProfile, videoLevel, videoFramerate, packetLength, timestamp, isAnamorphic, isInterlaced, refFrames, numVideoStreams, numAudioStreams, videoCodecTag, isAvc))
  841. {
  842. LogConditionFailure(profile, "VideoContainerProfile", i, mediaSource);
  843. var transcodeReason = GetTranscodeReasonForFailedCondition(i);
  844. var transcodeReasons = transcodeReason.HasValue
  845. ? new List<TranscodeReason> { transcodeReason.Value }
  846. : new List<TranscodeReason> { };
  847. return new Tuple<PlayMethod?, List<TranscodeReason>>(null, transcodeReasons);
  848. }
  849. }
  850. string videoCodec = videoStream == null ? null : videoStream.Codec;
  851. if (string.IsNullOrEmpty(videoCodec))
  852. {
  853. _logger.Info("Profile: {0}, DirectPlay=false. Reason=Unknown video codec. Path: {1}",
  854. profile.Name ?? "Unknown Profile",
  855. mediaSource.Path ?? "Unknown path");
  856. return new Tuple<PlayMethod?, List<TranscodeReason>>(null, new List<TranscodeReason> { TranscodeReason.UnknownVideoStreamInfo });
  857. }
  858. conditions = new List<ProfileCondition>();
  859. foreach (CodecProfile i in profile.CodecProfiles)
  860. {
  861. if (i.Type == CodecType.Video && i.ContainsCodec(videoCodec, container))
  862. {
  863. bool applyConditions = true;
  864. foreach (ProfileCondition applyCondition in i.ApplyConditions)
  865. {
  866. if (!conditionProcessor.IsVideoConditionSatisfied(applyCondition, width, height, bitDepth, videoBitrate, videoProfile, videoLevel, videoFramerate, packetLength, timestamp, isAnamorphic, isInterlaced, refFrames, numVideoStreams, numAudioStreams, videoCodecTag, isAvc))
  867. {
  868. LogConditionFailure(profile, "VideoCodecProfile", applyCondition, mediaSource);
  869. applyConditions = false;
  870. break;
  871. }
  872. }
  873. if (applyConditions)
  874. {
  875. foreach (ProfileCondition c in i.Conditions)
  876. {
  877. conditions.Add(c);
  878. }
  879. }
  880. }
  881. }
  882. foreach (ProfileCondition i in conditions)
  883. {
  884. if (!conditionProcessor.IsVideoConditionSatisfied(i, width, height, bitDepth, videoBitrate, videoProfile, videoLevel, videoFramerate, packetLength, timestamp, isAnamorphic, isInterlaced, refFrames, numVideoStreams, numAudioStreams, videoCodecTag, isAvc))
  885. {
  886. LogConditionFailure(profile, "VideoCodecProfile", i, mediaSource);
  887. var transcodeReason = GetTranscodeReasonForFailedCondition(i);
  888. var transcodeReasons = transcodeReason.HasValue
  889. ? new List<TranscodeReason> { transcodeReason.Value }
  890. : new List<TranscodeReason> { };
  891. return new Tuple<PlayMethod?, List<TranscodeReason>>(null, transcodeReasons);
  892. }
  893. }
  894. if (audioStream != null)
  895. {
  896. string audioCodec = audioStream.Codec;
  897. if (string.IsNullOrEmpty(audioCodec))
  898. {
  899. _logger.Info("Profile: {0}, DirectPlay=false. Reason=Unknown audio codec. Path: {1}",
  900. profile.Name ?? "Unknown Profile",
  901. mediaSource.Path ?? "Unknown path");
  902. return new Tuple<PlayMethod?, List<TranscodeReason>>(null, new List<TranscodeReason> { TranscodeReason.UnknownAudioStreamInfo });
  903. }
  904. conditions = new List<ProfileCondition>();
  905. bool? isSecondaryAudio = audioStream == null ? null : mediaSource.IsSecondaryAudio(audioStream);
  906. foreach (CodecProfile i in profile.CodecProfiles)
  907. {
  908. if (i.Type == CodecType.VideoAudio && i.ContainsCodec(audioCodec, container))
  909. {
  910. bool applyConditions = true;
  911. foreach (ProfileCondition applyCondition in i.ApplyConditions)
  912. {
  913. if (!conditionProcessor.IsVideoAudioConditionSatisfied(applyCondition, audioChannels, audioBitrate, audioSampleRate, audioBitDepth, audioProfile, isSecondaryAudio))
  914. {
  915. LogConditionFailure(profile, "VideoAudioCodecProfile", applyCondition, mediaSource);
  916. applyConditions = false;
  917. break;
  918. }
  919. }
  920. if (applyConditions)
  921. {
  922. foreach (ProfileCondition c in i.Conditions)
  923. {
  924. conditions.Add(c);
  925. }
  926. }
  927. }
  928. }
  929. foreach (ProfileCondition i in conditions)
  930. {
  931. if (!conditionProcessor.IsVideoAudioConditionSatisfied(i, audioChannels, audioBitrate, audioSampleRate, audioBitDepth, audioProfile, isSecondaryAudio))
  932. {
  933. LogConditionFailure(profile, "VideoAudioCodecProfile", i, mediaSource);
  934. var transcodeReason = GetTranscodeReasonForFailedCondition(i);
  935. var transcodeReasons = transcodeReason.HasValue
  936. ? new List<TranscodeReason> { transcodeReason.Value }
  937. : new List<TranscodeReason> { };
  938. return new Tuple<PlayMethod?, List<TranscodeReason>>(null, transcodeReasons);
  939. }
  940. }
  941. }
  942. if (isEligibleForDirectStream && mediaSource.SupportsDirectStream)
  943. {
  944. return new Tuple<PlayMethod?, List<TranscodeReason>>(PlayMethod.DirectStream, new List<TranscodeReason>());
  945. }
  946. return new Tuple<PlayMethod?, List<TranscodeReason>>(null, new List<TranscodeReason> { TranscodeReason.ContainerBitrateExceedsLimit });
  947. }
  948. private void LogConditionFailure(DeviceProfile profile, string type, ProfileCondition condition, MediaSourceInfo mediaSource)
  949. {
  950. _logger.Info("Profile: {0}, DirectPlay=false. Reason={1}.{2} Condition: {3}. ConditionValue: {4}. IsRequired: {5}. Path: {6}",
  951. type,
  952. profile.Name ?? "Unknown Profile",
  953. condition.Property,
  954. condition.Condition,
  955. condition.Value ?? string.Empty,
  956. condition.IsRequired,
  957. mediaSource.Path ?? "Unknown path");
  958. }
  959. private Tuple<bool, TranscodeReason?> IsEligibleForDirectPlay(MediaSourceInfo item,
  960. long? maxBitrate,
  961. MediaStream subtitleStream,
  962. VideoOptions options,
  963. PlayMethod playMethod)
  964. {
  965. if (subtitleStream != null)
  966. {
  967. SubtitleProfile subtitleProfile = GetSubtitleProfile(subtitleStream, options.Profile.SubtitleProfiles, playMethod, null, null);
  968. if (subtitleProfile.Method != SubtitleDeliveryMethod.External && subtitleProfile.Method != SubtitleDeliveryMethod.Embed)
  969. {
  970. _logger.Info("Not eligible for {0} due to unsupported subtitles", playMethod);
  971. return new Tuple<bool, TranscodeReason?>(false, TranscodeReason.SubtitleCodecNotSupported);
  972. }
  973. }
  974. var result = IsAudioEligibleForDirectPlay(item, maxBitrate, playMethod);
  975. if (result)
  976. {
  977. return new Tuple<bool, TranscodeReason?>(result, null);
  978. }
  979. return new Tuple<bool, TranscodeReason?>(result, TranscodeReason.ContainerBitrateExceedsLimit);
  980. }
  981. public static SubtitleProfile GetSubtitleProfile(MediaStream subtitleStream, SubtitleProfile[] subtitleProfiles, PlayMethod playMethod, string transcodingSubProtocol, string transcodingContainer)
  982. {
  983. if (!subtitleStream.IsExternal && (playMethod != PlayMethod.Transcode || !string.Equals(transcodingSubProtocol, "hls", StringComparison.OrdinalIgnoreCase)))
  984. {
  985. // Look for supported embedded subs of the same format
  986. foreach (SubtitleProfile profile in subtitleProfiles)
  987. {
  988. if (!profile.SupportsLanguage(subtitleStream.Language))
  989. {
  990. continue;
  991. }
  992. if (profile.Method != SubtitleDeliveryMethod.Embed)
  993. {
  994. continue;
  995. }
  996. if (playMethod == PlayMethod.Transcode && !IsSubtitleEmbedSupported(subtitleStream, profile, transcodingSubProtocol, transcodingContainer))
  997. {
  998. continue;
  999. }
  1000. if (subtitleStream.IsTextSubtitleStream == MediaStream.IsTextFormat(profile.Format) && StringHelper.EqualsIgnoreCase(profile.Format, subtitleStream.Codec))
  1001. {
  1002. return profile;
  1003. }
  1004. }
  1005. // Look for supported embedded subs of a convertible format
  1006. foreach (SubtitleProfile profile in subtitleProfiles)
  1007. {
  1008. if (!profile.SupportsLanguage(subtitleStream.Language))
  1009. {
  1010. continue;
  1011. }
  1012. if (profile.Method != SubtitleDeliveryMethod.Embed)
  1013. {
  1014. continue;
  1015. }
  1016. if (playMethod == PlayMethod.Transcode && !IsSubtitleEmbedSupported(subtitleStream, profile, transcodingSubProtocol, transcodingContainer))
  1017. {
  1018. continue;
  1019. }
  1020. if (subtitleStream.IsTextSubtitleStream && subtitleStream.SupportsSubtitleConversionTo(profile.Format))
  1021. {
  1022. return profile;
  1023. }
  1024. }
  1025. }
  1026. // Look for an external or hls profile that matches the stream type (text/graphical) and doesn't require conversion
  1027. return GetExternalSubtitleProfile(subtitleStream, subtitleProfiles, playMethod, false) ?? GetExternalSubtitleProfile(subtitleStream, subtitleProfiles, playMethod, true) ?? new SubtitleProfile
  1028. {
  1029. Method = SubtitleDeliveryMethod.Encode,
  1030. Format = subtitleStream.Codec
  1031. };
  1032. }
  1033. private static bool IsSubtitleEmbedSupported(MediaStream subtitleStream, SubtitleProfile subtitleProfile, string transcodingSubProtocol, string transcodingContainer)
  1034. {
  1035. if (string.Equals(transcodingContainer, "ts", StringComparison.OrdinalIgnoreCase))
  1036. {
  1037. return false;
  1038. }
  1039. if (string.Equals(transcodingContainer, "mpegts", StringComparison.OrdinalIgnoreCase))
  1040. {
  1041. return false;
  1042. }
  1043. if (string.Equals(transcodingContainer, "mp4", StringComparison.OrdinalIgnoreCase))
  1044. {
  1045. return false;
  1046. }
  1047. if (string.Equals(transcodingContainer, "mkv", StringComparison.OrdinalIgnoreCase))
  1048. {
  1049. return true;
  1050. }
  1051. return false;
  1052. }
  1053. private static SubtitleProfile GetExternalSubtitleProfile(MediaStream subtitleStream, SubtitleProfile[] subtitleProfiles, PlayMethod playMethod, bool allowConversion)
  1054. {
  1055. foreach (SubtitleProfile profile in subtitleProfiles)
  1056. {
  1057. if (profile.Method != SubtitleDeliveryMethod.External && profile.Method != SubtitleDeliveryMethod.Hls)
  1058. {
  1059. continue;
  1060. }
  1061. if (profile.Method == SubtitleDeliveryMethod.Hls && playMethod != PlayMethod.Transcode)
  1062. {
  1063. continue;
  1064. }
  1065. if (!profile.SupportsLanguage(subtitleStream.Language))
  1066. {
  1067. continue;
  1068. }
  1069. if ((profile.Method == SubtitleDeliveryMethod.External && subtitleStream.IsTextSubtitleStream == MediaStream.IsTextFormat(profile.Format)) ||
  1070. (profile.Method == SubtitleDeliveryMethod.Hls && subtitleStream.IsTextSubtitleStream))
  1071. {
  1072. bool requiresConversion = !StringHelper.EqualsIgnoreCase(subtitleStream.Codec, profile.Format);
  1073. if (!requiresConversion)
  1074. {
  1075. return profile;
  1076. }
  1077. if (!allowConversion)
  1078. {
  1079. continue;
  1080. }
  1081. if (subtitleStream.IsTextSubtitleStream && subtitleStream.SupportsExternalStream && subtitleStream.SupportsSubtitleConversionTo(profile.Format))
  1082. {
  1083. return profile;
  1084. }
  1085. }
  1086. }
  1087. return null;
  1088. }
  1089. private bool IsAudioEligibleForDirectPlay(MediaSourceInfo item, long? maxBitrate, PlayMethod playMethod)
  1090. {
  1091. // Don't restrict by bitrate if coming from an external domain
  1092. if (item.IsRemote)
  1093. {
  1094. return true;
  1095. }
  1096. if (!maxBitrate.HasValue)
  1097. {
  1098. _logger.Info("Cannot " + playMethod + " due to unknown supported bitrate");
  1099. return false;
  1100. }
  1101. if (!item.Bitrate.HasValue)
  1102. {
  1103. _logger.Info("Cannot " + playMethod + " due to unknown content bitrate");
  1104. return false;
  1105. }
  1106. if (item.Bitrate.Value > maxBitrate.Value)
  1107. {
  1108. _logger.Info("Bitrate exceeds " + playMethod + " limit: media bitrate: {0}, max bitrate: {1}", item.Bitrate.Value.ToString(CultureInfo.InvariantCulture), maxBitrate.Value.ToString(CultureInfo.InvariantCulture));
  1109. return false;
  1110. }
  1111. return true;
  1112. }
  1113. private void ValidateInput(VideoOptions options)
  1114. {
  1115. ValidateAudioInput(options);
  1116. if (options.AudioStreamIndex.HasValue && string.IsNullOrEmpty(options.MediaSourceId))
  1117. {
  1118. throw new ArgumentException("MediaSourceId is required when a specific audio stream is requested");
  1119. }
  1120. if (options.SubtitleStreamIndex.HasValue && string.IsNullOrEmpty(options.MediaSourceId))
  1121. {
  1122. throw new ArgumentException("MediaSourceId is required when a specific subtitle stream is requested");
  1123. }
  1124. }
  1125. private void ValidateAudioInput(AudioOptions options)
  1126. {
  1127. if (string.IsNullOrEmpty(options.ItemId))
  1128. {
  1129. throw new ArgumentException("ItemId is required");
  1130. }
  1131. if (string.IsNullOrEmpty(options.DeviceId))
  1132. {
  1133. throw new ArgumentException("DeviceId is required");
  1134. }
  1135. if (options.Profile == null)
  1136. {
  1137. throw new ArgumentException("Profile is required");
  1138. }
  1139. if (options.MediaSources == null)
  1140. {
  1141. throw new ArgumentException("MediaSources is required");
  1142. }
  1143. }
  1144. private void ApplyTranscodingConditions(StreamInfo item, IEnumerable<ProfileCondition> conditions)
  1145. {
  1146. foreach (ProfileCondition condition in conditions)
  1147. {
  1148. string value = condition.Value;
  1149. if (string.IsNullOrEmpty(value))
  1150. {
  1151. continue;
  1152. }
  1153. // No way to express this
  1154. if (condition.Condition == ProfileConditionType.GreaterThanEqual)
  1155. {
  1156. continue;
  1157. }
  1158. switch (condition.Property)
  1159. {
  1160. case ProfileConditionValue.AudioBitrate:
  1161. {
  1162. int num;
  1163. if (int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out num))
  1164. {
  1165. item.AudioBitrate = num;
  1166. }
  1167. break;
  1168. }
  1169. case ProfileConditionValue.AudioChannels:
  1170. {
  1171. int num;
  1172. if (int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out num))
  1173. {
  1174. item.MaxAudioChannels = num;
  1175. }
  1176. break;
  1177. }
  1178. case ProfileConditionValue.IsAvc:
  1179. {
  1180. bool isAvc;
  1181. if (bool.TryParse(value, out isAvc))
  1182. {
  1183. if (isAvc && condition.Condition == ProfileConditionType.Equals)
  1184. {
  1185. item.RequireAvc = true;
  1186. }
  1187. else if (!isAvc && condition.Condition == ProfileConditionType.NotEquals)
  1188. {
  1189. item.RequireAvc = true;
  1190. }
  1191. }
  1192. break;
  1193. }
  1194. case ProfileConditionValue.IsAnamorphic:
  1195. {
  1196. bool isAnamorphic;
  1197. if (bool.TryParse(value, out isAnamorphic))
  1198. {
  1199. if (isAnamorphic && condition.Condition == ProfileConditionType.Equals)
  1200. {
  1201. item.RequireNonAnamorphic = true;
  1202. }
  1203. else if (!isAnamorphic && condition.Condition == ProfileConditionType.NotEquals)
  1204. {
  1205. item.RequireNonAnamorphic = true;
  1206. }
  1207. }
  1208. break;
  1209. }
  1210. case ProfileConditionValue.IsInterlaced:
  1211. {
  1212. bool isInterlaced;
  1213. if (bool.TryParse(value, out isInterlaced))
  1214. {
  1215. if (!isInterlaced && condition.Condition == ProfileConditionType.Equals)
  1216. {
  1217. item.DeInterlace = true;
  1218. }
  1219. else if (isInterlaced && condition.Condition == ProfileConditionType.NotEquals)
  1220. {
  1221. item.DeInterlace = true;
  1222. }
  1223. }
  1224. break;
  1225. }
  1226. case ProfileConditionValue.AudioProfile:
  1227. case ProfileConditionValue.Has64BitOffsets:
  1228. case ProfileConditionValue.PacketLength:
  1229. case ProfileConditionValue.NumAudioStreams:
  1230. case ProfileConditionValue.NumVideoStreams:
  1231. case ProfileConditionValue.IsSecondaryAudio:
  1232. case ProfileConditionValue.VideoTimestamp:
  1233. {
  1234. // Not supported yet
  1235. break;
  1236. }
  1237. case ProfileConditionValue.RefFrames:
  1238. {
  1239. int num;
  1240. if (int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out num))
  1241. {
  1242. item.MaxRefFrames = num;
  1243. }
  1244. break;
  1245. }
  1246. case ProfileConditionValue.VideoBitDepth:
  1247. {
  1248. int num;
  1249. if (int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out num))
  1250. {
  1251. item.MaxVideoBitDepth = num;
  1252. }
  1253. break;
  1254. }
  1255. case ProfileConditionValue.VideoProfile:
  1256. {
  1257. item.VideoProfile = (value ?? string.Empty).Split('|')[0];
  1258. break;
  1259. }
  1260. case ProfileConditionValue.Height:
  1261. {
  1262. int num;
  1263. if (int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out num))
  1264. {
  1265. item.MaxHeight = num;
  1266. }
  1267. break;
  1268. }
  1269. case ProfileConditionValue.VideoBitrate:
  1270. {
  1271. int num;
  1272. if (int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out num))
  1273. {
  1274. item.VideoBitrate = num;
  1275. }
  1276. break;
  1277. }
  1278. case ProfileConditionValue.VideoFramerate:
  1279. {
  1280. float num;
  1281. if (float.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out num))
  1282. {
  1283. item.MaxFramerate = num;
  1284. }
  1285. break;
  1286. }
  1287. case ProfileConditionValue.VideoLevel:
  1288. {
  1289. int num;
  1290. if (int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out num))
  1291. {
  1292. item.VideoLevel = num;
  1293. }
  1294. break;
  1295. }
  1296. case ProfileConditionValue.Width:
  1297. {
  1298. int num;
  1299. if (int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out num))
  1300. {
  1301. item.MaxWidth = num;
  1302. }
  1303. break;
  1304. }
  1305. default:
  1306. break;
  1307. }
  1308. }
  1309. }
  1310. private bool IsAudioDirectPlaySupported(DirectPlayProfile profile, MediaSourceInfo item, MediaStream audioStream)
  1311. {
  1312. // Check container type
  1313. if (!profile.SupportsContainer(item.Container))
  1314. {
  1315. return false;
  1316. }
  1317. // Check audio codec
  1318. List<string> audioCodecs = profile.GetAudioCodecs();
  1319. if (audioCodecs.Count > 0)
  1320. {
  1321. // Check audio codecs
  1322. string audioCodec = audioStream == null ? null : audioStream.Codec;
  1323. if (string.IsNullOrEmpty(audioCodec) || !ListHelper.ContainsIgnoreCase(audioCodecs, audioCodec))
  1324. {
  1325. return false;
  1326. }
  1327. }
  1328. return true;
  1329. }
  1330. private bool IsVideoDirectPlaySupported(DirectPlayProfile profile, MediaSourceInfo item, MediaStream videoStream, MediaStream audioStream)
  1331. {
  1332. // Check container type
  1333. if (!profile.SupportsContainer(item.Container))
  1334. {
  1335. return false;
  1336. }
  1337. // Check video codec
  1338. List<string> videoCodecs = profile.GetVideoCodecs();
  1339. if (videoCodecs.Count > 0)
  1340. {
  1341. string videoCodec = videoStream == null ? null : videoStream.Codec;
  1342. if (string.IsNullOrEmpty(videoCodec) || !ListHelper.ContainsIgnoreCase(videoCodecs, videoCodec))
  1343. {
  1344. return false;
  1345. }
  1346. }
  1347. // Check audio codec
  1348. List<string> audioCodecs = profile.GetAudioCodecs();
  1349. if (audioCodecs.Count > 0)
  1350. {
  1351. // Check audio codecs
  1352. string audioCodec = audioStream == null ? null : audioStream.Codec;
  1353. if (string.IsNullOrEmpty(audioCodec) || !ListHelper.ContainsIgnoreCase(audioCodecs, audioCodec))
  1354. {
  1355. return false;
  1356. }
  1357. }
  1358. return true;
  1359. }
  1360. }
  1361. }