DidlBuilder.cs 46 KB

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