Video.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. using MediaBrowser.Controller.Library;
  2. using MediaBrowser.Controller.Persistence;
  3. using MediaBrowser.Controller.Providers;
  4. using MediaBrowser.Model.Dto;
  5. using MediaBrowser.Model.Entities;
  6. using MediaBrowser.Model.MediaInfo;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Runtime.Serialization;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. namespace MediaBrowser.Controller.Entities
  15. {
  16. /// <summary>
  17. /// Class Video
  18. /// </summary>
  19. public class Video : BaseItem,
  20. IHasAspectRatio,
  21. IHasTags,
  22. ISupportsPlaceHolders,
  23. IHasMediaSources,
  24. IHasShortOverview,
  25. IHasPreferredMetadataLanguage,
  26. IThemeMedia
  27. {
  28. public Guid? PrimaryVersionId { get; set; }
  29. public List<string> AdditionalParts { get; set; }
  30. public List<string> LocalAlternateVersions { get; set; }
  31. public List<LinkedChild> LinkedAlternateVersions { get; set; }
  32. public bool IsThemeMedia { get; set; }
  33. public string FormatName { get; set; }
  34. public long? Size { get; set; }
  35. public string Container { get; set; }
  36. public int? TotalBitrate { get; set; }
  37. public string ShortOverview { get; set; }
  38. public ExtraType ExtraType { get; set; }
  39. /// <summary>
  40. /// Gets or sets the preferred metadata country code.
  41. /// </summary>
  42. /// <value>The preferred metadata country code.</value>
  43. public string PreferredMetadataCountryCode { get; set; }
  44. public string PreferredMetadataLanguage { get; set; }
  45. /// <summary>
  46. /// Gets or sets the timestamp.
  47. /// </summary>
  48. /// <value>The timestamp.</value>
  49. public TransportStreamTimestamp? Timestamp { get; set; }
  50. public Video()
  51. {
  52. PlayableStreamFileNames = new List<string>();
  53. AdditionalParts = new List<string>();
  54. LocalAlternateVersions = new List<string>();
  55. Tags = new List<string>();
  56. SubtitleFiles = new List<string>();
  57. LinkedAlternateVersions = new List<LinkedChild>();
  58. }
  59. [IgnoreDataMember]
  60. public override bool SupportsAddingToPlaylist
  61. {
  62. get { return LocationType == LocationType.FileSystem && RunTimeTicks.HasValue; }
  63. }
  64. [IgnoreDataMember]
  65. public int MediaSourceCount
  66. {
  67. get
  68. {
  69. return LinkedAlternateVersions.Count + LocalAlternateVersions.Count + 1;
  70. }
  71. }
  72. [IgnoreDataMember]
  73. public bool IsStacked
  74. {
  75. get { return AdditionalParts.Count > 0; }
  76. }
  77. [IgnoreDataMember]
  78. public bool HasLocalAlternateVersions
  79. {
  80. get { return LocalAlternateVersions.Count > 0; }
  81. }
  82. [IgnoreDataMember]
  83. public bool IsArchive
  84. {
  85. get
  86. {
  87. if (string.IsNullOrWhiteSpace(Path))
  88. {
  89. return false;
  90. }
  91. var ext = System.IO.Path.GetExtension(Path) ?? string.Empty;
  92. return new[] { ".zip", ".rar", ".7z" }.Contains(ext, StringComparer.OrdinalIgnoreCase);
  93. }
  94. }
  95. public IEnumerable<Guid> GetAdditionalPartIds()
  96. {
  97. return AdditionalParts.Select(i => LibraryManager.GetNewItemId(i, typeof(Video)));
  98. }
  99. public IEnumerable<Guid> GetLocalAlternateVersionIds()
  100. {
  101. return LocalAlternateVersions.Select(i => LibraryManager.GetNewItemId(i, typeof(Video)));
  102. }
  103. /// <summary>
  104. /// Gets the linked children.
  105. /// </summary>
  106. /// <returns>IEnumerable{BaseItem}.</returns>
  107. public IEnumerable<Video> GetAlternateVersions()
  108. {
  109. var filesWithinSameDirectory = GetLocalAlternateVersionIds()
  110. .Select(i => LibraryManager.GetItemById(i))
  111. .Where(i => i != null)
  112. .OfType<Video>();
  113. return filesWithinSameDirectory.Concat(GetLinkedAlternateVersions())
  114. .OrderBy(i => i.SortName);
  115. }
  116. public IEnumerable<Video> GetLinkedAlternateVersions()
  117. {
  118. var linkedVersions = LinkedAlternateVersions
  119. .Select(GetLinkedChild)
  120. .Where(i => i != null)
  121. .OfType<Video>();
  122. return linkedVersions
  123. .OrderBy(i => i.SortName);
  124. }
  125. /// <summary>
  126. /// Gets the additional parts.
  127. /// </summary>
  128. /// <returns>IEnumerable{Video}.</returns>
  129. public IEnumerable<Video> GetAdditionalParts()
  130. {
  131. return GetAdditionalPartIds()
  132. .Select(i => LibraryManager.GetItemById(i))
  133. .Where(i => i != null)
  134. .OfType<Video>()
  135. .OrderBy(i => i.SortName);
  136. }
  137. /// <summary>
  138. /// Gets or sets the subtitle paths.
  139. /// </summary>
  140. /// <value>The subtitle paths.</value>
  141. public List<string> SubtitleFiles { get; set; }
  142. /// <summary>
  143. /// Gets or sets a value indicating whether this instance has subtitles.
  144. /// </summary>
  145. /// <value><c>true</c> if this instance has subtitles; otherwise, <c>false</c>.</value>
  146. public bool HasSubtitles { get; set; }
  147. public bool IsPlaceHolder { get; set; }
  148. public bool IsShortcut { get; set; }
  149. public string ShortcutPath { get; set; }
  150. /// <summary>
  151. /// Gets or sets the tags.
  152. /// </summary>
  153. /// <value>The tags.</value>
  154. public List<string> Tags { get; set; }
  155. /// <summary>
  156. /// Gets or sets the video bit rate.
  157. /// </summary>
  158. /// <value>The video bit rate.</value>
  159. public int? VideoBitRate { get; set; }
  160. /// <summary>
  161. /// Gets or sets the default index of the video stream.
  162. /// </summary>
  163. /// <value>The default index of the video stream.</value>
  164. public int? DefaultVideoStreamIndex { get; set; }
  165. /// <summary>
  166. /// Gets or sets the type of the video.
  167. /// </summary>
  168. /// <value>The type of the video.</value>
  169. public VideoType VideoType { get; set; }
  170. /// <summary>
  171. /// Gets or sets the type of the iso.
  172. /// </summary>
  173. /// <value>The type of the iso.</value>
  174. public IsoType? IsoType { get; set; }
  175. /// <summary>
  176. /// Gets or sets the video3 D format.
  177. /// </summary>
  178. /// <value>The video3 D format.</value>
  179. public Video3DFormat? Video3DFormat { get; set; }
  180. /// <summary>
  181. /// If the video is a folder-rip, this will hold the file list for the largest playlist
  182. /// </summary>
  183. public List<string> PlayableStreamFileNames { get; set; }
  184. /// <summary>
  185. /// Gets the playable stream files.
  186. /// </summary>
  187. /// <returns>List{System.String}.</returns>
  188. public List<string> GetPlayableStreamFiles()
  189. {
  190. return GetPlayableStreamFiles(Path);
  191. }
  192. /// <summary>
  193. /// Gets or sets the aspect ratio.
  194. /// </summary>
  195. /// <value>The aspect ratio.</value>
  196. public string AspectRatio { get; set; }
  197. [IgnoreDataMember]
  198. public override string ContainingFolderPath
  199. {
  200. get
  201. {
  202. if (IsStacked)
  203. {
  204. return System.IO.Path.GetDirectoryName(Path);
  205. }
  206. if (!IsPlaceHolder)
  207. {
  208. if (VideoType == VideoType.BluRay || VideoType == VideoType.Dvd ||
  209. VideoType == VideoType.HdDvd)
  210. {
  211. return Path;
  212. }
  213. }
  214. return base.ContainingFolderPath;
  215. }
  216. }
  217. [IgnoreDataMember]
  218. public override string FileNameWithoutExtension
  219. {
  220. get
  221. {
  222. if (LocationType == LocationType.FileSystem)
  223. {
  224. if (VideoType == VideoType.BluRay || VideoType == VideoType.Dvd || VideoType == VideoType.HdDvd)
  225. {
  226. return System.IO.Path.GetFileName(Path);
  227. }
  228. return System.IO.Path.GetFileNameWithoutExtension(Path);
  229. }
  230. return null;
  231. }
  232. }
  233. internal override bool IsValidFromResolver(BaseItem newItem)
  234. {
  235. var current = this;
  236. var newAsVideo = newItem as Video;
  237. if (newAsVideo != null)
  238. {
  239. if (!current.AdditionalParts.SequenceEqual(newAsVideo.AdditionalParts, StringComparer.OrdinalIgnoreCase))
  240. {
  241. return false;
  242. }
  243. if (!current.LocalAlternateVersions.SequenceEqual(newAsVideo.LocalAlternateVersions, StringComparer.OrdinalIgnoreCase))
  244. {
  245. return false;
  246. }
  247. }
  248. return base.IsValidFromResolver(newItem);
  249. }
  250. public string MainFeaturePlaylistName { get; set; }
  251. /// <summary>
  252. /// Gets the playable stream files.
  253. /// </summary>
  254. /// <param name="rootPath">The root path.</param>
  255. /// <returns>List{System.String}.</returns>
  256. public List<string> GetPlayableStreamFiles(string rootPath)
  257. {
  258. var allFiles = Directory.EnumerateFiles(rootPath, "*", SearchOption.AllDirectories).ToList();
  259. return PlayableStreamFileNames.Select(name => allFiles.FirstOrDefault(f => string.Equals(System.IO.Path.GetFileName(f), name, StringComparison.OrdinalIgnoreCase)))
  260. .Where(f => !string.IsNullOrEmpty(f))
  261. .ToList();
  262. }
  263. /// <summary>
  264. /// Gets a value indicating whether [is3 D].
  265. /// </summary>
  266. /// <value><c>true</c> if [is3 D]; otherwise, <c>false</c>.</value>
  267. [IgnoreDataMember]
  268. public bool Is3D
  269. {
  270. get { return Video3DFormat.HasValue; }
  271. }
  272. public bool IsHD { get; set; }
  273. /// <summary>
  274. /// Gets the type of the media.
  275. /// </summary>
  276. /// <value>The type of the media.</value>
  277. [IgnoreDataMember]
  278. public override string MediaType
  279. {
  280. get
  281. {
  282. return Model.Entities.MediaType.Video;
  283. }
  284. }
  285. protected override async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemInfo> fileSystemChildren, CancellationToken cancellationToken)
  286. {
  287. var hasChanges = await base.RefreshedOwnedItems(options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  288. if (IsStacked)
  289. {
  290. var tasks = AdditionalParts
  291. .Select(i => RefreshMetadataForOwnedVideo(options, i, cancellationToken));
  292. await Task.WhenAll(tasks).ConfigureAwait(false);
  293. }
  294. // Must have a parent to have additional parts or alternate versions
  295. // In other words, it must be part of the Parent/Child tree
  296. // The additional parts won't have additional parts themselves
  297. if (LocationType == LocationType.FileSystem && Parent != null)
  298. {
  299. if (!IsStacked)
  300. {
  301. RefreshLinkedAlternateVersions();
  302. var tasks = LocalAlternateVersions
  303. .Select(i => RefreshMetadataForOwnedVideo(options, i, cancellationToken));
  304. await Task.WhenAll(tasks).ConfigureAwait(false);
  305. }
  306. }
  307. return hasChanges;
  308. }
  309. private void RefreshLinkedAlternateVersions()
  310. {
  311. foreach (var child in LinkedAlternateVersions)
  312. {
  313. // Reset the cached value
  314. if (child.ItemId.HasValue && child.ItemId.Value == Guid.Empty)
  315. {
  316. child.ItemId = null;
  317. }
  318. }
  319. }
  320. public override async Task UpdateToRepository(ItemUpdateType updateReason, CancellationToken cancellationToken)
  321. {
  322. await base.UpdateToRepository(updateReason, cancellationToken).ConfigureAwait(false);
  323. var localAlternates = GetLocalAlternateVersionIds()
  324. .Select(i => LibraryManager.GetItemById(i))
  325. .Where(i => i != null);
  326. foreach (var item in localAlternates)
  327. {
  328. item.ImageInfos = ImageInfos;
  329. item.Overview = Overview;
  330. item.ProductionYear = ProductionYear;
  331. item.PremiereDate = PremiereDate;
  332. item.CommunityRating = CommunityRating;
  333. item.OfficialRating = OfficialRating;
  334. item.Genres = Genres;
  335. item.ProviderIds = ProviderIds;
  336. await item.UpdateToRepository(ItemUpdateType.MetadataDownload, cancellationToken).ConfigureAwait(false);
  337. }
  338. }
  339. public override IEnumerable<string> GetDeletePaths()
  340. {
  341. if (!IsInMixedFolder)
  342. {
  343. return new[] { ContainingFolderPath };
  344. }
  345. return base.GetDeletePaths();
  346. }
  347. public virtual IEnumerable<MediaStream> GetMediaStreams()
  348. {
  349. return ItemRepository.GetMediaStreams(new MediaStreamQuery
  350. {
  351. ItemId = Id
  352. });
  353. }
  354. public virtual MediaStream GetDefaultVideoStream()
  355. {
  356. if (!DefaultVideoStreamIndex.HasValue)
  357. {
  358. return null;
  359. }
  360. return ItemRepository.GetMediaStreams(new MediaStreamQuery
  361. {
  362. ItemId = Id,
  363. Index = DefaultVideoStreamIndex.Value
  364. }).FirstOrDefault();
  365. }
  366. public virtual IEnumerable<MediaSourceInfo> GetMediaSources(bool enablePathSubstitution)
  367. {
  368. var item = this;
  369. var result = item.GetAlternateVersions()
  370. .Select(i => GetVersionInfo(enablePathSubstitution, i, MediaSourceType.Grouping))
  371. .ToList();
  372. result.Add(GetVersionInfo(enablePathSubstitution, item, MediaSourceType.Default));
  373. return result.OrderBy(i =>
  374. {
  375. if (item.VideoType == VideoType.VideoFile)
  376. {
  377. return 0;
  378. }
  379. return 1;
  380. }).ThenBy(i => i.Video3DFormat.HasValue ? 1 : 0)
  381. .ThenByDescending(i =>
  382. {
  383. var stream = i.VideoStream;
  384. return stream == null || stream.Width == null ? 0 : stream.Width.Value;
  385. })
  386. .ToList();
  387. }
  388. private static MediaSourceInfo GetVersionInfo(bool enablePathSubstitution, Video i, MediaSourceType type)
  389. {
  390. var mediaStreams = ItemRepository.GetMediaStreams(new MediaStreamQuery { ItemId = i.Id }).ToList();
  391. var locationType = i.LocationType;
  392. var info = new MediaSourceInfo
  393. {
  394. Id = i.Id.ToString("N"),
  395. IsoType = i.IsoType,
  396. Protocol = locationType == LocationType.Remote ? MediaProtocol.Http : MediaProtocol.File,
  397. MediaStreams = mediaStreams,
  398. Name = GetMediaSourceName(i, mediaStreams),
  399. Path = enablePathSubstitution ? GetMappedPath(i.Path, locationType) : i.Path,
  400. RunTimeTicks = i.RunTimeTicks,
  401. Video3DFormat = i.Video3DFormat,
  402. VideoType = i.VideoType,
  403. Container = i.Container,
  404. Size = i.Size,
  405. Formats = (i.FormatName ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(),
  406. Timestamp = i.Timestamp,
  407. Type = type,
  408. PlayableStreamFileNames = i.PlayableStreamFileNames.ToList()
  409. };
  410. if (i.IsShortcut)
  411. {
  412. info.Path = i.ShortcutPath;
  413. if (info.Path.StartsWith("Http", StringComparison.OrdinalIgnoreCase))
  414. {
  415. info.Protocol = MediaProtocol.Http;
  416. }
  417. else if (info.Path.StartsWith("Rtmp", StringComparison.OrdinalIgnoreCase))
  418. {
  419. info.Protocol = MediaProtocol.Rtmp;
  420. }
  421. else if (info.Path.StartsWith("Rtsp", StringComparison.OrdinalIgnoreCase))
  422. {
  423. info.Protocol = MediaProtocol.Rtsp;
  424. }
  425. else
  426. {
  427. info.Protocol = MediaProtocol.File;
  428. }
  429. }
  430. if (string.IsNullOrEmpty(info.Container))
  431. {
  432. if (i.VideoType == VideoType.VideoFile || i.VideoType == VideoType.Iso)
  433. {
  434. if (!string.IsNullOrWhiteSpace(i.Path) && locationType != LocationType.Remote && locationType != LocationType.Virtual)
  435. {
  436. info.Container = System.IO.Path.GetExtension(i.Path).TrimStart('.');
  437. }
  438. }
  439. }
  440. try
  441. {
  442. var bitrate = i.TotalBitrate ??
  443. info.MediaStreams.Where(m => m.Type != MediaStreamType.Subtitle && !string.Equals(m.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase))
  444. .Select(m => m.BitRate ?? 0)
  445. .Sum();
  446. if (bitrate > 0)
  447. {
  448. info.Bitrate = bitrate;
  449. }
  450. }
  451. catch (OverflowException ex)
  452. {
  453. Logger.ErrorException("Error calculating total bitrate", ex);
  454. }
  455. return info;
  456. }
  457. private static string GetMediaSourceName(Video video, List<MediaStream> mediaStreams)
  458. {
  459. var terms = new List<string>();
  460. var videoStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video);
  461. var audioStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);
  462. if (video.Video3DFormat.HasValue)
  463. {
  464. terms.Add("3D");
  465. }
  466. if (video.VideoType == VideoType.BluRay)
  467. {
  468. terms.Add("Bluray");
  469. }
  470. else if (video.VideoType == VideoType.Dvd)
  471. {
  472. terms.Add("DVD");
  473. }
  474. else if (video.VideoType == VideoType.HdDvd)
  475. {
  476. terms.Add("HD-DVD");
  477. }
  478. else if (video.VideoType == VideoType.Iso)
  479. {
  480. if (video.IsoType.HasValue)
  481. {
  482. if (video.IsoType.Value == Model.Entities.IsoType.BluRay)
  483. {
  484. terms.Add("Bluray");
  485. }
  486. else if (video.IsoType.Value == Model.Entities.IsoType.Dvd)
  487. {
  488. terms.Add("DVD");
  489. }
  490. }
  491. else
  492. {
  493. terms.Add("ISO");
  494. }
  495. }
  496. if (videoStream != null)
  497. {
  498. if (videoStream.Width.HasValue)
  499. {
  500. if (videoStream.Width.Value >= 3800)
  501. {
  502. terms.Add("4K");
  503. }
  504. else if (videoStream.Width.Value >= 1900)
  505. {
  506. terms.Add("1080P");
  507. }
  508. else if (videoStream.Width.Value >= 1270)
  509. {
  510. terms.Add("720P");
  511. }
  512. else if (videoStream.Width.Value >= 700)
  513. {
  514. terms.Add("480P");
  515. }
  516. else
  517. {
  518. terms.Add("SD");
  519. }
  520. }
  521. }
  522. if (videoStream != null && !string.IsNullOrWhiteSpace(videoStream.Codec))
  523. {
  524. terms.Add(videoStream.Codec.ToUpper());
  525. }
  526. if (audioStream != null)
  527. {
  528. var audioCodec = string.Equals(audioStream.Codec, "dca", StringComparison.OrdinalIgnoreCase)
  529. ? audioStream.Profile
  530. : audioStream.Codec;
  531. if (!string.IsNullOrEmpty(audioCodec))
  532. {
  533. terms.Add(audioCodec.ToUpper());
  534. }
  535. }
  536. return string.Join("/", terms.ToArray());
  537. }
  538. }
  539. }