Video.cs 21 KB

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