Video.cs 21 KB

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