Video.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  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. using CommonIO;
  15. using MediaBrowser.Common.IO;
  16. namespace MediaBrowser.Controller.Entities
  17. {
  18. /// <summary>
  19. /// Class Video
  20. /// </summary>
  21. public class Video : BaseItem,
  22. IHasAspectRatio,
  23. IHasTags,
  24. ISupportsPlaceHolders,
  25. IHasMediaSources,
  26. IHasShortOverview,
  27. IThemeMedia,
  28. IArchivable
  29. {
  30. public Guid? PrimaryVersionId { get; set; }
  31. public List<string> AdditionalParts { get; set; }
  32. public List<string> LocalAlternateVersions { get; set; }
  33. public List<LinkedChild> LinkedAlternateVersions { get; set; }
  34. [IgnoreDataMember]
  35. public bool IsThemeMedia
  36. {
  37. get
  38. {
  39. return ExtraType.HasValue && ExtraType.Value == Model.Entities.ExtraType.ThemeVideo;
  40. }
  41. }
  42. public long? Size { get; set; }
  43. public string Container { get; set; }
  44. public int? TotalBitrate { get; set; }
  45. public string ShortOverview { get; set; }
  46. public ExtraType? ExtraType { get; set; }
  47. /// <summary>
  48. /// Gets or sets the timestamp.
  49. /// </summary>
  50. /// <value>The timestamp.</value>
  51. public TransportStreamTimestamp? Timestamp { get; set; }
  52. public Video()
  53. {
  54. PlayableStreamFileNames = new List<string>();
  55. AdditionalParts = new List<string>();
  56. LocalAlternateVersions = new List<string>();
  57. Tags = new List<string>();
  58. SubtitleFiles = new List<string>();
  59. LinkedAlternateVersions = new List<LinkedChild>();
  60. }
  61. public override bool CanDownload()
  62. {
  63. if (VideoType == VideoType.HdDvd || VideoType == VideoType.Dvd ||
  64. VideoType == VideoType.BluRay)
  65. {
  66. return false;
  67. }
  68. var locationType = LocationType;
  69. return locationType != LocationType.Remote &&
  70. locationType != LocationType.Virtual;
  71. }
  72. [IgnoreDataMember]
  73. public override bool SupportsAddingToPlaylist
  74. {
  75. get { return LocationType == LocationType.FileSystem && RunTimeTicks.HasValue; }
  76. }
  77. [IgnoreDataMember]
  78. public int MediaSourceCount
  79. {
  80. get
  81. {
  82. return LinkedAlternateVersions.Count + LocalAlternateVersions.Count + 1;
  83. }
  84. }
  85. [IgnoreDataMember]
  86. public bool IsStacked
  87. {
  88. get { return AdditionalParts.Count > 0; }
  89. }
  90. [IgnoreDataMember]
  91. public bool HasLocalAlternateVersions
  92. {
  93. get { return LocalAlternateVersions.Count > 0; }
  94. }
  95. [IgnoreDataMember]
  96. public bool IsArchive
  97. {
  98. get
  99. {
  100. if (string.IsNullOrWhiteSpace(Path))
  101. {
  102. return false;
  103. }
  104. var ext = System.IO.Path.GetExtension(Path) ?? string.Empty;
  105. return new[] { ".zip", ".rar", ".7z" }.Contains(ext, StringComparer.OrdinalIgnoreCase);
  106. }
  107. }
  108. public IEnumerable<Guid> GetAdditionalPartIds()
  109. {
  110. return AdditionalParts.Select(i => LibraryManager.GetNewItemId(i, typeof(Video)));
  111. }
  112. public IEnumerable<Guid> GetLocalAlternateVersionIds()
  113. {
  114. return LocalAlternateVersions.Select(i => LibraryManager.GetNewItemId(i, typeof(Video)));
  115. }
  116. /// <summary>
  117. /// Gets the linked children.
  118. /// </summary>
  119. /// <returns>IEnumerable{BaseItem}.</returns>
  120. public IEnumerable<Video> GetAlternateVersions()
  121. {
  122. var filesWithinSameDirectory = GetLocalAlternateVersionIds()
  123. .Select(i => LibraryManager.GetItemById(i))
  124. .Where(i => i != null)
  125. .OfType<Video>();
  126. return filesWithinSameDirectory.Concat(GetLinkedAlternateVersions())
  127. .OrderBy(i => i.SortName);
  128. }
  129. public IEnumerable<Video> GetLinkedAlternateVersions()
  130. {
  131. var linkedVersions = LinkedAlternateVersions
  132. .Select(GetLinkedChild)
  133. .Where(i => i != null)
  134. .OfType<Video>();
  135. return linkedVersions
  136. .OrderBy(i => i.SortName);
  137. }
  138. /// <summary>
  139. /// Gets the additional parts.
  140. /// </summary>
  141. /// <returns>IEnumerable{Video}.</returns>
  142. public IEnumerable<Video> GetAdditionalParts()
  143. {
  144. return GetAdditionalPartIds()
  145. .Select(i => LibraryManager.GetItemById(i))
  146. .Where(i => i != null)
  147. .OfType<Video>()
  148. .OrderBy(i => i.SortName);
  149. }
  150. /// <summary>
  151. /// Gets or sets the subtitle paths.
  152. /// </summary>
  153. /// <value>The subtitle paths.</value>
  154. public List<string> SubtitleFiles { get; set; }
  155. /// <summary>
  156. /// Gets or sets a value indicating whether this instance has subtitles.
  157. /// </summary>
  158. /// <value><c>true</c> if this instance has subtitles; otherwise, <c>false</c>.</value>
  159. public bool HasSubtitles { get; set; }
  160. public bool IsPlaceHolder { get; set; }
  161. public bool IsShortcut { get; set; }
  162. public string ShortcutPath { get; set; }
  163. /// <summary>
  164. /// Gets or sets the tags.
  165. /// </summary>
  166. /// <value>The tags.</value>
  167. public List<string> Tags { get; set; }
  168. /// <summary>
  169. /// Gets or sets the video bit rate.
  170. /// </summary>
  171. /// <value>The video bit rate.</value>
  172. public int? VideoBitRate { get; set; }
  173. /// <summary>
  174. /// Gets or sets the default index of the video stream.
  175. /// </summary>
  176. /// <value>The default index of the video stream.</value>
  177. public int? DefaultVideoStreamIndex { get; set; }
  178. /// <summary>
  179. /// Gets or sets the type of the video.
  180. /// </summary>
  181. /// <value>The type of the video.</value>
  182. public VideoType VideoType { get; set; }
  183. /// <summary>
  184. /// Gets or sets the type of the iso.
  185. /// </summary>
  186. /// <value>The type of the iso.</value>
  187. public IsoType? IsoType { get; set; }
  188. /// <summary>
  189. /// Gets or sets the video3 D format.
  190. /// </summary>
  191. /// <value>The video3 D format.</value>
  192. public Video3DFormat? Video3DFormat { get; set; }
  193. /// <summary>
  194. /// If the video is a folder-rip, this will hold the file list for the largest playlist
  195. /// </summary>
  196. public List<string> PlayableStreamFileNames { get; set; }
  197. /// <summary>
  198. /// Gets the playable stream files.
  199. /// </summary>
  200. /// <returns>List{System.String}.</returns>
  201. public List<string> GetPlayableStreamFiles()
  202. {
  203. return GetPlayableStreamFiles(Path);
  204. }
  205. /// <summary>
  206. /// Gets or sets the aspect ratio.
  207. /// </summary>
  208. /// <value>The aspect ratio.</value>
  209. public string AspectRatio { get; set; }
  210. [IgnoreDataMember]
  211. public override string ContainingFolderPath
  212. {
  213. get
  214. {
  215. if (IsStacked)
  216. {
  217. return System.IO.Path.GetDirectoryName(Path);
  218. }
  219. if (!IsPlaceHolder)
  220. {
  221. if (VideoType == VideoType.BluRay || VideoType == VideoType.Dvd ||
  222. VideoType == VideoType.HdDvd)
  223. {
  224. return Path;
  225. }
  226. }
  227. return base.ContainingFolderPath;
  228. }
  229. }
  230. [IgnoreDataMember]
  231. public override string FileNameWithoutExtension
  232. {
  233. get
  234. {
  235. if (LocationType == LocationType.FileSystem)
  236. {
  237. if (VideoType == VideoType.BluRay || VideoType == VideoType.Dvd || VideoType == VideoType.HdDvd)
  238. {
  239. return System.IO.Path.GetFileName(Path);
  240. }
  241. return System.IO.Path.GetFileNameWithoutExtension(Path);
  242. }
  243. return null;
  244. }
  245. }
  246. internal override bool IsValidFromResolver(BaseItem newItem)
  247. {
  248. var current = this;
  249. var newAsVideo = newItem as Video;
  250. if (newAsVideo != null)
  251. {
  252. if (!current.AdditionalParts.SequenceEqual(newAsVideo.AdditionalParts, StringComparer.OrdinalIgnoreCase))
  253. {
  254. return false;
  255. }
  256. if (!current.LocalAlternateVersions.SequenceEqual(newAsVideo.LocalAlternateVersions, StringComparer.OrdinalIgnoreCase))
  257. {
  258. return false;
  259. }
  260. }
  261. return base.IsValidFromResolver(newItem);
  262. }
  263. public string MainFeaturePlaylistName { get; set; }
  264. /// <summary>
  265. /// Gets the playable stream files.
  266. /// </summary>
  267. /// <param name="rootPath">The root path.</param>
  268. /// <returns>List{System.String}.</returns>
  269. public List<string> GetPlayableStreamFiles(string rootPath)
  270. {
  271. var allFiles = FileSystem.GetFilePaths(rootPath, true).ToList();
  272. return PlayableStreamFileNames.Select(name => allFiles.FirstOrDefault(f => string.Equals(System.IO.Path.GetFileName(f), name, StringComparison.OrdinalIgnoreCase)))
  273. .Where(f => !string.IsNullOrEmpty(f))
  274. .ToList();
  275. }
  276. /// <summary>
  277. /// Gets a value indicating whether [is3 D].
  278. /// </summary>
  279. /// <value><c>true</c> if [is3 D]; otherwise, <c>false</c>.</value>
  280. [IgnoreDataMember]
  281. public bool Is3D
  282. {
  283. get { return Video3DFormat.HasValue; }
  284. }
  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<FileSystemMetadata> 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. Timestamp = i.Timestamp,
  422. Type = type,
  423. PlayableStreamFileNames = i.PlayableStreamFileNames.ToList(),
  424. SupportsDirectStream = i.VideoType == VideoType.VideoFile
  425. };
  426. if (i.IsShortcut)
  427. {
  428. info.Path = i.ShortcutPath;
  429. if (info.Path.StartsWith("Http", StringComparison.OrdinalIgnoreCase))
  430. {
  431. info.Protocol = MediaProtocol.Http;
  432. }
  433. else if (info.Path.StartsWith("Rtmp", StringComparison.OrdinalIgnoreCase))
  434. {
  435. info.Protocol = MediaProtocol.Rtmp;
  436. }
  437. else if (info.Path.StartsWith("Rtsp", StringComparison.OrdinalIgnoreCase))
  438. {
  439. info.Protocol = MediaProtocol.Rtsp;
  440. }
  441. else
  442. {
  443. info.Protocol = MediaProtocol.File;
  444. }
  445. }
  446. if (string.IsNullOrEmpty(info.Container))
  447. {
  448. if (i.VideoType == VideoType.VideoFile || i.VideoType == VideoType.Iso)
  449. {
  450. if (!string.IsNullOrWhiteSpace(i.Path) && locationType != LocationType.Remote && locationType != LocationType.Virtual)
  451. {
  452. info.Container = System.IO.Path.GetExtension(i.Path).TrimStart('.');
  453. }
  454. }
  455. }
  456. try
  457. {
  458. var bitrate = i.TotalBitrate ??
  459. info.MediaStreams.Where(m => m.Type != MediaStreamType.Subtitle && !string.Equals(m.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase))
  460. .Select(m => m.BitRate ?? 0)
  461. .Sum();
  462. if (bitrate > 0)
  463. {
  464. info.Bitrate = bitrate;
  465. }
  466. }
  467. catch (OverflowException ex)
  468. {
  469. Logger.ErrorException("Error calculating total bitrate", ex);
  470. }
  471. return info;
  472. }
  473. private static string GetMediaSourceName(Video video, List<MediaStream> mediaStreams)
  474. {
  475. var terms = new List<string>();
  476. var videoStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video);
  477. var audioStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);
  478. if (video.Video3DFormat.HasValue)
  479. {
  480. terms.Add("3D");
  481. }
  482. if (video.VideoType == VideoType.BluRay)
  483. {
  484. terms.Add("Bluray");
  485. }
  486. else if (video.VideoType == VideoType.Dvd)
  487. {
  488. terms.Add("DVD");
  489. }
  490. else if (video.VideoType == VideoType.HdDvd)
  491. {
  492. terms.Add("HD-DVD");
  493. }
  494. else if (video.VideoType == VideoType.Iso)
  495. {
  496. if (video.IsoType.HasValue)
  497. {
  498. if (video.IsoType.Value == Model.Entities.IsoType.BluRay)
  499. {
  500. terms.Add("Bluray");
  501. }
  502. else if (video.IsoType.Value == Model.Entities.IsoType.Dvd)
  503. {
  504. terms.Add("DVD");
  505. }
  506. }
  507. else
  508. {
  509. terms.Add("ISO");
  510. }
  511. }
  512. if (videoStream != null)
  513. {
  514. if (videoStream.Width.HasValue)
  515. {
  516. if (videoStream.Width.Value >= 3800)
  517. {
  518. terms.Add("4K");
  519. }
  520. else if (videoStream.Width.Value >= 1900)
  521. {
  522. terms.Add("1080P");
  523. }
  524. else if (videoStream.Width.Value >= 1270)
  525. {
  526. terms.Add("720P");
  527. }
  528. else if (videoStream.Width.Value >= 700)
  529. {
  530. terms.Add("480P");
  531. }
  532. else
  533. {
  534. terms.Add("SD");
  535. }
  536. }
  537. }
  538. if (videoStream != null && !string.IsNullOrWhiteSpace(videoStream.Codec))
  539. {
  540. terms.Add(videoStream.Codec.ToUpper());
  541. }
  542. if (audioStream != null)
  543. {
  544. var audioCodec = string.Equals(audioStream.Codec, "dca", StringComparison.OrdinalIgnoreCase)
  545. ? audioStream.Profile
  546. : audioStream.Codec;
  547. if (!string.IsNullOrEmpty(audioCodec))
  548. {
  549. terms.Add(audioCodec.ToUpper());
  550. }
  551. }
  552. return string.Join("/", terms.ToArray());
  553. }
  554. }
  555. }