StreamInfo.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.Linq;
  6. using Jellyfin.Data.Enums;
  7. using MediaBrowser.Model.Drawing;
  8. using MediaBrowser.Model.Dto;
  9. using MediaBrowser.Model.Entities;
  10. using MediaBrowser.Model.MediaInfo;
  11. using MediaBrowser.Model.Session;
  12. namespace MediaBrowser.Model.Dlna
  13. {
  14. /// <summary>
  15. /// Class StreamInfo.
  16. /// </summary>
  17. public class StreamInfo
  18. {
  19. public StreamInfo()
  20. {
  21. AudioCodecs = Array.Empty<string>();
  22. VideoCodecs = Array.Empty<string>();
  23. SubtitleCodecs = Array.Empty<string>();
  24. StreamOptions = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  25. }
  26. public Guid ItemId { get; set; }
  27. public PlayMethod PlayMethod { get; set; }
  28. public EncodingContext Context { get; set; }
  29. public DlnaProfileType MediaType { get; set; }
  30. public string? Container { get; set; }
  31. public MediaStreamProtocol SubProtocol { get; set; }
  32. public long StartPositionTicks { get; set; }
  33. public int? SegmentLength { get; set; }
  34. public int? MinSegments { get; set; }
  35. public bool BreakOnNonKeyFrames { get; set; }
  36. public bool RequireAvc { get; set; }
  37. public bool RequireNonAnamorphic { get; set; }
  38. public bool CopyTimestamps { get; set; }
  39. public bool EnableMpegtsM2TsMode { get; set; }
  40. public bool EnableSubtitlesInManifest { get; set; }
  41. public string[] AudioCodecs { get; set; }
  42. public string[] VideoCodecs { get; set; }
  43. public int? AudioStreamIndex { get; set; }
  44. public int? SubtitleStreamIndex { get; set; }
  45. public int? TranscodingMaxAudioChannels { get; set; }
  46. public int? GlobalMaxAudioChannels { get; set; }
  47. public int? AudioBitrate { get; set; }
  48. public int? AudioSampleRate { get; set; }
  49. public int? VideoBitrate { get; set; }
  50. public int? MaxWidth { get; set; }
  51. public int? MaxHeight { get; set; }
  52. public float? MaxFramerate { get; set; }
  53. public required DeviceProfile DeviceProfile { get; set; }
  54. public string? DeviceProfileId { get; set; }
  55. public string? DeviceId { get; set; }
  56. public long? RunTimeTicks { get; set; }
  57. public TranscodeSeekInfo TranscodeSeekInfo { get; set; }
  58. public bool EstimateContentLength { get; set; }
  59. public MediaSourceInfo? MediaSource { get; set; }
  60. public string[] SubtitleCodecs { get; set; }
  61. public SubtitleDeliveryMethod SubtitleDeliveryMethod { get; set; }
  62. public string? SubtitleFormat { get; set; }
  63. public string? PlaySessionId { get; set; }
  64. public TranscodeReason TranscodeReasons { get; set; }
  65. public Dictionary<string, string> StreamOptions { get; private set; }
  66. public string? MediaSourceId => MediaSource?.Id;
  67. public bool EnableAudioVbrEncoding { get; set; }
  68. public bool IsDirectStream => MediaSource?.VideoType is not (VideoType.Dvd or VideoType.BluRay)
  69. && PlayMethod is PlayMethod.DirectStream or PlayMethod.DirectPlay;
  70. /// <summary>
  71. /// Gets the audio stream that will be used.
  72. /// </summary>
  73. public MediaStream? TargetAudioStream => MediaSource?.GetDefaultAudioStream(AudioStreamIndex);
  74. /// <summary>
  75. /// Gets the video stream that will be used.
  76. /// </summary>
  77. public MediaStream? TargetVideoStream => MediaSource?.VideoStream;
  78. /// <summary>
  79. /// Gets the audio sample rate that will be in the output stream.
  80. /// </summary>
  81. public int? TargetAudioSampleRate
  82. {
  83. get
  84. {
  85. var stream = TargetAudioStream;
  86. return AudioSampleRate.HasValue && !IsDirectStream
  87. ? AudioSampleRate
  88. : stream?.SampleRate;
  89. }
  90. }
  91. /// <summary>
  92. /// Gets the audio sample rate that will be in the output stream.
  93. /// </summary>
  94. public int? TargetAudioBitDepth
  95. {
  96. get
  97. {
  98. if (IsDirectStream)
  99. {
  100. return TargetAudioStream?.BitDepth;
  101. }
  102. var targetAudioCodecs = TargetAudioCodec;
  103. var audioCodec = targetAudioCodecs.Length == 0 ? null : targetAudioCodecs[0];
  104. if (!string.IsNullOrEmpty(audioCodec))
  105. {
  106. return GetTargetAudioBitDepth(audioCodec);
  107. }
  108. return TargetAudioStream?.BitDepth;
  109. }
  110. }
  111. /// <summary>
  112. /// Gets the audio sample rate that will be in the output stream.
  113. /// </summary>
  114. public int? TargetVideoBitDepth
  115. {
  116. get
  117. {
  118. if (IsDirectStream)
  119. {
  120. return TargetVideoStream?.BitDepth;
  121. }
  122. var targetVideoCodecs = TargetVideoCodec;
  123. var videoCodec = targetVideoCodecs.Length == 0 ? null : targetVideoCodecs[0];
  124. if (!string.IsNullOrEmpty(videoCodec))
  125. {
  126. return GetTargetVideoBitDepth(videoCodec);
  127. }
  128. return TargetVideoStream?.BitDepth;
  129. }
  130. }
  131. /// <summary>
  132. /// Gets the target reference frames.
  133. /// </summary>
  134. /// <value>The target reference frames.</value>
  135. public int? TargetRefFrames
  136. {
  137. get
  138. {
  139. if (IsDirectStream)
  140. {
  141. return TargetVideoStream?.RefFrames;
  142. }
  143. var targetVideoCodecs = TargetVideoCodec;
  144. var videoCodec = targetVideoCodecs.Length == 0 ? null : targetVideoCodecs[0];
  145. if (!string.IsNullOrEmpty(videoCodec))
  146. {
  147. return GetTargetRefFrames(videoCodec);
  148. }
  149. return TargetVideoStream?.RefFrames;
  150. }
  151. }
  152. /// <summary>
  153. /// Gets the audio sample rate that will be in the output stream.
  154. /// </summary>
  155. public float? TargetFramerate
  156. {
  157. get
  158. {
  159. var stream = TargetVideoStream;
  160. return MaxFramerate.HasValue && !IsDirectStream
  161. ? MaxFramerate
  162. : stream is null ? null : stream.AverageFrameRate ?? stream.RealFrameRate;
  163. }
  164. }
  165. /// <summary>
  166. /// Gets the audio sample rate that will be in the output stream.
  167. /// </summary>
  168. public double? TargetVideoLevel
  169. {
  170. get
  171. {
  172. if (IsDirectStream)
  173. {
  174. return TargetVideoStream?.Level;
  175. }
  176. var targetVideoCodecs = TargetVideoCodec;
  177. var videoCodec = targetVideoCodecs.Length == 0 ? null : targetVideoCodecs[0];
  178. if (!string.IsNullOrEmpty(videoCodec))
  179. {
  180. return GetTargetVideoLevel(videoCodec);
  181. }
  182. return TargetVideoStream?.Level;
  183. }
  184. }
  185. /// <summary>
  186. /// Gets the audio sample rate that will be in the output stream.
  187. /// </summary>
  188. public int? TargetPacketLength
  189. {
  190. get
  191. {
  192. var stream = TargetVideoStream;
  193. return !IsDirectStream
  194. ? null
  195. : stream?.PacketLength;
  196. }
  197. }
  198. /// <summary>
  199. /// Gets the audio sample rate that will be in the output stream.
  200. /// </summary>
  201. public string? TargetVideoProfile
  202. {
  203. get
  204. {
  205. if (IsDirectStream)
  206. {
  207. return TargetVideoStream?.Profile;
  208. }
  209. var targetVideoCodecs = TargetVideoCodec;
  210. var videoCodec = targetVideoCodecs.Length == 0 ? null : targetVideoCodecs[0];
  211. if (!string.IsNullOrEmpty(videoCodec))
  212. {
  213. return GetOption(videoCodec, "profile");
  214. }
  215. return TargetVideoStream?.Profile;
  216. }
  217. }
  218. /// <summary>
  219. /// Gets the target video range type that will be in the output stream.
  220. /// </summary>
  221. public VideoRangeType TargetVideoRangeType
  222. {
  223. get
  224. {
  225. if (IsDirectStream)
  226. {
  227. return TargetVideoStream?.VideoRangeType ?? VideoRangeType.Unknown;
  228. }
  229. var targetVideoCodecs = TargetVideoCodec;
  230. var videoCodec = targetVideoCodecs.Length == 0 ? null : targetVideoCodecs[0];
  231. if (!string.IsNullOrEmpty(videoCodec)
  232. && Enum.TryParse(GetOption(videoCodec, "rangetype"), true, out VideoRangeType videoRangeType))
  233. {
  234. return videoRangeType;
  235. }
  236. return TargetVideoStream?.VideoRangeType ?? VideoRangeType.Unknown;
  237. }
  238. }
  239. /// <summary>
  240. /// Gets the target video codec tag.
  241. /// </summary>
  242. /// <value>The target video codec tag.</value>
  243. public string? TargetVideoCodecTag
  244. {
  245. get
  246. {
  247. var stream = TargetVideoStream;
  248. return !IsDirectStream
  249. ? null
  250. : stream?.CodecTag;
  251. }
  252. }
  253. /// <summary>
  254. /// Gets the audio bitrate that will be in the output stream.
  255. /// </summary>
  256. public int? TargetAudioBitrate
  257. {
  258. get
  259. {
  260. var stream = TargetAudioStream;
  261. return AudioBitrate.HasValue && !IsDirectStream
  262. ? AudioBitrate
  263. : stream?.BitRate;
  264. }
  265. }
  266. /// <summary>
  267. /// Gets the audio channels that will be in the output stream.
  268. /// </summary>
  269. public int? TargetAudioChannels
  270. {
  271. get
  272. {
  273. if (IsDirectStream)
  274. {
  275. return TargetAudioStream?.Channels;
  276. }
  277. var targetAudioCodecs = TargetAudioCodec;
  278. var codec = targetAudioCodecs.Length == 0 ? null : targetAudioCodecs[0];
  279. if (!string.IsNullOrEmpty(codec))
  280. {
  281. return GetTargetRefFrames(codec);
  282. }
  283. return TargetAudioStream?.Channels;
  284. }
  285. }
  286. /// <summary>
  287. /// Gets the audio codec that will be in the output stream.
  288. /// </summary>
  289. public string[] TargetAudioCodec
  290. {
  291. get
  292. {
  293. var stream = TargetAudioStream;
  294. string? inputCodec = stream?.Codec;
  295. if (IsDirectStream)
  296. {
  297. return string.IsNullOrEmpty(inputCodec) ? Array.Empty<string>() : new[] { inputCodec };
  298. }
  299. foreach (string codec in AudioCodecs)
  300. {
  301. if (string.Equals(codec, inputCodec, StringComparison.OrdinalIgnoreCase))
  302. {
  303. return string.IsNullOrEmpty(codec) ? Array.Empty<string>() : new[] { codec };
  304. }
  305. }
  306. return AudioCodecs;
  307. }
  308. }
  309. public string[] TargetVideoCodec
  310. {
  311. get
  312. {
  313. var stream = TargetVideoStream;
  314. string? inputCodec = stream?.Codec;
  315. if (IsDirectStream)
  316. {
  317. return string.IsNullOrEmpty(inputCodec) ? Array.Empty<string>() : new[] { inputCodec };
  318. }
  319. foreach (string codec in VideoCodecs)
  320. {
  321. if (string.Equals(codec, inputCodec, StringComparison.OrdinalIgnoreCase))
  322. {
  323. return string.IsNullOrEmpty(codec) ? Array.Empty<string>() : new[] { codec };
  324. }
  325. }
  326. return VideoCodecs;
  327. }
  328. }
  329. /// <summary>
  330. /// Gets the audio channels that will be in the output stream.
  331. /// </summary>
  332. public long? TargetSize
  333. {
  334. get
  335. {
  336. if (IsDirectStream)
  337. {
  338. return MediaSource?.Size;
  339. }
  340. if (RunTimeTicks.HasValue)
  341. {
  342. int? totalBitrate = TargetTotalBitrate;
  343. double totalSeconds = RunTimeTicks.Value;
  344. // Convert to ms
  345. totalSeconds /= 10000;
  346. // Convert to seconds
  347. totalSeconds /= 1000;
  348. return totalBitrate.HasValue ?
  349. Convert.ToInt64(totalBitrate.Value * totalSeconds) :
  350. null;
  351. }
  352. return null;
  353. }
  354. }
  355. public int? TargetVideoBitrate
  356. {
  357. get
  358. {
  359. var stream = TargetVideoStream;
  360. return VideoBitrate.HasValue && !IsDirectStream
  361. ? VideoBitrate
  362. : stream?.BitRate;
  363. }
  364. }
  365. public TransportStreamTimestamp TargetTimestamp
  366. {
  367. get
  368. {
  369. var defaultValue = string.Equals(Container, "m2ts", StringComparison.OrdinalIgnoreCase)
  370. ? TransportStreamTimestamp.Valid
  371. : TransportStreamTimestamp.None;
  372. return !IsDirectStream
  373. ? defaultValue
  374. : MediaSource is null ? defaultValue : MediaSource.Timestamp ?? TransportStreamTimestamp.None;
  375. }
  376. }
  377. public int? TargetTotalBitrate => (TargetAudioBitrate ?? 0) + (TargetVideoBitrate ?? 0);
  378. public bool? IsTargetAnamorphic
  379. {
  380. get
  381. {
  382. if (IsDirectStream)
  383. {
  384. return TargetVideoStream?.IsAnamorphic;
  385. }
  386. return false;
  387. }
  388. }
  389. public bool? IsTargetInterlaced
  390. {
  391. get
  392. {
  393. if (IsDirectStream)
  394. {
  395. return TargetVideoStream?.IsInterlaced;
  396. }
  397. var targetVideoCodecs = TargetVideoCodec;
  398. var videoCodec = targetVideoCodecs.Length == 0 ? null : targetVideoCodecs[0];
  399. if (!string.IsNullOrEmpty(videoCodec))
  400. {
  401. if (string.Equals(GetOption(videoCodec, "deinterlace"), "true", StringComparison.OrdinalIgnoreCase))
  402. {
  403. return false;
  404. }
  405. }
  406. return TargetVideoStream?.IsInterlaced;
  407. }
  408. }
  409. public bool? IsTargetAVC
  410. {
  411. get
  412. {
  413. if (IsDirectStream)
  414. {
  415. return TargetVideoStream?.IsAVC;
  416. }
  417. return true;
  418. }
  419. }
  420. public int? TargetWidth
  421. {
  422. get
  423. {
  424. var videoStream = TargetVideoStream;
  425. if (videoStream is not null && videoStream.Width.HasValue && videoStream.Height.HasValue)
  426. {
  427. ImageDimensions size = new ImageDimensions(videoStream.Width.Value, videoStream.Height.Value);
  428. size = DrawingUtils.Resize(size, 0, 0, MaxWidth ?? 0, MaxHeight ?? 0);
  429. return size.Width;
  430. }
  431. return MaxWidth;
  432. }
  433. }
  434. public int? TargetHeight
  435. {
  436. get
  437. {
  438. var videoStream = TargetVideoStream;
  439. if (videoStream is not null && videoStream.Width.HasValue && videoStream.Height.HasValue)
  440. {
  441. ImageDimensions size = new ImageDimensions(videoStream.Width.Value, videoStream.Height.Value);
  442. size = DrawingUtils.Resize(size, 0, 0, MaxWidth ?? 0, MaxHeight ?? 0);
  443. return size.Height;
  444. }
  445. return MaxHeight;
  446. }
  447. }
  448. public int? TargetVideoStreamCount
  449. {
  450. get
  451. {
  452. if (IsDirectStream)
  453. {
  454. return GetMediaStreamCount(MediaStreamType.Video, int.MaxValue);
  455. }
  456. return GetMediaStreamCount(MediaStreamType.Video, 1);
  457. }
  458. }
  459. public int? TargetAudioStreamCount
  460. {
  461. get
  462. {
  463. if (IsDirectStream)
  464. {
  465. return GetMediaStreamCount(MediaStreamType.Audio, int.MaxValue);
  466. }
  467. return GetMediaStreamCount(MediaStreamType.Audio, 1);
  468. }
  469. }
  470. public void SetOption(string? qualifier, string name, string value)
  471. {
  472. if (string.IsNullOrEmpty(qualifier))
  473. {
  474. SetOption(name, value);
  475. }
  476. else
  477. {
  478. SetOption(qualifier + "-" + name, value);
  479. }
  480. }
  481. public void SetOption(string name, string value)
  482. {
  483. StreamOptions[name] = value;
  484. }
  485. public string? GetOption(string? qualifier, string name)
  486. {
  487. var value = GetOption(qualifier + "-" + name);
  488. if (string.IsNullOrEmpty(value))
  489. {
  490. value = GetOption(name);
  491. }
  492. return value;
  493. }
  494. public string? GetOption(string name)
  495. {
  496. if (StreamOptions.TryGetValue(name, out var value))
  497. {
  498. return value;
  499. }
  500. return null;
  501. }
  502. public string ToUrl(string baseUrl, string? accessToken)
  503. {
  504. ArgumentException.ThrowIfNullOrEmpty(baseUrl);
  505. var list = new List<string>();
  506. foreach (NameValuePair pair in BuildParams(this, accessToken))
  507. {
  508. if (string.IsNullOrEmpty(pair.Value))
  509. {
  510. continue;
  511. }
  512. // Try to keep the url clean by omitting defaults
  513. if (string.Equals(pair.Name, "StartTimeTicks", StringComparison.OrdinalIgnoreCase)
  514. && string.Equals(pair.Value, "0", StringComparison.OrdinalIgnoreCase))
  515. {
  516. continue;
  517. }
  518. if (string.Equals(pair.Name, "SubtitleStreamIndex", StringComparison.OrdinalIgnoreCase)
  519. && string.Equals(pair.Value, "-1", StringComparison.OrdinalIgnoreCase))
  520. {
  521. continue;
  522. }
  523. if (string.Equals(pair.Name, "Static", StringComparison.OrdinalIgnoreCase)
  524. && string.Equals(pair.Value, "false", StringComparison.OrdinalIgnoreCase))
  525. {
  526. continue;
  527. }
  528. var encodedValue = pair.Value.Replace(" ", "%20", StringComparison.Ordinal);
  529. list.Add(string.Format(CultureInfo.InvariantCulture, "{0}={1}", pair.Name, encodedValue));
  530. }
  531. string queryString = string.Join('&', list);
  532. return GetUrl(baseUrl, queryString);
  533. }
  534. private string GetUrl(string baseUrl, string queryString)
  535. {
  536. ArgumentException.ThrowIfNullOrEmpty(baseUrl);
  537. string extension = string.IsNullOrEmpty(Container) ? string.Empty : "." + Container;
  538. baseUrl = baseUrl.TrimEnd('/');
  539. if (MediaType == DlnaProfileType.Audio)
  540. {
  541. if (SubProtocol == MediaStreamProtocol.hls)
  542. {
  543. return string.Format(CultureInfo.InvariantCulture, "{0}/audio/{1}/master.m3u8?{2}", baseUrl, ItemId, queryString);
  544. }
  545. return string.Format(CultureInfo.InvariantCulture, "{0}/audio/{1}/stream{2}?{3}", baseUrl, ItemId, extension, queryString);
  546. }
  547. if (SubProtocol == MediaStreamProtocol.hls)
  548. {
  549. return string.Format(CultureInfo.InvariantCulture, "{0}/videos/{1}/master.m3u8?{2}", baseUrl, ItemId, queryString);
  550. }
  551. return string.Format(CultureInfo.InvariantCulture, "{0}/videos/{1}/stream{2}?{3}", baseUrl, ItemId, extension, queryString);
  552. }
  553. private static IEnumerable<NameValuePair> BuildParams(StreamInfo item, string? accessToken)
  554. {
  555. var list = new List<NameValuePair>();
  556. string audioCodecs = item.AudioCodecs.Length == 0 ?
  557. string.Empty :
  558. string.Join(',', item.AudioCodecs);
  559. string videoCodecs = item.VideoCodecs.Length == 0 ?
  560. string.Empty :
  561. string.Join(',', item.VideoCodecs);
  562. list.Add(new NameValuePair("DeviceProfileId", item.DeviceProfileId ?? string.Empty));
  563. list.Add(new NameValuePair("DeviceId", item.DeviceId ?? string.Empty));
  564. list.Add(new NameValuePair("MediaSourceId", item.MediaSourceId ?? string.Empty));
  565. list.Add(new NameValuePair("Static", item.IsDirectStream.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()));
  566. list.Add(new NameValuePair("VideoCodec", videoCodecs));
  567. list.Add(new NameValuePair("AudioCodec", audioCodecs));
  568. list.Add(new NameValuePair("AudioStreamIndex", item.AudioStreamIndex.HasValue ? item.AudioStreamIndex.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
  569. list.Add(new NameValuePair("SubtitleStreamIndex", item.SubtitleStreamIndex.HasValue && item.SubtitleDeliveryMethod != SubtitleDeliveryMethod.External ? item.SubtitleStreamIndex.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
  570. list.Add(new NameValuePair("VideoBitrate", item.VideoBitrate.HasValue ? item.VideoBitrate.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
  571. list.Add(new NameValuePair("AudioBitrate", item.AudioBitrate.HasValue ? item.AudioBitrate.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
  572. list.Add(new NameValuePair("AudioSampleRate", item.AudioSampleRate.HasValue ? item.AudioSampleRate.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
  573. list.Add(new NameValuePair("MaxFramerate", item.MaxFramerate.HasValue ? item.MaxFramerate.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
  574. list.Add(new NameValuePair("MaxWidth", item.MaxWidth.HasValue ? item.MaxWidth.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
  575. list.Add(new NameValuePair("MaxHeight", item.MaxHeight.HasValue ? item.MaxHeight.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
  576. long startPositionTicks = item.StartPositionTicks;
  577. if (item.SubProtocol == MediaStreamProtocol.hls)
  578. {
  579. list.Add(new NameValuePair("StartTimeTicks", string.Empty));
  580. }
  581. else
  582. {
  583. list.Add(new NameValuePair("StartTimeTicks", startPositionTicks.ToString(CultureInfo.InvariantCulture)));
  584. }
  585. list.Add(new NameValuePair("PlaySessionId", item.PlaySessionId ?? string.Empty));
  586. list.Add(new NameValuePair("api_key", accessToken ?? string.Empty));
  587. string? liveStreamId = item.MediaSource?.LiveStreamId;
  588. list.Add(new NameValuePair("LiveStreamId", liveStreamId ?? string.Empty));
  589. list.Add(new NameValuePair("SubtitleMethod", item.SubtitleStreamIndex.HasValue && item.SubtitleDeliveryMethod != SubtitleDeliveryMethod.External ? item.SubtitleDeliveryMethod.ToString() : string.Empty));
  590. if (!item.IsDirectStream)
  591. {
  592. if (item.RequireNonAnamorphic)
  593. {
  594. list.Add(new NameValuePair("RequireNonAnamorphic", item.RequireNonAnamorphic.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()));
  595. }
  596. list.Add(new NameValuePair("TranscodingMaxAudioChannels", item.TranscodingMaxAudioChannels.HasValue ? item.TranscodingMaxAudioChannels.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
  597. if (item.EnableSubtitlesInManifest)
  598. {
  599. list.Add(new NameValuePair("EnableSubtitlesInManifest", item.EnableSubtitlesInManifest.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()));
  600. }
  601. if (item.EnableMpegtsM2TsMode)
  602. {
  603. list.Add(new NameValuePair("EnableMpegtsM2TsMode", item.EnableMpegtsM2TsMode.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()));
  604. }
  605. if (item.EstimateContentLength)
  606. {
  607. list.Add(new NameValuePair("EstimateContentLength", item.EstimateContentLength.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()));
  608. }
  609. if (item.TranscodeSeekInfo != TranscodeSeekInfo.Auto)
  610. {
  611. list.Add(new NameValuePair("TranscodeSeekInfo", item.TranscodeSeekInfo.ToString().ToLowerInvariant()));
  612. }
  613. if (item.CopyTimestamps)
  614. {
  615. list.Add(new NameValuePair("CopyTimestamps", item.CopyTimestamps.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()));
  616. }
  617. list.Add(new NameValuePair("RequireAvc", item.RequireAvc.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()));
  618. list.Add(new NameValuePair("EnableAudioVbrEncoding", item.EnableAudioVbrEncoding.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()));
  619. }
  620. list.Add(new NameValuePair("Tag", item.MediaSource?.ETag ?? string.Empty));
  621. string subtitleCodecs = item.SubtitleCodecs.Length == 0 ?
  622. string.Empty :
  623. string.Join(",", item.SubtitleCodecs);
  624. list.Add(new NameValuePair("SubtitleCodec", item.SubtitleStreamIndex.HasValue && item.SubtitleDeliveryMethod == SubtitleDeliveryMethod.Embed ? subtitleCodecs : string.Empty));
  625. if (item.SubProtocol == MediaStreamProtocol.hls)
  626. {
  627. list.Add(new NameValuePair("SegmentContainer", item.Container ?? string.Empty));
  628. if (item.SegmentLength.HasValue)
  629. {
  630. list.Add(new NameValuePair("SegmentLength", item.SegmentLength.Value.ToString(CultureInfo.InvariantCulture)));
  631. }
  632. if (item.MinSegments.HasValue)
  633. {
  634. list.Add(new NameValuePair("MinSegments", item.MinSegments.Value.ToString(CultureInfo.InvariantCulture)));
  635. }
  636. list.Add(new NameValuePair("BreakOnNonKeyFrames", item.BreakOnNonKeyFrames.ToString(CultureInfo.InvariantCulture)));
  637. }
  638. foreach (var pair in item.StreamOptions)
  639. {
  640. if (string.IsNullOrEmpty(pair.Value))
  641. {
  642. continue;
  643. }
  644. // strip spaces to avoid having to encode h264 profile names
  645. list.Add(new NameValuePair(pair.Key, pair.Value.Replace(" ", string.Empty, StringComparison.Ordinal)));
  646. }
  647. if (!item.IsDirectStream)
  648. {
  649. list.Add(new NameValuePair("TranscodeReasons", item.TranscodeReasons.ToString()));
  650. }
  651. return list;
  652. }
  653. public IEnumerable<SubtitleStreamInfo> GetSubtitleProfiles(ITranscoderSupport transcoderSupport, bool includeSelectedTrackOnly, string baseUrl, string? accessToken)
  654. {
  655. return GetSubtitleProfiles(transcoderSupport, includeSelectedTrackOnly, false, baseUrl, accessToken);
  656. }
  657. public IEnumerable<SubtitleStreamInfo> GetSubtitleProfiles(ITranscoderSupport transcoderSupport, bool includeSelectedTrackOnly, bool enableAllProfiles, string baseUrl, string? accessToken)
  658. {
  659. if (MediaSource is null)
  660. {
  661. return Enumerable.Empty<SubtitleStreamInfo>();
  662. }
  663. var list = new List<SubtitleStreamInfo>();
  664. // HLS will preserve timestamps so we can just grab the full subtitle stream
  665. long startPositionTicks = SubProtocol == MediaStreamProtocol.hls
  666. ? 0
  667. : (PlayMethod == PlayMethod.Transcode && !CopyTimestamps ? StartPositionTicks : 0);
  668. // First add the selected track
  669. if (SubtitleStreamIndex.HasValue)
  670. {
  671. foreach (var stream in MediaSource.MediaStreams)
  672. {
  673. if (stream.Type == MediaStreamType.Subtitle && stream.Index == SubtitleStreamIndex.Value)
  674. {
  675. AddSubtitleProfiles(list, stream, transcoderSupport, enableAllProfiles, baseUrl, accessToken, startPositionTicks);
  676. }
  677. }
  678. }
  679. if (!includeSelectedTrackOnly)
  680. {
  681. foreach (var stream in MediaSource.MediaStreams)
  682. {
  683. if (stream.Type == MediaStreamType.Subtitle && (!SubtitleStreamIndex.HasValue || stream.Index != SubtitleStreamIndex.Value))
  684. {
  685. AddSubtitleProfiles(list, stream, transcoderSupport, enableAllProfiles, baseUrl, accessToken, startPositionTicks);
  686. }
  687. }
  688. }
  689. return list;
  690. }
  691. private void AddSubtitleProfiles(List<SubtitleStreamInfo> list, MediaStream stream, ITranscoderSupport transcoderSupport, bool enableAllProfiles, string baseUrl, string? accessToken, long startPositionTicks)
  692. {
  693. if (enableAllProfiles)
  694. {
  695. foreach (var profile in DeviceProfile.SubtitleProfiles)
  696. {
  697. var info = GetSubtitleStreamInfo(stream, baseUrl, accessToken, startPositionTicks, new[] { profile }, transcoderSupport);
  698. if (info is not null)
  699. {
  700. list.Add(info);
  701. }
  702. }
  703. }
  704. else
  705. {
  706. var info = GetSubtitleStreamInfo(stream, baseUrl, accessToken, startPositionTicks, DeviceProfile.SubtitleProfiles, transcoderSupport);
  707. if (info is not null)
  708. {
  709. list.Add(info);
  710. }
  711. }
  712. }
  713. private SubtitleStreamInfo? GetSubtitleStreamInfo(MediaStream stream, string baseUrl, string? accessToken, long startPositionTicks, SubtitleProfile[] subtitleProfiles, ITranscoderSupport transcoderSupport)
  714. {
  715. if (MediaSource is null)
  716. {
  717. return null;
  718. }
  719. var subtitleProfile = StreamBuilder.GetSubtitleProfile(MediaSource, stream, subtitleProfiles, PlayMethod, transcoderSupport, Container, SubProtocol);
  720. var info = new SubtitleStreamInfo
  721. {
  722. IsForced = stream.IsForced,
  723. Language = stream.Language,
  724. Name = stream.Language ?? "Unknown",
  725. Format = subtitleProfile.Format,
  726. Index = stream.Index,
  727. DeliveryMethod = subtitleProfile.Method,
  728. DisplayTitle = stream.DisplayTitle
  729. };
  730. if (info.DeliveryMethod == SubtitleDeliveryMethod.External)
  731. {
  732. if (MediaSource.Protocol == MediaProtocol.File || !string.Equals(stream.Codec, subtitleProfile.Format, StringComparison.OrdinalIgnoreCase) || !stream.IsExternal)
  733. {
  734. info.Url = string.Format(
  735. CultureInfo.InvariantCulture,
  736. "{0}/Videos/{1}/{2}/Subtitles/{3}/{4}/Stream.{5}",
  737. baseUrl,
  738. ItemId,
  739. MediaSourceId,
  740. stream.Index.ToString(CultureInfo.InvariantCulture),
  741. startPositionTicks.ToString(CultureInfo.InvariantCulture),
  742. subtitleProfile.Format);
  743. if (!string.IsNullOrEmpty(accessToken))
  744. {
  745. info.Url += "?api_key=" + accessToken;
  746. }
  747. info.IsExternalUrl = false;
  748. }
  749. else
  750. {
  751. info.Url = stream.Path;
  752. info.IsExternalUrl = true;
  753. }
  754. }
  755. return info;
  756. }
  757. public int? GetTargetVideoBitDepth(string? codec)
  758. {
  759. var value = GetOption(codec, "videobitdepth");
  760. if (int.TryParse(value, CultureInfo.InvariantCulture, out var result))
  761. {
  762. return result;
  763. }
  764. return null;
  765. }
  766. public int? GetTargetAudioBitDepth(string? codec)
  767. {
  768. var value = GetOption(codec, "audiobitdepth");
  769. if (int.TryParse(value, CultureInfo.InvariantCulture, out var result))
  770. {
  771. return result;
  772. }
  773. return null;
  774. }
  775. public double? GetTargetVideoLevel(string? codec)
  776. {
  777. var value = GetOption(codec, "level");
  778. if (double.TryParse(value, CultureInfo.InvariantCulture, out var result))
  779. {
  780. return result;
  781. }
  782. return null;
  783. }
  784. public int? GetTargetRefFrames(string? codec)
  785. {
  786. var value = GetOption(codec, "maxrefframes");
  787. if (int.TryParse(value, CultureInfo.InvariantCulture, out var result))
  788. {
  789. return result;
  790. }
  791. return null;
  792. }
  793. public int? GetTargetAudioChannels(string? codec)
  794. {
  795. var defaultValue = GlobalMaxAudioChannels ?? TranscodingMaxAudioChannels;
  796. var value = GetOption(codec, "audiochannels");
  797. if (string.IsNullOrEmpty(value))
  798. {
  799. return defaultValue;
  800. }
  801. if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
  802. {
  803. return Math.Min(result, defaultValue ?? result);
  804. }
  805. return defaultValue;
  806. }
  807. private int? GetMediaStreamCount(MediaStreamType type, int limit)
  808. {
  809. var count = MediaSource?.GetStreamCount(type);
  810. if (count.HasValue)
  811. {
  812. count = Math.Min(count.Value, limit);
  813. }
  814. return count;
  815. }
  816. }
  817. }