StreamBuilder.cs 68 KB

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