DidlBuilder.cs 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267
  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.ToArray(sources.Count),
  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.FirstOrDefault(),
  180. streamInfo.TargetAudioCodec.FirstOrDefault(),
  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(_mediaEncoder, 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.FirstOrDefault(),
  297. streamInfo.TargetVideoCodec.FirstOrDefault(),
  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.Latest)
  329. {
  330. return _localization.GetLocalizedString("Latest");
  331. }
  332. if (itemStubType.HasValue && itemStubType.Value == StubType.Playlists)
  333. {
  334. return _localization.GetLocalizedString("Playlists");
  335. }
  336. if (itemStubType.HasValue && itemStubType.Value == StubType.AlbumArtists)
  337. {
  338. return _localization.GetLocalizedString("HeaderAlbumArtists");
  339. }
  340. if (itemStubType.HasValue && itemStubType.Value == StubType.Albums)
  341. {
  342. return _localization.GetLocalizedString("Albums");
  343. }
  344. if (itemStubType.HasValue && itemStubType.Value == StubType.Artists)
  345. {
  346. return _localization.GetLocalizedString("Artists");
  347. }
  348. if (itemStubType.HasValue && itemStubType.Value == StubType.Songs)
  349. {
  350. return _localization.GetLocalizedString("Songs");
  351. }
  352. if (itemStubType.HasValue && itemStubType.Value == StubType.Genres)
  353. {
  354. return _localization.GetLocalizedString("Genres");
  355. }
  356. if (itemStubType.HasValue && itemStubType.Value == StubType.FavoriteAlbums)
  357. {
  358. return _localization.GetLocalizedString("HeaderFavoriteAlbums");
  359. }
  360. if (itemStubType.HasValue && itemStubType.Value == StubType.FavoriteArtists)
  361. {
  362. return _localization.GetLocalizedString("HeaderFavoriteArtists");
  363. }
  364. if (itemStubType.HasValue && itemStubType.Value == StubType.FavoriteSongs)
  365. {
  366. return _localization.GetLocalizedString("HeaderFavoriteSongs");
  367. }
  368. if (itemStubType.HasValue && itemStubType.Value == StubType.ContinueWatching)
  369. {
  370. return _localization.GetLocalizedString("HeaderContinueWatching");
  371. }
  372. if (itemStubType.HasValue && itemStubType.Value == StubType.Movies)
  373. {
  374. return _localization.GetLocalizedString("Movies");
  375. }
  376. if (itemStubType.HasValue && itemStubType.Value == StubType.Collections)
  377. {
  378. return _localization.GetLocalizedString("Collections");
  379. }
  380. if (itemStubType.HasValue && itemStubType.Value == StubType.Favorites)
  381. {
  382. return _localization.GetLocalizedString("Favorites");
  383. }
  384. if (itemStubType.HasValue && itemStubType.Value == StubType.NextUp)
  385. {
  386. return _localization.GetLocalizedString("HeaderNextUp");
  387. }
  388. if (itemStubType.HasValue && itemStubType.Value == StubType.FavoriteSeries)
  389. {
  390. return _localization.GetLocalizedString("HeaderFavoriteShows");
  391. }
  392. if (itemStubType.HasValue && itemStubType.Value == StubType.FavoriteEpisodes)
  393. {
  394. return _localization.GetLocalizedString("HeaderFavoriteEpisodes");
  395. }
  396. if (itemStubType.HasValue && itemStubType.Value == StubType.Series)
  397. {
  398. return _localization.GetLocalizedString("Shows");
  399. }
  400. var episode = item as Episode;
  401. var season = context as Season;
  402. if (episode != null && season != null)
  403. {
  404. // This is a special embedded within a season
  405. if (item.ParentIndexNumber.HasValue && item.ParentIndexNumber.Value == 0)
  406. {
  407. if (season.IndexNumber.HasValue && season.IndexNumber.Value != 0)
  408. {
  409. return string.Format(_localization.GetLocalizedString("ValueSpecialEpisodeName"), item.Name);
  410. }
  411. }
  412. if (item.IndexNumber.HasValue)
  413. {
  414. var number = item.IndexNumber.Value.ToString("00", CultureInfo.InvariantCulture);
  415. if (episode.IndexNumberEnd.HasValue)
  416. {
  417. number += "-" + episode.IndexNumberEnd.Value.ToString("00", CultureInfo.InvariantCulture);
  418. }
  419. return number + " - " + item.Name;
  420. }
  421. }
  422. return item.Name;
  423. }
  424. private void AddAudioResource(DlnaOptions options, XmlWriter writer, IHasMediaSources audio, string deviceId, Filter filter, StreamInfo streamInfo = null)
  425. {
  426. writer.WriteStartElement(string.Empty, "res", NS_DIDL);
  427. if (streamInfo == null)
  428. {
  429. var sources = _mediaSourceManager.GetStaticMediaSources(audio, true, _user);
  430. streamInfo = new StreamBuilder(_mediaEncoder, GetStreamBuilderLogger(options)).BuildAudioItem(new AudioOptions
  431. {
  432. ItemId = GetClientId(audio),
  433. MediaSources = sources.ToArray(sources.Count),
  434. Profile = _profile,
  435. DeviceId = deviceId
  436. });
  437. }
  438. var url = streamInfo.ToDlnaUrl(_serverAddress, _accessToken);
  439. var mediaSource = streamInfo.MediaSource;
  440. if (mediaSource.RunTimeTicks.HasValue)
  441. {
  442. writer.WriteAttributeString("duration", TimeSpan.FromTicks(mediaSource.RunTimeTicks.Value).ToString("c", _usCulture));
  443. }
  444. if (filter.Contains("res@size"))
  445. {
  446. if (streamInfo.IsDirectStream || streamInfo.EstimateContentLength)
  447. {
  448. var size = streamInfo.TargetSize;
  449. if (size.HasValue)
  450. {
  451. writer.WriteAttributeString("size", size.Value.ToString(_usCulture));
  452. }
  453. }
  454. }
  455. var targetAudioBitrate = streamInfo.TargetAudioBitrate;
  456. var targetSampleRate = streamInfo.TargetAudioSampleRate;
  457. var targetChannels = streamInfo.TargetAudioChannels;
  458. var targetAudioBitDepth = streamInfo.TargetAudioBitDepth;
  459. if (targetChannels.HasValue)
  460. {
  461. writer.WriteAttributeString("nrAudioChannels", targetChannels.Value.ToString(_usCulture));
  462. }
  463. if (targetSampleRate.HasValue)
  464. {
  465. writer.WriteAttributeString("sampleFrequency", targetSampleRate.Value.ToString(_usCulture));
  466. }
  467. if (targetAudioBitrate.HasValue)
  468. {
  469. writer.WriteAttributeString("bitrate", targetAudioBitrate.Value.ToString(_usCulture));
  470. }
  471. var mediaProfile = _profile.GetAudioMediaProfile(streamInfo.Container,
  472. streamInfo.TargetAudioCodec.FirstOrDefault(),
  473. targetChannels,
  474. targetAudioBitrate,
  475. targetSampleRate,
  476. targetAudioBitDepth);
  477. var filename = url.Substring(0, url.IndexOf('?'));
  478. var mimeType = mediaProfile == null || string.IsNullOrEmpty(mediaProfile.MimeType)
  479. ? GetMimeType(filename)
  480. : mediaProfile.MimeType;
  481. var contentFeatures = new ContentFeatureBuilder(_profile).BuildAudioHeader(streamInfo.Container,
  482. streamInfo.TargetAudioCodec.FirstOrDefault(),
  483. targetAudioBitrate,
  484. targetSampleRate,
  485. targetChannels,
  486. targetAudioBitDepth,
  487. streamInfo.IsDirectStream,
  488. streamInfo.RunTimeTicks,
  489. streamInfo.TranscodeSeekInfo);
  490. writer.WriteAttributeString("protocolInfo", String.Format(
  491. "http-get:*:{0}:{1}",
  492. mimeType,
  493. contentFeatures
  494. ));
  495. writer.WriteString(url);
  496. writer.WriteFullEndElement();
  497. }
  498. public static bool IsIdRoot(string id)
  499. {
  500. if (string.IsNullOrWhiteSpace(id) ||
  501. string.Equals(id, "0", StringComparison.OrdinalIgnoreCase)
  502. // Samsung sometimes uses 1 as root
  503. || string.Equals(id, "1", StringComparison.OrdinalIgnoreCase))
  504. {
  505. return true;
  506. }
  507. return false;
  508. }
  509. public void WriteFolderElement(XmlWriter writer, BaseItem folder, StubType? stubType, BaseItem context, int childCount, Filter filter, string requestedId = null)
  510. {
  511. writer.WriteStartElement(string.Empty, "container", NS_DIDL);
  512. writer.WriteAttributeString("restricted", "0");
  513. writer.WriteAttributeString("searchable", "1");
  514. writer.WriteAttributeString("childCount", childCount.ToString(_usCulture));
  515. var clientId = GetClientId(folder, stubType);
  516. if (string.Equals(requestedId, "0"))
  517. {
  518. writer.WriteAttributeString("id", "0");
  519. writer.WriteAttributeString("parentID", "-1");
  520. }
  521. else
  522. {
  523. writer.WriteAttributeString("id", clientId);
  524. if (context != null)
  525. {
  526. writer.WriteAttributeString("parentID", GetClientId(context, null));
  527. }
  528. else
  529. {
  530. var parent = folder.DisplayParentId;
  531. if (!parent.HasValue)
  532. {
  533. writer.WriteAttributeString("parentID", "0");
  534. }
  535. else
  536. {
  537. writer.WriteAttributeString("parentID", GetClientId(parent.Value, null));
  538. }
  539. }
  540. }
  541. AddGeneralProperties(folder, stubType, context, writer, filter);
  542. AddCover(folder, context, stubType, writer);
  543. writer.WriteFullEndElement();
  544. }
  545. private void AddSamsungBookmarkInfo(BaseItem item, User user, XmlWriter writer)
  546. {
  547. if (!item.SupportsPositionTicksResume || item is Folder)
  548. {
  549. return;
  550. }
  551. MediaBrowser.Model.Dlna.XmlAttribute secAttribute = null;
  552. foreach (var attribute in _profile.XmlRootAttributes)
  553. {
  554. if (string.Equals(attribute.Name, "xmlns:sec", StringComparison.OrdinalIgnoreCase))
  555. {
  556. secAttribute = attribute;
  557. break;
  558. }
  559. }
  560. // Not a samsung device
  561. if (secAttribute == null)
  562. {
  563. return;
  564. }
  565. var userdata = _userDataManager.GetUserData(user.Id, item);
  566. if (userdata.PlaybackPositionTicks > 0)
  567. {
  568. var elementValue = string.Format("BM={0}", Convert.ToInt32(TimeSpan.FromTicks(userdata.PlaybackPositionTicks).TotalSeconds).ToString(_usCulture));
  569. AddValue(writer, "sec", "dcmInfo", elementValue, secAttribute.Value);
  570. }
  571. }
  572. /// <summary>
  573. /// Adds fields used by both items and folders
  574. /// </summary>
  575. private void AddCommonFields(BaseItem item, StubType? itemStubType, BaseItem context, XmlWriter writer, Filter filter)
  576. {
  577. // Don't filter on dc:title because not all devices will include it in the filter
  578. // MediaMonkey for example won't display content without a title
  579. //if (filter.Contains("dc:title"))
  580. {
  581. AddValue(writer, "dc", "title", GetDisplayName(item, itemStubType, context), NS_DC);
  582. }
  583. WriteObjectClass(writer, item, itemStubType);
  584. if (filter.Contains("dc:date"))
  585. {
  586. if (item.PremiereDate.HasValue)
  587. {
  588. AddValue(writer, "dc", "date", item.PremiereDate.Value.ToString("o"), NS_DC);
  589. }
  590. }
  591. if (filter.Contains("upnp:genre"))
  592. {
  593. foreach (var genre in item.Genres)
  594. {
  595. AddValue(writer, "upnp", "genre", genre, NS_UPNP);
  596. }
  597. }
  598. foreach (var studio in item.Studios)
  599. {
  600. AddValue(writer, "upnp", "publisher", studio, NS_UPNP);
  601. }
  602. if (filter.Contains("dc:description"))
  603. {
  604. var desc = item.Overview;
  605. if (!string.IsNullOrWhiteSpace(desc))
  606. {
  607. AddValue(writer, "dc", "description", desc, NS_DC);
  608. }
  609. }
  610. if (filter.Contains("upnp:longDescription"))
  611. {
  612. if (!string.IsNullOrWhiteSpace(item.Overview))
  613. {
  614. AddValue(writer, "upnp", "longDescription", item.Overview, NS_UPNP);
  615. }
  616. }
  617. if (!string.IsNullOrEmpty(item.OfficialRating))
  618. {
  619. if (filter.Contains("dc:rating"))
  620. {
  621. AddValue(writer, "dc", "rating", item.OfficialRating, NS_DC);
  622. }
  623. if (filter.Contains("upnp:rating"))
  624. {
  625. AddValue(writer, "upnp", "rating", item.OfficialRating, NS_UPNP);
  626. }
  627. }
  628. AddPeople(item, writer);
  629. }
  630. private void WriteObjectClass(XmlWriter writer, BaseItem item, StubType? stubType)
  631. {
  632. // More types here
  633. // http://oss.linn.co.uk/repos/Public/LibUpnpCil/DidlLite/UpnpAv/Test/TestDidlLite.cs
  634. writer.WriteStartElement("upnp", "class", NS_UPNP);
  635. if (item.IsDisplayedAsFolder || stubType.HasValue)
  636. {
  637. string classType = null;
  638. if (!_profile.RequiresPlainFolders)
  639. {
  640. if (item is MusicAlbum)
  641. {
  642. classType = "object.container.album.musicAlbum";
  643. }
  644. else if (item is MusicArtist)
  645. {
  646. classType = "object.container.person.musicArtist";
  647. }
  648. else if (item is Series || item is Season || item is BoxSet || item is Video)
  649. {
  650. classType = "object.container.album.videoAlbum";
  651. }
  652. else if (item is Playlist)
  653. {
  654. classType = "object.container.playlistContainer";
  655. }
  656. else if (item is PhotoAlbum)
  657. {
  658. classType = "object.container.album.photoAlbum";
  659. }
  660. }
  661. writer.WriteString(classType ?? "object.container.storageFolder");
  662. }
  663. else if (string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase))
  664. {
  665. writer.WriteString("object.item.audioItem.musicTrack");
  666. }
  667. else if (string.Equals(item.MediaType, MediaType.Photo, StringComparison.OrdinalIgnoreCase))
  668. {
  669. writer.WriteString("object.item.imageItem.photo");
  670. }
  671. else if (string.Equals(item.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase))
  672. {
  673. if (!_profile.RequiresPlainVideoItems && item is Movie)
  674. {
  675. writer.WriteString("object.item.videoItem.movie");
  676. }
  677. else if (!_profile.RequiresPlainVideoItems && item is MusicVideo)
  678. {
  679. writer.WriteString("object.item.videoItem.musicVideoClip");
  680. }
  681. else
  682. {
  683. writer.WriteString("object.item.videoItem");
  684. }
  685. }
  686. else if (item is MusicGenre)
  687. {
  688. writer.WriteString(_profile.RequiresPlainFolders ? "object.container.storageFolder" : "object.container.genre.musicGenre");
  689. }
  690. else if (item is Genre || item is GameGenre)
  691. {
  692. writer.WriteString(_profile.RequiresPlainFolders ? "object.container.storageFolder" : "object.container.genre");
  693. }
  694. else
  695. {
  696. writer.WriteString("object.item");
  697. }
  698. writer.WriteFullEndElement();
  699. }
  700. private void AddPeople(BaseItem item, XmlWriter writer)
  701. {
  702. var types = new[]
  703. {
  704. PersonType.Director,
  705. PersonType.Writer,
  706. PersonType.Producer,
  707. PersonType.Composer,
  708. "Creator"
  709. };
  710. var people = _libraryManager.GetPeople(item);
  711. var index = 0;
  712. // Seeing some LG models locking up due content with large lists of people
  713. // The actual issue might just be due to processing a more metadata than it can handle
  714. var limit = 6;
  715. foreach (var actor in people)
  716. {
  717. var type = types.FirstOrDefault(i => string.Equals(i, actor.Type, StringComparison.OrdinalIgnoreCase) || string.Equals(i, actor.Role, StringComparison.OrdinalIgnoreCase))
  718. ?? PersonType.Actor;
  719. AddValue(writer, "upnp", type.ToLower(), actor.Name, NS_UPNP);
  720. index++;
  721. if (index >= limit)
  722. {
  723. break;
  724. }
  725. }
  726. }
  727. private void AddGeneralProperties(BaseItem item, StubType? itemStubType, BaseItem context, XmlWriter writer, Filter filter)
  728. {
  729. AddCommonFields(item, itemStubType, context, writer, filter);
  730. var audio = item as Audio;
  731. if (audio != null)
  732. {
  733. foreach (var artist in audio.Artists)
  734. {
  735. AddValue(writer, "upnp", "artist", artist, NS_UPNP);
  736. }
  737. if (!string.IsNullOrEmpty(audio.Album))
  738. {
  739. AddValue(writer, "upnp", "album", audio.Album, NS_UPNP);
  740. }
  741. foreach (var artist in audio.AlbumArtists)
  742. {
  743. AddAlbumArtist(writer, artist);
  744. }
  745. }
  746. var album = item as MusicAlbum;
  747. if (album != null)
  748. {
  749. foreach (var artist in album.AlbumArtists)
  750. {
  751. AddAlbumArtist(writer, artist);
  752. AddValue(writer, "upnp", "artist", artist, NS_UPNP);
  753. }
  754. foreach (var artist in album.Artists)
  755. {
  756. AddValue(writer, "upnp", "artist", artist, NS_UPNP);
  757. }
  758. }
  759. var musicVideo = item as MusicVideo;
  760. if (musicVideo != null)
  761. {
  762. foreach (var artist in musicVideo.Artists)
  763. {
  764. AddValue(writer, "upnp", "artist", artist, NS_UPNP);
  765. AddAlbumArtist(writer, artist);
  766. }
  767. if (!string.IsNullOrEmpty(musicVideo.Album))
  768. {
  769. AddValue(writer, "upnp", "album", musicVideo.Album, NS_UPNP);
  770. }
  771. }
  772. if (item.IndexNumber.HasValue)
  773. {
  774. AddValue(writer, "upnp", "originalTrackNumber", item.IndexNumber.Value.ToString(_usCulture), NS_UPNP);
  775. if (item is Episode)
  776. {
  777. AddValue(writer, "upnp", "episodeNumber", item.IndexNumber.Value.ToString(_usCulture), NS_UPNP);
  778. }
  779. }
  780. }
  781. private void AddAlbumArtist(XmlWriter writer, string name)
  782. {
  783. try
  784. {
  785. writer.WriteStartElement("upnp", "artist", NS_UPNP);
  786. writer.WriteAttributeString("role", "AlbumArtist");
  787. writer.WriteString(name);
  788. writer.WriteFullEndElement();
  789. }
  790. catch (XmlException)
  791. {
  792. //_logger.Error("Error adding xml value: " + value);
  793. }
  794. }
  795. private void AddValue(XmlWriter writer, string prefix, string name, string value, string namespaceUri)
  796. {
  797. try
  798. {
  799. writer.WriteElementString(prefix, name, namespaceUri, value);
  800. }
  801. catch (XmlException)
  802. {
  803. //_logger.Error("Error adding xml value: " + value);
  804. }
  805. }
  806. private void AddCover(BaseItem item, BaseItem context, StubType? stubType, XmlWriter writer)
  807. {
  808. ImageDownloadInfo imageInfo = null;
  809. if (context is UserView)
  810. {
  811. var episode = item as Episode;
  812. if (episode != null)
  813. {
  814. var parent = episode.Series;
  815. if (parent != null)
  816. {
  817. imageInfo = GetImageInfo(parent);
  818. }
  819. }
  820. }
  821. // Finally, just use the image from the item
  822. if (imageInfo == null)
  823. {
  824. imageInfo = GetImageInfo(item);
  825. }
  826. if (imageInfo == null)
  827. {
  828. return;
  829. }
  830. var playbackPercentage = 0;
  831. var unplayedCount = 0;
  832. if (item is Video)
  833. {
  834. var userData = _userDataManager.GetUserDataDto(item, _user);
  835. playbackPercentage = Convert.ToInt32(userData.PlayedPercentage ?? 0);
  836. if (playbackPercentage >= 100 || userData.Played)
  837. {
  838. playbackPercentage = 100;
  839. }
  840. }
  841. else if (item is Series || item is Season || item is BoxSet)
  842. {
  843. var userData = _userDataManager.GetUserDataDto(item, _user);
  844. if (userData.Played)
  845. {
  846. playbackPercentage = 100;
  847. }
  848. else
  849. {
  850. unplayedCount = userData.UnplayedItemCount ?? 0;
  851. }
  852. }
  853. var albumartUrlInfo = GetImageUrl(imageInfo, _profile.MaxAlbumArtWidth, _profile.MaxAlbumArtHeight, playbackPercentage, unplayedCount, "jpg");
  854. writer.WriteStartElement("upnp", "albumArtURI", NS_UPNP);
  855. writer.WriteAttributeString("dlna", "profileID", NS_DLNA, _profile.AlbumArtPn);
  856. writer.WriteString(albumartUrlInfo.Url);
  857. writer.WriteFullEndElement();
  858. // TOOD: Remove these default values
  859. var iconUrlInfo = GetImageUrl(imageInfo, _profile.MaxIconWidth ?? 48, _profile.MaxIconHeight ?? 48, playbackPercentage, unplayedCount, "jpg");
  860. writer.WriteElementString("upnp", "icon", NS_UPNP, iconUrlInfo.Url);
  861. if (!_profile.EnableAlbumArtInDidl)
  862. {
  863. if (string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase)
  864. || string.Equals(item.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase))
  865. {
  866. if (!stubType.HasValue)
  867. {
  868. return;
  869. }
  870. }
  871. }
  872. AddImageResElement(item, writer, 160, 160, playbackPercentage, unplayedCount, "jpg", "JPEG_TN");
  873. if (!_profile.EnableSingleAlbumArtLimit)
  874. {
  875. AddImageResElement(item, writer, 4096, 4096, playbackPercentage, unplayedCount, "jpg", "JPEG_LRG");
  876. AddImageResElement(item, writer, 1024, 768, playbackPercentage, unplayedCount, "jpg", "JPEG_MED");
  877. AddImageResElement(item, writer, 640, 480, playbackPercentage, unplayedCount, "jpg", "JPEG_SM");
  878. AddImageResElement(item, writer, 4096, 4096, playbackPercentage, unplayedCount, "png", "PNG_LRG");
  879. AddImageResElement(item, writer, 160, 160, playbackPercentage, unplayedCount, "png", "PNG_TN");
  880. }
  881. }
  882. private void AddEmbeddedImageAsCover(string name, XmlWriter writer)
  883. {
  884. writer.WriteStartElement("upnp", "albumArtURI", NS_UPNP);
  885. writer.WriteAttributeString("dlna", "profileID", NS_DLNA, _profile.AlbumArtPn);
  886. writer.WriteString(_serverAddress + "/Dlna/icons/people480.jpg");
  887. writer.WriteFullEndElement();
  888. writer.WriteElementString("upnp", "icon", NS_UPNP, _serverAddress + "/Dlna/icons/people48.jpg");
  889. }
  890. private void AddImageResElement(BaseItem item,
  891. XmlWriter writer,
  892. int maxWidth,
  893. int maxHeight,
  894. int playbackPercentage,
  895. int unplayedCount,
  896. string format,
  897. string org_Pn)
  898. {
  899. var imageInfo = GetImageInfo(item);
  900. if (imageInfo == null)
  901. {
  902. return;
  903. }
  904. var albumartUrlInfo = GetImageUrl(imageInfo, maxWidth, maxHeight, playbackPercentage, unplayedCount, format);
  905. writer.WriteStartElement(string.Empty, "res", NS_DIDL);
  906. // Images must have a reported size or many clients (Bubble upnp), will only use the first thumbnail
  907. // rather than using a larger one when available
  908. var width = albumartUrlInfo.Width ?? maxWidth;
  909. var height = albumartUrlInfo.Height ?? maxHeight;
  910. var contentFeatures = new ContentFeatureBuilder(_profile)
  911. .BuildImageHeader(format, width, height, imageInfo.IsDirectStream, org_Pn);
  912. writer.WriteAttributeString("protocolInfo", String.Format(
  913. "http-get:*:{0}:{1}",
  914. GetMimeType("file." + format),
  915. contentFeatures
  916. ));
  917. writer.WriteAttributeString("resolution", string.Format("{0}x{1}", width, height));
  918. writer.WriteString(albumartUrlInfo.Url);
  919. writer.WriteFullEndElement();
  920. }
  921. private ImageDownloadInfo GetImageInfo(BaseItem item)
  922. {
  923. if (item.HasImage(ImageType.Primary))
  924. {
  925. return GetImageInfo(item, ImageType.Primary);
  926. }
  927. if (item.HasImage(ImageType.Thumb))
  928. {
  929. return GetImageInfo(item, ImageType.Thumb);
  930. }
  931. if (item.HasImage(ImageType.Backdrop))
  932. {
  933. if (item is Channel)
  934. {
  935. return GetImageInfo(item, ImageType.Backdrop);
  936. }
  937. }
  938. item = item.GetParents().FirstOrDefault(i => i.HasImage(ImageType.Primary));
  939. if (item != null)
  940. {
  941. if (item.HasImage(ImageType.Primary))
  942. {
  943. return GetImageInfo(item, ImageType.Primary);
  944. }
  945. }
  946. return null;
  947. }
  948. private ImageDownloadInfo GetImageInfo(BaseItem item, ImageType type)
  949. {
  950. var imageInfo = item.GetImageInfo(type, 0);
  951. string tag = null;
  952. try
  953. {
  954. tag = _imageProcessor.GetImageCacheTag(item, type);
  955. }
  956. catch
  957. {
  958. }
  959. int? width = null;
  960. int? height = null;
  961. //try
  962. //{
  963. // var size = _imageProcessor.GetImageSize(imageInfo);
  964. // width = Convert.ToInt32(size.Width);
  965. // height = Convert.ToInt32(size.Height);
  966. //}
  967. //catch
  968. //{
  969. //}
  970. var inputFormat = (Path.GetExtension(imageInfo.Path) ?? string.Empty)
  971. .TrimStart('.')
  972. .Replace("jpeg", "jpg", StringComparison.OrdinalIgnoreCase);
  973. return new ImageDownloadInfo
  974. {
  975. ItemId = item.Id.ToString("N"),
  976. Type = type,
  977. ImageTag = tag,
  978. Width = width,
  979. Height = height,
  980. Format = inputFormat,
  981. ItemImageInfo = imageInfo
  982. };
  983. }
  984. class ImageDownloadInfo
  985. {
  986. internal string ItemId;
  987. internal string ImageTag;
  988. internal ImageType Type;
  989. internal int? Width;
  990. internal int? Height;
  991. internal bool IsDirectStream;
  992. internal string Format;
  993. internal ItemImageInfo ItemImageInfo;
  994. }
  995. class ImageUrlInfo
  996. {
  997. internal string Url;
  998. internal int? Width;
  999. internal int? Height;
  1000. }
  1001. public static string GetClientId(BaseItem item, StubType? stubType)
  1002. {
  1003. return GetClientId(item.Id, stubType);
  1004. }
  1005. public static string GetClientId(Guid idValue, StubType? stubType)
  1006. {
  1007. var id = idValue.ToString("N");
  1008. if (stubType.HasValue)
  1009. {
  1010. id = stubType.Value.ToString().ToLower() + "_" + id;
  1011. }
  1012. return id;
  1013. }
  1014. public static string GetClientId(IHasMediaSources item)
  1015. {
  1016. var id = item.Id.ToString("N");
  1017. return id;
  1018. }
  1019. private ImageUrlInfo GetImageUrl(ImageDownloadInfo info, int maxWidth, int maxHeight, int playbackPercentage, int unplayedCount, string format)
  1020. {
  1021. var url = string.Format("{0}/Items/{1}/Images/{2}/0/{3}/{4}/{5}/{6}/{7}/{8}",
  1022. _serverAddress,
  1023. info.ItemId,
  1024. info.Type,
  1025. info.ImageTag,
  1026. format,
  1027. maxWidth.ToString(CultureInfo.InvariantCulture),
  1028. maxHeight.ToString(CultureInfo.InvariantCulture),
  1029. playbackPercentage.ToString(CultureInfo.InvariantCulture),
  1030. unplayedCount.ToString(CultureInfo.InvariantCulture)
  1031. );
  1032. var width = info.Width;
  1033. var height = info.Height;
  1034. info.IsDirectStream = false;
  1035. if (width.HasValue && height.HasValue)
  1036. {
  1037. var newSize = DrawingUtils.Resize(new ImageSize
  1038. {
  1039. Height = height.Value,
  1040. Width = width.Value
  1041. }, null, null, maxWidth, maxHeight);
  1042. width = Convert.ToInt32(newSize.Width);
  1043. height = Convert.ToInt32(newSize.Height);
  1044. var normalizedFormat = format
  1045. .Replace("jpeg", "jpg", StringComparison.OrdinalIgnoreCase);
  1046. if (string.Equals(info.Format, normalizedFormat, StringComparison.OrdinalIgnoreCase))
  1047. {
  1048. info.IsDirectStream = maxWidth >= width.Value && maxHeight >= height.Value;
  1049. }
  1050. }
  1051. return new ImageUrlInfo
  1052. {
  1053. Url = url,
  1054. Width = width,
  1055. Height = height
  1056. };
  1057. }
  1058. }
  1059. }