DidlBuilder.cs 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Xml;
  9. using Emby.Dlna.ContentDirectory;
  10. using Jellyfin.Data.Entities;
  11. using MediaBrowser.Controller.Channels;
  12. using MediaBrowser.Controller.Drawing;
  13. using MediaBrowser.Controller.Entities;
  14. using MediaBrowser.Controller.Entities.Audio;
  15. using MediaBrowser.Controller.Entities.Movies;
  16. using MediaBrowser.Controller.Library;
  17. using MediaBrowser.Controller.MediaEncoding;
  18. using MediaBrowser.Controller.Playlists;
  19. using MediaBrowser.Model.Dlna;
  20. using MediaBrowser.Model.Drawing;
  21. using MediaBrowser.Model.Entities;
  22. using MediaBrowser.Model.Globalization;
  23. using MediaBrowser.Model.Net;
  24. using Microsoft.Extensions.Logging;
  25. using Episode = MediaBrowser.Controller.Entities.TV.Episode;
  26. using Genre = MediaBrowser.Controller.Entities.Genre;
  27. using Movie = MediaBrowser.Controller.Entities.Movies.Movie;
  28. using MusicAlbum = MediaBrowser.Controller.Entities.Audio.MusicAlbum;
  29. using Season = MediaBrowser.Controller.Entities.TV.Season;
  30. using Series = MediaBrowser.Controller.Entities.TV.Series;
  31. using XmlAttribute = MediaBrowser.Model.Dlna.XmlAttribute;
  32. namespace Emby.Dlna.Didl
  33. {
  34. public class DidlBuilder
  35. {
  36. private const string NsDidl = "urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/";
  37. private const string NsDc = "http://purl.org/dc/elements/1.1/";
  38. private const string NsUpnp = "urn:schemas-upnp-org:metadata-1-0/upnp/";
  39. private const string NsDlna = "urn:schemas-dlna-org:metadata-1-0/";
  40. private readonly DeviceProfile _profile;
  41. private readonly IImageProcessor _imageProcessor;
  42. private readonly string _serverAddress;
  43. private readonly string _accessToken;
  44. private readonly User _user;
  45. private readonly IUserDataManager _userDataManager;
  46. private readonly ILocalizationManager _localization;
  47. private readonly IMediaSourceManager _mediaSourceManager;
  48. private readonly ILogger _logger;
  49. private readonly IMediaEncoder _mediaEncoder;
  50. private readonly ILibraryManager _libraryManager;
  51. public DidlBuilder(
  52. DeviceProfile profile,
  53. User user,
  54. IImageProcessor imageProcessor,
  55. string serverAddress,
  56. string accessToken,
  57. IUserDataManager userDataManager,
  58. ILocalizationManager localization,
  59. IMediaSourceManager mediaSourceManager,
  60. ILogger logger,
  61. IMediaEncoder mediaEncoder,
  62. ILibraryManager libraryManager)
  63. {
  64. _profile = profile;
  65. _user = user;
  66. _imageProcessor = imageProcessor;
  67. _serverAddress = serverAddress;
  68. _accessToken = accessToken;
  69. _userDataManager = userDataManager;
  70. _localization = localization;
  71. _mediaSourceManager = mediaSourceManager;
  72. _logger = logger;
  73. _mediaEncoder = mediaEncoder;
  74. _libraryManager = libraryManager;
  75. }
  76. public static string NormalizeDlnaMediaUrl(string url)
  77. {
  78. return url + "&dlnaheaders=true";
  79. }
  80. public string GetItemDidl(BaseItem item, User user, BaseItem context, string deviceId, Filter filter, StreamInfo streamInfo)
  81. {
  82. var settings = new XmlWriterSettings
  83. {
  84. Encoding = Encoding.UTF8,
  85. CloseOutput = false,
  86. OmitXmlDeclaration = true,
  87. ConformanceLevel = ConformanceLevel.Fragment
  88. };
  89. using (StringWriter builder = new StringWriterWithEncoding(Encoding.UTF8))
  90. {
  91. // If this using are changed to single lines, then write.Flush needs to be appended before the return.
  92. using (var writer = XmlWriter.Create(builder, settings))
  93. {
  94. // writer.WriteStartDocument();
  95. writer.WriteStartElement(string.Empty, "DIDL-Lite", NsDidl);
  96. writer.WriteAttributeString("xmlns", "dc", null, NsDc);
  97. writer.WriteAttributeString("xmlns", "dlna", null, NsDlna);
  98. writer.WriteAttributeString("xmlns", "upnp", null, NsUpnp);
  99. // didl.SetAttribute("xmlns:sec", NS_SEC);
  100. WriteXmlRootAttributes(_profile, writer);
  101. WriteItemElement(writer, item, user, context, null, deviceId, filter, streamInfo);
  102. writer.WriteFullEndElement();
  103. // writer.WriteEndDocument();
  104. }
  105. return builder.ToString();
  106. }
  107. }
  108. public static void WriteXmlRootAttributes(DeviceProfile profile, XmlWriter writer)
  109. {
  110. foreach (var att in profile.XmlRootAttributes)
  111. {
  112. var parts = att.Name.Split(':', StringSplitOptions.RemoveEmptyEntries);
  113. if (parts.Length == 2)
  114. {
  115. writer.WriteAttributeString(parts[0], parts[1], null, att.Value);
  116. }
  117. else
  118. {
  119. writer.WriteAttributeString(att.Name, att.Value);
  120. }
  121. }
  122. }
  123. public void WriteItemElement(
  124. XmlWriter writer,
  125. BaseItem item,
  126. User user,
  127. BaseItem context,
  128. StubType? contextStubType,
  129. string deviceId,
  130. Filter filter,
  131. StreamInfo streamInfo = null)
  132. {
  133. var clientId = GetClientId(item, null);
  134. writer.WriteStartElement(string.Empty, "item", NsDidl);
  135. writer.WriteAttributeString("restricted", "1");
  136. writer.WriteAttributeString("id", clientId);
  137. if (context != null)
  138. {
  139. writer.WriteAttributeString("parentID", GetClientId(context, contextStubType));
  140. }
  141. else
  142. {
  143. var parent = item.DisplayParentId;
  144. if (!parent.Equals(default))
  145. {
  146. writer.WriteAttributeString("parentID", GetClientId(parent, null));
  147. }
  148. }
  149. AddGeneralProperties(item, null, context, writer, filter);
  150. AddSamsungBookmarkInfo(item, user, writer, streamInfo);
  151. // refID?
  152. // storeAttribute(itemNode, object, ClassProperties.REF_ID, false);
  153. if (item is IHasMediaSources)
  154. {
  155. if (string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase))
  156. {
  157. AddAudioResource(writer, item, deviceId, filter, streamInfo);
  158. }
  159. else if (string.Equals(item.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase))
  160. {
  161. AddVideoResource(writer, item, deviceId, filter, streamInfo);
  162. }
  163. }
  164. AddCover(item, null, writer);
  165. writer.WriteFullEndElement();
  166. }
  167. private void AddVideoResource(XmlWriter writer, BaseItem video, string deviceId, Filter filter, StreamInfo streamInfo = null)
  168. {
  169. if (streamInfo == null)
  170. {
  171. var sources = _mediaSourceManager.GetStaticMediaSources(video, true, _user);
  172. streamInfo = new StreamBuilder(_mediaEncoder, _logger).BuildVideoItem(new VideoOptions
  173. {
  174. ItemId = video.Id,
  175. MediaSources = sources.ToArray(),
  176. Profile = _profile,
  177. DeviceId = deviceId,
  178. MaxBitrate = _profile.MaxStreamingBitrate
  179. });
  180. }
  181. var targetWidth = streamInfo.TargetWidth;
  182. var targetHeight = streamInfo.TargetHeight;
  183. var contentFeatureList = ContentFeatureBuilder.BuildVideoHeader(
  184. _profile,
  185. streamInfo.Container,
  186. streamInfo.TargetVideoCodec.FirstOrDefault(),
  187. streamInfo.TargetAudioCodec.FirstOrDefault(),
  188. targetWidth,
  189. targetHeight,
  190. streamInfo.TargetVideoBitDepth,
  191. streamInfo.TargetVideoBitrate,
  192. streamInfo.TargetTimestamp,
  193. streamInfo.IsDirectStream,
  194. streamInfo.RunTimeTicks ?? 0,
  195. streamInfo.TargetVideoProfile,
  196. streamInfo.TargetVideoLevel,
  197. streamInfo.TargetFramerate ?? 0,
  198. streamInfo.TargetPacketLength,
  199. streamInfo.TranscodeSeekInfo,
  200. streamInfo.IsTargetAnamorphic,
  201. streamInfo.IsTargetInterlaced,
  202. streamInfo.TargetRefFrames,
  203. streamInfo.TargetVideoStreamCount,
  204. streamInfo.TargetAudioStreamCount,
  205. streamInfo.TargetVideoCodecTag,
  206. streamInfo.IsTargetAVC);
  207. foreach (var contentFeature in contentFeatureList)
  208. {
  209. AddVideoResource(writer, filter, contentFeature, streamInfo);
  210. }
  211. var subtitleProfiles = streamInfo.GetSubtitleProfiles(_mediaEncoder, false, _serverAddress, _accessToken);
  212. foreach (var subtitle in subtitleProfiles)
  213. {
  214. if (subtitle.DeliveryMethod != SubtitleDeliveryMethod.External)
  215. {
  216. continue;
  217. }
  218. var subtitleAdded = AddSubtitleElement(writer, subtitle);
  219. if (subtitleAdded && _profile.EnableSingleSubtitleLimit)
  220. {
  221. break;
  222. }
  223. }
  224. }
  225. private bool AddSubtitleElement(XmlWriter writer, SubtitleStreamInfo info)
  226. {
  227. var subtitleProfile = _profile.SubtitleProfiles
  228. .FirstOrDefault(i => string.Equals(info.Format, i.Format, StringComparison.OrdinalIgnoreCase)
  229. && i.Method == SubtitleDeliveryMethod.External);
  230. if (subtitleProfile == null)
  231. {
  232. return false;
  233. }
  234. var subtitleMode = subtitleProfile.DidlMode;
  235. if (string.Equals(subtitleMode, "CaptionInfoEx", StringComparison.OrdinalIgnoreCase))
  236. {
  237. // <sec:CaptionInfoEx sec:type="srt">http://192.168.1.3:9999/video.srt</sec:CaptionInfoEx>
  238. // <sec:CaptionInfo sec:type="srt">http://192.168.1.3:9999/video.srt</sec:CaptionInfo>
  239. writer.WriteStartElement("sec", "CaptionInfoEx", null);
  240. writer.WriteAttributeString("sec", "type", null, info.Format.ToLowerInvariant());
  241. writer.WriteString(info.Url);
  242. writer.WriteFullEndElement();
  243. }
  244. else if (string.Equals(subtitleMode, "smi", StringComparison.OrdinalIgnoreCase))
  245. {
  246. writer.WriteStartElement(string.Empty, "res", NsDidl);
  247. writer.WriteAttributeString("protocolInfo", "http-get:*:smi/caption:*");
  248. writer.WriteString(info.Url);
  249. writer.WriteFullEndElement();
  250. }
  251. else
  252. {
  253. writer.WriteStartElement(string.Empty, "res", NsDidl);
  254. var protocolInfo = string.Format(
  255. CultureInfo.InvariantCulture,
  256. "http-get:*:text/{0}:*",
  257. info.Format.ToLowerInvariant());
  258. writer.WriteAttributeString("protocolInfo", protocolInfo);
  259. writer.WriteString(info.Url);
  260. writer.WriteFullEndElement();
  261. }
  262. return true;
  263. }
  264. private void AddVideoResource(XmlWriter writer, Filter filter, string contentFeatures, StreamInfo streamInfo)
  265. {
  266. writer.WriteStartElement(string.Empty, "res", NsDidl);
  267. var url = NormalizeDlnaMediaUrl(streamInfo.ToUrl(_serverAddress, _accessToken));
  268. var mediaSource = streamInfo.MediaSource;
  269. if (mediaSource.RunTimeTicks.HasValue)
  270. {
  271. writer.WriteAttributeString("duration", TimeSpan.FromTicks(mediaSource.RunTimeTicks.Value).ToString("c", CultureInfo.InvariantCulture));
  272. }
  273. if (filter.Contains("res@size"))
  274. {
  275. if (streamInfo.IsDirectStream || streamInfo.EstimateContentLength)
  276. {
  277. var size = streamInfo.TargetSize;
  278. if (size.HasValue)
  279. {
  280. writer.WriteAttributeString("size", size.Value.ToString(CultureInfo.InvariantCulture));
  281. }
  282. }
  283. }
  284. var totalBitrate = streamInfo.TargetTotalBitrate;
  285. var targetSampleRate = streamInfo.TargetAudioSampleRate;
  286. var targetChannels = streamInfo.TargetAudioChannels;
  287. var targetWidth = streamInfo.TargetWidth;
  288. var targetHeight = streamInfo.TargetHeight;
  289. if (targetChannels.HasValue)
  290. {
  291. writer.WriteAttributeString("nrAudioChannels", targetChannels.Value.ToString(CultureInfo.InvariantCulture));
  292. }
  293. if (filter.Contains("res@resolution"))
  294. {
  295. if (targetWidth.HasValue && targetHeight.HasValue)
  296. {
  297. writer.WriteAttributeString(
  298. "resolution",
  299. string.Format(
  300. CultureInfo.InvariantCulture,
  301. "{0}x{1}",
  302. targetWidth.Value,
  303. targetHeight.Value));
  304. }
  305. }
  306. if (targetSampleRate.HasValue)
  307. {
  308. writer.WriteAttributeString("sampleFrequency", targetSampleRate.Value.ToString(CultureInfo.InvariantCulture));
  309. }
  310. if (totalBitrate.HasValue)
  311. {
  312. writer.WriteAttributeString("bitrate", totalBitrate.Value.ToString(CultureInfo.InvariantCulture));
  313. }
  314. var mediaProfile = _profile.GetVideoMediaProfile(
  315. streamInfo.Container,
  316. streamInfo.TargetAudioCodec.FirstOrDefault(),
  317. streamInfo.TargetVideoCodec.FirstOrDefault(),
  318. streamInfo.TargetAudioBitrate,
  319. targetWidth,
  320. targetHeight,
  321. streamInfo.TargetVideoBitDepth,
  322. streamInfo.TargetVideoProfile,
  323. streamInfo.TargetVideoLevel,
  324. streamInfo.TargetFramerate ?? 0,
  325. streamInfo.TargetPacketLength,
  326. streamInfo.TargetTimestamp,
  327. streamInfo.IsTargetAnamorphic,
  328. streamInfo.IsTargetInterlaced,
  329. streamInfo.TargetRefFrames,
  330. streamInfo.TargetVideoStreamCount,
  331. streamInfo.TargetAudioStreamCount,
  332. streamInfo.TargetVideoCodecTag,
  333. streamInfo.IsTargetAVC);
  334. var filename = url.Substring(0, url.IndexOf('?', StringComparison.Ordinal));
  335. var mimeType = mediaProfile == null || string.IsNullOrEmpty(mediaProfile.MimeType)
  336. ? MimeTypes.GetMimeType(filename)
  337. : mediaProfile.MimeType;
  338. writer.WriteAttributeString(
  339. "protocolInfo",
  340. string.Format(
  341. CultureInfo.InvariantCulture,
  342. "http-get:*:{0}:{1}",
  343. mimeType,
  344. contentFeatures));
  345. writer.WriteString(url);
  346. writer.WriteFullEndElement();
  347. }
  348. private string GetDisplayName(BaseItem item, StubType? itemStubType, BaseItem context)
  349. {
  350. if (itemStubType.HasValue)
  351. {
  352. switch (itemStubType.Value)
  353. {
  354. case StubType.Latest: return _localization.GetLocalizedString("Latest");
  355. case StubType.Playlists: return _localization.GetLocalizedString("Playlists");
  356. case StubType.AlbumArtists: return _localization.GetLocalizedString("HeaderAlbumArtists");
  357. case StubType.Albums: return _localization.GetLocalizedString("Albums");
  358. case StubType.Artists: return _localization.GetLocalizedString("Artists");
  359. case StubType.Songs: return _localization.GetLocalizedString("Songs");
  360. case StubType.Genres: return _localization.GetLocalizedString("Genres");
  361. case StubType.FavoriteAlbums: return _localization.GetLocalizedString("HeaderFavoriteAlbums");
  362. case StubType.FavoriteArtists: return _localization.GetLocalizedString("HeaderFavoriteArtists");
  363. case StubType.FavoriteSongs: return _localization.GetLocalizedString("HeaderFavoriteSongs");
  364. case StubType.ContinueWatching: return _localization.GetLocalizedString("HeaderContinueWatching");
  365. case StubType.Movies: return _localization.GetLocalizedString("Movies");
  366. case StubType.Collections: return _localization.GetLocalizedString("Collections");
  367. case StubType.Favorites: return _localization.GetLocalizedString("Favorites");
  368. case StubType.NextUp: return _localization.GetLocalizedString("HeaderNextUp");
  369. case StubType.FavoriteSeries: return _localization.GetLocalizedString("HeaderFavoriteShows");
  370. case StubType.FavoriteEpisodes: return _localization.GetLocalizedString("HeaderFavoriteEpisodes");
  371. case StubType.Series: return _localization.GetLocalizedString("Shows");
  372. }
  373. }
  374. return item is Episode episode
  375. ? GetEpisodeDisplayName(episode, context)
  376. : item.Name;
  377. }
  378. /// <summary>
  379. /// Gets episode display name appropriate for the given context.
  380. /// </summary>
  381. /// <remarks>
  382. /// If context is a season, this will return a string containing just episode number and name.
  383. /// Otherwise the result will include series nams and season number.
  384. /// </remarks>
  385. /// <param name="episode">The episode.</param>
  386. /// <param name="context">Current context.</param>
  387. /// <returns>Formatted name of the episode.</returns>
  388. private string GetEpisodeDisplayName(Episode episode, BaseItem context)
  389. {
  390. string[] components;
  391. if (context is Season season)
  392. {
  393. // This is a special embedded within a season
  394. if (episode.ParentIndexNumber.HasValue && episode.ParentIndexNumber.Value == 0
  395. && season.IndexNumber.HasValue && season.IndexNumber.Value != 0)
  396. {
  397. return string.Format(
  398. CultureInfo.InvariantCulture,
  399. _localization.GetLocalizedString("ValueSpecialEpisodeName"),
  400. episode.Name);
  401. }
  402. // inside a season use simple format (ex. '12 - Episode Name')
  403. var epNumberName = GetEpisodeIndexFullName(episode);
  404. components = new[] { epNumberName, episode.Name };
  405. }
  406. else
  407. {
  408. // outside a season include series and season details (ex. 'TV Show - S05E11 - Episode Name')
  409. var epNumberName = GetEpisodeNumberDisplayName(episode);
  410. components = new[] { episode.SeriesName, epNumberName, episode.Name };
  411. }
  412. return string.Join(" - ", components.Where(NotNullOrWhiteSpace));
  413. }
  414. /// <summary>
  415. /// Gets complete episode number.
  416. /// </summary>
  417. /// <param name="episode">The episode.</param>
  418. /// <returns>For single episodes returns just the number. For double episodes - current and ending numbers.</returns>
  419. private string GetEpisodeIndexFullName(Episode episode)
  420. {
  421. var name = string.Empty;
  422. if (episode.IndexNumber.HasValue)
  423. {
  424. name += episode.IndexNumber.Value.ToString("00", CultureInfo.InvariantCulture);
  425. if (episode.IndexNumberEnd.HasValue)
  426. {
  427. name += "-" + episode.IndexNumberEnd.Value.ToString("00", CultureInfo.InvariantCulture);
  428. }
  429. }
  430. return name;
  431. }
  432. /// <summary>
  433. /// Gets episode number formatted as 'S##E##'.
  434. /// </summary>
  435. /// <param name="episode">The episode.</param>
  436. /// <returns>Formatted episode number.</returns>
  437. private string GetEpisodeNumberDisplayName(Episode episode)
  438. {
  439. var name = string.Empty;
  440. var seasonNumber = episode.Season?.IndexNumber;
  441. if (seasonNumber.HasValue)
  442. {
  443. name = "S" + seasonNumber.Value.ToString("00", CultureInfo.InvariantCulture);
  444. }
  445. var indexName = GetEpisodeIndexFullName(episode);
  446. if (!string.IsNullOrWhiteSpace(indexName))
  447. {
  448. name += "E" + indexName;
  449. }
  450. return name;
  451. }
  452. private bool NotNullOrWhiteSpace(string s) => !string.IsNullOrWhiteSpace(s);
  453. private void AddAudioResource(XmlWriter writer, BaseItem audio, string deviceId, Filter filter, StreamInfo streamInfo = null)
  454. {
  455. writer.WriteStartElement(string.Empty, "res", NsDidl);
  456. if (streamInfo == null)
  457. {
  458. var sources = _mediaSourceManager.GetStaticMediaSources(audio, true, _user);
  459. streamInfo = new StreamBuilder(_mediaEncoder, _logger).BuildAudioItem(new AudioOptions
  460. {
  461. ItemId = audio.Id,
  462. MediaSources = sources.ToArray(),
  463. Profile = _profile,
  464. DeviceId = deviceId
  465. });
  466. }
  467. var url = NormalizeDlnaMediaUrl(streamInfo.ToUrl(_serverAddress, _accessToken));
  468. var mediaSource = streamInfo.MediaSource;
  469. if (mediaSource.RunTimeTicks.HasValue)
  470. {
  471. writer.WriteAttributeString("duration", TimeSpan.FromTicks(mediaSource.RunTimeTicks.Value).ToString("c", CultureInfo.InvariantCulture));
  472. }
  473. if (filter.Contains("res@size"))
  474. {
  475. if (streamInfo.IsDirectStream || streamInfo.EstimateContentLength)
  476. {
  477. var size = streamInfo.TargetSize;
  478. if (size.HasValue)
  479. {
  480. writer.WriteAttributeString("size", size.Value.ToString(CultureInfo.InvariantCulture));
  481. }
  482. }
  483. }
  484. var targetAudioBitrate = streamInfo.TargetAudioBitrate;
  485. var targetSampleRate = streamInfo.TargetAudioSampleRate;
  486. var targetChannels = streamInfo.TargetAudioChannels;
  487. var targetAudioBitDepth = streamInfo.TargetAudioBitDepth;
  488. if (targetChannels.HasValue)
  489. {
  490. writer.WriteAttributeString("nrAudioChannels", targetChannels.Value.ToString(CultureInfo.InvariantCulture));
  491. }
  492. if (targetSampleRate.HasValue)
  493. {
  494. writer.WriteAttributeString("sampleFrequency", targetSampleRate.Value.ToString(CultureInfo.InvariantCulture));
  495. }
  496. if (targetAudioBitrate.HasValue)
  497. {
  498. writer.WriteAttributeString("bitrate", targetAudioBitrate.Value.ToString(CultureInfo.InvariantCulture));
  499. }
  500. var mediaProfile = _profile.GetAudioMediaProfile(
  501. streamInfo.Container,
  502. streamInfo.TargetAudioCodec.FirstOrDefault(),
  503. targetChannels,
  504. targetAudioBitrate,
  505. targetSampleRate,
  506. targetAudioBitDepth);
  507. var filename = url.Substring(0, url.IndexOf('?', StringComparison.Ordinal));
  508. var mimeType = mediaProfile == null || string.IsNullOrEmpty(mediaProfile.MimeType)
  509. ? MimeTypes.GetMimeType(filename)
  510. : mediaProfile.MimeType;
  511. var contentFeatures = ContentFeatureBuilder.BuildAudioHeader(
  512. _profile,
  513. streamInfo.Container,
  514. streamInfo.TargetAudioCodec.FirstOrDefault(),
  515. targetAudioBitrate,
  516. targetSampleRate,
  517. targetChannels,
  518. targetAudioBitDepth,
  519. streamInfo.IsDirectStream,
  520. streamInfo.RunTimeTicks ?? 0,
  521. streamInfo.TranscodeSeekInfo);
  522. writer.WriteAttributeString(
  523. "protocolInfo",
  524. string.Format(
  525. CultureInfo.InvariantCulture,
  526. "http-get:*:{0}:{1}",
  527. mimeType,
  528. contentFeatures));
  529. writer.WriteString(url);
  530. writer.WriteFullEndElement();
  531. }
  532. public static bool IsIdRoot(string id)
  533. => string.IsNullOrWhiteSpace(id)
  534. || string.Equals(id, "0", StringComparison.OrdinalIgnoreCase)
  535. // Samsung sometimes uses 1 as root
  536. || string.Equals(id, "1", StringComparison.OrdinalIgnoreCase);
  537. public void WriteFolderElement(XmlWriter writer, BaseItem folder, StubType? stubType, BaseItem context, int childCount, Filter filter, string requestedId = null)
  538. {
  539. writer.WriteStartElement(string.Empty, "container", NsDidl);
  540. writer.WriteAttributeString("restricted", "1");
  541. writer.WriteAttributeString("searchable", "1");
  542. writer.WriteAttributeString("childCount", childCount.ToString(CultureInfo.InvariantCulture));
  543. var clientId = GetClientId(folder, stubType);
  544. if (string.Equals(requestedId, "0", StringComparison.Ordinal))
  545. {
  546. writer.WriteAttributeString("id", "0");
  547. writer.WriteAttributeString("parentID", "-1");
  548. }
  549. else
  550. {
  551. writer.WriteAttributeString("id", clientId);
  552. if (context != null)
  553. {
  554. writer.WriteAttributeString("parentID", GetClientId(context, null));
  555. }
  556. else
  557. {
  558. var parent = folder.DisplayParentId;
  559. if (parent.Equals(default))
  560. {
  561. writer.WriteAttributeString("parentID", "0");
  562. }
  563. else
  564. {
  565. writer.WriteAttributeString("parentID", GetClientId(parent, null));
  566. }
  567. }
  568. }
  569. AddGeneralProperties(folder, stubType, context, writer, filter);
  570. AddCover(folder, stubType, writer);
  571. writer.WriteFullEndElement();
  572. }
  573. private void AddSamsungBookmarkInfo(BaseItem item, User user, XmlWriter writer, StreamInfo streamInfo)
  574. {
  575. if (!item.SupportsPositionTicksResume || item is Folder)
  576. {
  577. return;
  578. }
  579. XmlAttribute secAttribute = null;
  580. foreach (var attribute in _profile.XmlRootAttributes)
  581. {
  582. if (string.Equals(attribute.Name, "xmlns:sec", StringComparison.OrdinalIgnoreCase))
  583. {
  584. secAttribute = attribute;
  585. break;
  586. }
  587. }
  588. // Not a samsung device
  589. if (secAttribute == null)
  590. {
  591. return;
  592. }
  593. var userdata = _userDataManager.GetUserData(user, item);
  594. var playbackPositionTicks = (streamInfo != null && streamInfo.StartPositionTicks > 0) ? streamInfo.StartPositionTicks : userdata.PlaybackPositionTicks;
  595. if (playbackPositionTicks > 0)
  596. {
  597. var elementValue = string.Format(
  598. CultureInfo.InvariantCulture,
  599. "BM={0}",
  600. Convert.ToInt32(TimeSpan.FromTicks(playbackPositionTicks).TotalSeconds));
  601. AddValue(writer, "sec", "dcmInfo", elementValue, secAttribute.Value);
  602. }
  603. }
  604. /// <summary>
  605. /// Adds fields used by both items and folders.
  606. /// </summary>
  607. private void AddCommonFields(BaseItem item, StubType? itemStubType, BaseItem context, XmlWriter writer, Filter filter)
  608. {
  609. // Don't filter on dc:title because not all devices will include it in the filter
  610. // MediaMonkey for example won't display content without a title
  611. // if (filter.Contains("dc:title"))
  612. {
  613. AddValue(writer, "dc", "title", GetDisplayName(item, itemStubType, context), NsDc);
  614. }
  615. WriteObjectClass(writer, item, itemStubType);
  616. if (filter.Contains("dc:date"))
  617. {
  618. if (item.PremiereDate.HasValue)
  619. {
  620. AddValue(writer, "dc", "date", item.PremiereDate.Value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), NsDc);
  621. }
  622. }
  623. if (filter.Contains("upnp:genre"))
  624. {
  625. foreach (var genre in item.Genres)
  626. {
  627. AddValue(writer, "upnp", "genre", genre, NsUpnp);
  628. }
  629. }
  630. foreach (var studio in item.Studios)
  631. {
  632. AddValue(writer, "upnp", "publisher", studio, NsUpnp);
  633. }
  634. if (item is not Folder)
  635. {
  636. if (filter.Contains("dc:description"))
  637. {
  638. var desc = item.Overview;
  639. if (!string.IsNullOrWhiteSpace(desc))
  640. {
  641. AddValue(writer, "dc", "description", desc, NsDc);
  642. }
  643. }
  644. // if (filter.Contains("upnp:longDescription"))
  645. // {
  646. // if (!string.IsNullOrWhiteSpace(item.Overview))
  647. // {
  648. // AddValue(writer, "upnp", "longDescription", item.Overview, NsUpnp);
  649. // }
  650. // }
  651. }
  652. if (!string.IsNullOrEmpty(item.OfficialRating))
  653. {
  654. if (filter.Contains("dc:rating"))
  655. {
  656. AddValue(writer, "dc", "rating", item.OfficialRating, NsDc);
  657. }
  658. if (filter.Contains("upnp:rating"))
  659. {
  660. AddValue(writer, "upnp", "rating", item.OfficialRating, NsUpnp);
  661. }
  662. }
  663. AddPeople(item, writer);
  664. }
  665. private void WriteObjectClass(XmlWriter writer, BaseItem item, StubType? stubType)
  666. {
  667. // More types here
  668. // http://oss.linn.co.uk/repos/Public/LibUpnpCil/DidlLite/UpnpAv/Test/TestDidlLite.cs
  669. writer.WriteStartElement("upnp", "class", NsUpnp);
  670. if (item.IsDisplayedAsFolder || stubType.HasValue)
  671. {
  672. string classType = null;
  673. if (!_profile.RequiresPlainFolders)
  674. {
  675. if (item is MusicAlbum)
  676. {
  677. classType = "object.container.album.musicAlbum";
  678. }
  679. else if (item is MusicArtist)
  680. {
  681. classType = "object.container.person.musicArtist";
  682. }
  683. else if (item is Series || item is Season || item is BoxSet || item is Video)
  684. {
  685. classType = "object.container.album.videoAlbum";
  686. }
  687. else if (item is Playlist)
  688. {
  689. classType = "object.container.playlistContainer";
  690. }
  691. else if (item is PhotoAlbum)
  692. {
  693. classType = "object.container.album.photoAlbum";
  694. }
  695. }
  696. writer.WriteString(classType ?? "object.container.storageFolder");
  697. }
  698. else if (string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase))
  699. {
  700. writer.WriteString("object.item.audioItem.musicTrack");
  701. }
  702. else if (string.Equals(item.MediaType, MediaType.Photo, StringComparison.OrdinalIgnoreCase))
  703. {
  704. writer.WriteString("object.item.imageItem.photo");
  705. }
  706. else if (string.Equals(item.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase))
  707. {
  708. if (!_profile.RequiresPlainVideoItems && item is Movie)
  709. {
  710. writer.WriteString("object.item.videoItem.movie");
  711. }
  712. else if (!_profile.RequiresPlainVideoItems && item is MusicVideo)
  713. {
  714. writer.WriteString("object.item.videoItem.musicVideoClip");
  715. }
  716. else
  717. {
  718. writer.WriteString("object.item.videoItem");
  719. }
  720. }
  721. else if (item is MusicGenre)
  722. {
  723. writer.WriteString(_profile.RequiresPlainFolders ? "object.container.storageFolder" : "object.container.genre.musicGenre");
  724. }
  725. else if (item is Genre)
  726. {
  727. writer.WriteString(_profile.RequiresPlainFolders ? "object.container.storageFolder" : "object.container.genre");
  728. }
  729. else
  730. {
  731. writer.WriteString("object.item");
  732. }
  733. writer.WriteFullEndElement();
  734. }
  735. private void AddPeople(BaseItem item, XmlWriter writer)
  736. {
  737. if (!item.SupportsPeople)
  738. {
  739. return;
  740. }
  741. var types = new[]
  742. {
  743. PersonType.Director,
  744. PersonType.Writer,
  745. PersonType.Producer,
  746. PersonType.Composer,
  747. "creator"
  748. };
  749. // Seeing some LG models locking up due content with large lists of people
  750. // The actual issue might just be due to processing a more metadata than it can handle
  751. var people = _libraryManager.GetPeople(
  752. new InternalPeopleQuery
  753. {
  754. ItemId = item.Id,
  755. Limit = 6
  756. });
  757. foreach (var actor in people)
  758. {
  759. var type = types.FirstOrDefault(i => string.Equals(i, actor.Type, StringComparison.OrdinalIgnoreCase) || string.Equals(i, actor.Role, StringComparison.OrdinalIgnoreCase))
  760. ?? PersonType.Actor;
  761. AddValue(writer, "upnp", type.ToLowerInvariant(), actor.Name, NsUpnp);
  762. }
  763. }
  764. private void AddGeneralProperties(BaseItem item, StubType? itemStubType, BaseItem context, XmlWriter writer, Filter filter)
  765. {
  766. AddCommonFields(item, itemStubType, context, writer, filter);
  767. var hasAlbumArtists = item as IHasAlbumArtist;
  768. if (item is IHasArtist hasArtists)
  769. {
  770. foreach (var artist in hasArtists.Artists)
  771. {
  772. AddValue(writer, "upnp", "artist", artist, NsUpnp);
  773. AddValue(writer, "dc", "creator", artist, NsDc);
  774. // If it doesn't support album artists (musicvideo), then tag as both
  775. if (hasAlbumArtists == null)
  776. {
  777. AddAlbumArtist(writer, artist);
  778. }
  779. }
  780. }
  781. if (hasAlbumArtists != null)
  782. {
  783. foreach (var albumArtist in hasAlbumArtists.AlbumArtists)
  784. {
  785. AddAlbumArtist(writer, albumArtist);
  786. }
  787. }
  788. if (!string.IsNullOrWhiteSpace(item.Album))
  789. {
  790. AddValue(writer, "upnp", "album", item.Album, NsUpnp);
  791. }
  792. if (item.IndexNumber.HasValue)
  793. {
  794. AddValue(writer, "upnp", "originalTrackNumber", item.IndexNumber.Value.ToString(CultureInfo.InvariantCulture), NsUpnp);
  795. if (item is Episode)
  796. {
  797. AddValue(writer, "upnp", "episodeNumber", item.IndexNumber.Value.ToString(CultureInfo.InvariantCulture), NsUpnp);
  798. }
  799. }
  800. }
  801. private void AddAlbumArtist(XmlWriter writer, string name)
  802. {
  803. try
  804. {
  805. writer.WriteStartElement("upnp", "artist", NsUpnp);
  806. writer.WriteAttributeString("role", "AlbumArtist");
  807. writer.WriteString(name);
  808. writer.WriteFullEndElement();
  809. }
  810. catch (XmlException ex)
  811. {
  812. _logger.LogError(ex, "Error adding xml value: {Value}", name);
  813. }
  814. }
  815. private void AddValue(XmlWriter writer, string prefix, string name, string value, string namespaceUri)
  816. {
  817. try
  818. {
  819. writer.WriteElementString(prefix, name, namespaceUri, value);
  820. }
  821. catch (XmlException ex)
  822. {
  823. _logger.LogError(ex, "Error adding xml value: {Value}", value);
  824. }
  825. }
  826. private void AddCover(BaseItem item, StubType? stubType, XmlWriter writer)
  827. {
  828. ImageDownloadInfo imageInfo = GetImageInfo(item);
  829. if (imageInfo == null)
  830. {
  831. return;
  832. }
  833. // TODO: Remove these default values
  834. var albumArtUrlInfo = GetImageUrl(
  835. imageInfo,
  836. _profile.MaxAlbumArtWidth ?? 10000,
  837. _profile.MaxAlbumArtHeight ?? 10000,
  838. "jpg");
  839. writer.WriteStartElement("upnp", "albumArtURI", NsUpnp);
  840. if (!string.IsNullOrEmpty(_profile.AlbumArtPn))
  841. {
  842. writer.WriteAttributeString("dlna", "profileID", NsDlna, _profile.AlbumArtPn);
  843. }
  844. writer.WriteString(albumArtUrlInfo.Url);
  845. writer.WriteFullEndElement();
  846. // TODO: Remove these default values
  847. var iconUrlInfo = GetImageUrl(
  848. imageInfo,
  849. _profile.MaxIconWidth ?? 48,
  850. _profile.MaxIconHeight ?? 48,
  851. "jpg");
  852. writer.WriteElementString("upnp", "icon", NsUpnp, iconUrlInfo.Url);
  853. if (!_profile.EnableAlbumArtInDidl)
  854. {
  855. if (string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase)
  856. || string.Equals(item.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase))
  857. {
  858. if (!stubType.HasValue)
  859. {
  860. return;
  861. }
  862. }
  863. }
  864. if (!_profile.EnableSingleAlbumArtLimit || string.Equals(item.MediaType, MediaType.Photo, StringComparison.OrdinalIgnoreCase))
  865. {
  866. AddImageResElement(item, writer, 4096, 4096, "jpg", "JPEG_LRG");
  867. AddImageResElement(item, writer, 1024, 768, "jpg", "JPEG_MED");
  868. AddImageResElement(item, writer, 640, 480, "jpg", "JPEG_SM");
  869. AddImageResElement(item, writer, 4096, 4096, "png", "PNG_LRG");
  870. AddImageResElement(item, writer, 160, 160, "png", "PNG_TN");
  871. }
  872. AddImageResElement(item, writer, 160, 160, "jpg", "JPEG_TN");
  873. }
  874. private void AddImageResElement(
  875. BaseItem item,
  876. XmlWriter writer,
  877. int maxWidth,
  878. int maxHeight,
  879. string format,
  880. string org_Pn)
  881. {
  882. var imageInfo = GetImageInfo(item);
  883. if (imageInfo == null)
  884. {
  885. return;
  886. }
  887. var albumartUrlInfo = GetImageUrl(imageInfo, maxWidth, maxHeight, format);
  888. writer.WriteStartElement(string.Empty, "res", NsDidl);
  889. // Images must have a reported size or many clients (Bubble upnp), will only use the first thumbnail
  890. // rather than using a larger one when available
  891. var width = albumartUrlInfo.Width ?? maxWidth;
  892. var height = albumartUrlInfo.Height ?? maxHeight;
  893. var contentFeatures = ContentFeatureBuilder.BuildImageHeader(_profile, format, width, height, imageInfo.IsDirectStream, org_Pn);
  894. writer.WriteAttributeString(
  895. "protocolInfo",
  896. string.Format(
  897. CultureInfo.InvariantCulture,
  898. "http-get:*:{0}:{1}",
  899. MimeTypes.GetMimeType("file." + format),
  900. contentFeatures));
  901. writer.WriteAttributeString(
  902. "resolution",
  903. string.Format(CultureInfo.InvariantCulture, "{0}x{1}", width, height));
  904. writer.WriteString(albumartUrlInfo.Url);
  905. writer.WriteFullEndElement();
  906. }
  907. private ImageDownloadInfo GetImageInfo(BaseItem item)
  908. {
  909. if (item.HasImage(ImageType.Primary))
  910. {
  911. return GetImageInfo(item, ImageType.Primary);
  912. }
  913. if (item.HasImage(ImageType.Thumb))
  914. {
  915. return GetImageInfo(item, ImageType.Thumb);
  916. }
  917. if (item.HasImage(ImageType.Backdrop))
  918. {
  919. if (item is Channel)
  920. {
  921. return GetImageInfo(item, ImageType.Backdrop);
  922. }
  923. }
  924. // For audio tracks without art use album art if available.
  925. if (item is Audio audioItem)
  926. {
  927. var album = audioItem.AlbumEntity;
  928. return album != null && album.HasImage(ImageType.Primary)
  929. ? GetImageInfo(album, ImageType.Primary)
  930. : null;
  931. }
  932. // Don't look beyond album/playlist level. Metadata service may assign an image from a different album/show to the parent folder.
  933. if (item is MusicAlbum || item is Playlist)
  934. {
  935. return null;
  936. }
  937. // For other item types check parents, but be aware that image retrieved from a parent may be not suitable for this media item.
  938. var parentWithImage = GetFirstParentWithImageBelowUserRoot(item);
  939. if (parentWithImage != null)
  940. {
  941. return GetImageInfo(parentWithImage, ImageType.Primary);
  942. }
  943. return null;
  944. }
  945. private BaseItem GetFirstParentWithImageBelowUserRoot(BaseItem item)
  946. {
  947. if (item == null)
  948. {
  949. return null;
  950. }
  951. if (item.HasImage(ImageType.Primary))
  952. {
  953. return item;
  954. }
  955. var parent = item.GetParent();
  956. if (parent is UserRootFolder)
  957. {
  958. return null;
  959. }
  960. // terminate in case we went past user root folder (unlikely?)
  961. if (parent is Folder folder && folder.IsRoot)
  962. {
  963. return null;
  964. }
  965. return GetFirstParentWithImageBelowUserRoot(parent);
  966. }
  967. private ImageDownloadInfo GetImageInfo(BaseItem item, ImageType type)
  968. {
  969. var imageInfo = item.GetImageInfo(type, 0);
  970. string tag = null;
  971. try
  972. {
  973. tag = _imageProcessor.GetImageCacheTag(item, type);
  974. }
  975. catch (Exception ex)
  976. {
  977. _logger.LogError(ex, "Error getting image cache tag");
  978. }
  979. int? width = imageInfo.Width;
  980. int? height = imageInfo.Height;
  981. if (width == 0 || height == 0)
  982. {
  983. width = null;
  984. height = null;
  985. }
  986. else if (width == -1 || height == -1)
  987. {
  988. width = null;
  989. height = null;
  990. }
  991. var inputFormat = (Path.GetExtension(imageInfo.Path) ?? string.Empty)
  992. .TrimStart('.')
  993. .Replace("jpeg", "jpg", StringComparison.OrdinalIgnoreCase);
  994. return new ImageDownloadInfo
  995. {
  996. ItemId = item.Id,
  997. Type = type,
  998. ImageTag = tag,
  999. Width = width,
  1000. Height = height,
  1001. Format = inputFormat,
  1002. ItemImageInfo = imageInfo
  1003. };
  1004. }
  1005. public static string GetClientId(BaseItem item, StubType? stubType)
  1006. {
  1007. return GetClientId(item.Id, stubType);
  1008. }
  1009. public static string GetClientId(Guid idValue, StubType? stubType)
  1010. {
  1011. var id = idValue.ToString("N", CultureInfo.InvariantCulture);
  1012. if (stubType.HasValue)
  1013. {
  1014. id = stubType.Value.ToString().ToLowerInvariant() + "_" + id;
  1015. }
  1016. return id;
  1017. }
  1018. private (string Url, int? Width, int? Height) GetImageUrl(ImageDownloadInfo info, int maxWidth, int maxHeight, string format)
  1019. {
  1020. var url = string.Format(
  1021. CultureInfo.InvariantCulture,
  1022. "{0}/Items/{1}/Images/{2}/0/{3}/{4}/{5}/{6}/0/0",
  1023. _serverAddress,
  1024. info.ItemId.ToString("N", CultureInfo.InvariantCulture),
  1025. info.Type,
  1026. info.ImageTag,
  1027. format,
  1028. maxWidth.ToString(CultureInfo.InvariantCulture),
  1029. maxHeight.ToString(CultureInfo.InvariantCulture));
  1030. var width = info.Width;
  1031. var height = info.Height;
  1032. info.IsDirectStream = false;
  1033. if (width.HasValue && height.HasValue)
  1034. {
  1035. var newSize = DrawingUtils.Resize(new ImageDimensions(width.Value, height.Value), 0, 0, maxWidth, maxHeight);
  1036. width = newSize.Width;
  1037. height = newSize.Height;
  1038. var normalizedFormat = format
  1039. .Replace("jpeg", "jpg", StringComparison.OrdinalIgnoreCase);
  1040. if (string.Equals(info.Format, normalizedFormat, StringComparison.OrdinalIgnoreCase))
  1041. {
  1042. info.IsDirectStream = maxWidth >= width.Value && maxHeight >= height.Value;
  1043. }
  1044. }
  1045. // just lie
  1046. info.IsDirectStream = true;
  1047. return (url, width, height);
  1048. }
  1049. private class ImageDownloadInfo
  1050. {
  1051. internal Guid ItemId { get; set; }
  1052. internal string ImageTag { get; set; }
  1053. internal ImageType Type { get; set; }
  1054. internal int? Width { get; set; }
  1055. internal int? Height { get; set; }
  1056. internal bool IsDirectStream { get; set; }
  1057. internal string Format { get; set; }
  1058. internal ItemImageInfo ItemImageInfo { get; set; }
  1059. }
  1060. }
  1061. }