StreamBuilder.cs 68 KB

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