Video.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  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 video bit rate.
  165. /// </summary>
  166. /// <value>The video bit rate.</value>
  167. public int? VideoBitRate { get; set; }
  168. /// <summary>
  169. /// Gets or sets the default index of the video stream.
  170. /// </summary>
  171. /// <value>The default index of the video stream.</value>
  172. public int? DefaultVideoStreamIndex { get; set; }
  173. /// <summary>
  174. /// Gets or sets the type of the video.
  175. /// </summary>
  176. /// <value>The type of the video.</value>
  177. public VideoType VideoType { get; set; }
  178. /// <summary>
  179. /// Gets or sets the type of the iso.
  180. /// </summary>
  181. /// <value>The type of the iso.</value>
  182. public IsoType? IsoType { get; set; }
  183. /// <summary>
  184. /// Gets or sets the video3 D format.
  185. /// </summary>
  186. /// <value>The video3 D format.</value>
  187. public Video3DFormat? Video3DFormat { get; set; }
  188. /// <summary>
  189. /// If the video is a folder-rip, this will hold the file list for the largest playlist
  190. /// </summary>
  191. public List<string> PlayableStreamFileNames { get; set; }
  192. /// <summary>
  193. /// Gets the playable stream files.
  194. /// </summary>
  195. /// <returns>List{System.String}.</returns>
  196. public List<string> GetPlayableStreamFiles()
  197. {
  198. return GetPlayableStreamFiles(Path);
  199. }
  200. /// <summary>
  201. /// Gets or sets the aspect ratio.
  202. /// </summary>
  203. /// <value>The aspect ratio.</value>
  204. public string AspectRatio { get; set; }
  205. [IgnoreDataMember]
  206. public override string ContainingFolderPath
  207. {
  208. get
  209. {
  210. if (IsStacked)
  211. {
  212. return System.IO.Path.GetDirectoryName(Path);
  213. }
  214. if (!IsPlaceHolder)
  215. {
  216. if (VideoType == VideoType.BluRay || VideoType == VideoType.Dvd ||
  217. VideoType == VideoType.HdDvd)
  218. {
  219. return Path;
  220. }
  221. }
  222. return base.ContainingFolderPath;
  223. }
  224. }
  225. [IgnoreDataMember]
  226. public override string FileNameWithoutExtension
  227. {
  228. get
  229. {
  230. if (LocationType == LocationType.FileSystem)
  231. {
  232. if (VideoType == VideoType.BluRay || VideoType == VideoType.Dvd || VideoType == VideoType.HdDvd)
  233. {
  234. return System.IO.Path.GetFileName(Path);
  235. }
  236. return System.IO.Path.GetFileNameWithoutExtension(Path);
  237. }
  238. return null;
  239. }
  240. }
  241. internal override bool IsValidFromResolver(BaseItem newItem)
  242. {
  243. var current = this;
  244. var newAsVideo = newItem as Video;
  245. if (newAsVideo != null)
  246. {
  247. if (!current.AdditionalParts.SequenceEqual(newAsVideo.AdditionalParts, StringComparer.OrdinalIgnoreCase))
  248. {
  249. return false;
  250. }
  251. if (!current.LocalAlternateVersions.SequenceEqual(newAsVideo.LocalAlternateVersions, StringComparer.OrdinalIgnoreCase))
  252. {
  253. return false;
  254. }
  255. }
  256. return base.IsValidFromResolver(newItem);
  257. }
  258. /// <summary>
  259. /// Gets the playable stream files.
  260. /// </summary>
  261. /// <param name="rootPath">The root path.</param>
  262. /// <returns>List{System.String}.</returns>
  263. public List<string> GetPlayableStreamFiles(string rootPath)
  264. {
  265. var allFiles = FileSystem.GetFilePaths(rootPath, true).ToList();
  266. return PlayableStreamFileNames.Select(name => allFiles.FirstOrDefault(f => string.Equals(System.IO.Path.GetFileName(f), name, StringComparison.OrdinalIgnoreCase)))
  267. .Where(f => !string.IsNullOrEmpty(f))
  268. .ToList();
  269. }
  270. /// <summary>
  271. /// Gets a value indicating whether [is3 D].
  272. /// </summary>
  273. /// <value><c>true</c> if [is3 D]; otherwise, <c>false</c>.</value>
  274. [IgnoreDataMember]
  275. public bool Is3D
  276. {
  277. get { return Video3DFormat.HasValue; }
  278. }
  279. /// <summary>
  280. /// Gets the type of the media.
  281. /// </summary>
  282. /// <value>The type of the media.</value>
  283. [IgnoreDataMember]
  284. public override string MediaType
  285. {
  286. get
  287. {
  288. return Model.Entities.MediaType.Video;
  289. }
  290. }
  291. protected override async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  292. {
  293. var hasChanges = await base.RefreshedOwnedItems(options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  294. if (IsStacked)
  295. {
  296. var tasks = AdditionalParts
  297. .Select(i => RefreshMetadataForOwnedVideo(options, i, cancellationToken));
  298. await Task.WhenAll(tasks).ConfigureAwait(false);
  299. }
  300. // Must have a parent to have additional parts or alternate versions
  301. // In other words, it must be part of the Parent/Child tree
  302. // The additional parts won't have additional parts themselves
  303. if (LocationType == LocationType.FileSystem && GetParent() != null)
  304. {
  305. if (!IsStacked)
  306. {
  307. RefreshLinkedAlternateVersions();
  308. var tasks = LocalAlternateVersions
  309. .Select(i => RefreshMetadataForOwnedVideo(options, i, cancellationToken));
  310. await Task.WhenAll(tasks).ConfigureAwait(false);
  311. }
  312. }
  313. return hasChanges;
  314. }
  315. private void RefreshLinkedAlternateVersions()
  316. {
  317. foreach (var child in LinkedAlternateVersions)
  318. {
  319. // Reset the cached value
  320. if (child.ItemId.HasValue && child.ItemId.Value == Guid.Empty)
  321. {
  322. child.ItemId = null;
  323. }
  324. }
  325. }
  326. public override async Task UpdateToRepository(ItemUpdateType updateReason, CancellationToken cancellationToken)
  327. {
  328. await base.UpdateToRepository(updateReason, cancellationToken).ConfigureAwait(false);
  329. var localAlternates = GetLocalAlternateVersionIds()
  330. .Select(i => LibraryManager.GetItemById(i))
  331. .Where(i => i != null);
  332. foreach (var item in localAlternates)
  333. {
  334. item.ImageInfos = ImageInfos;
  335. item.Overview = Overview;
  336. item.ProductionYear = ProductionYear;
  337. item.PremiereDate = PremiereDate;
  338. item.CommunityRating = CommunityRating;
  339. item.OfficialRating = OfficialRating;
  340. item.Genres = Genres;
  341. item.ProviderIds = ProviderIds;
  342. await item.UpdateToRepository(ItemUpdateType.MetadataDownload, cancellationToken).ConfigureAwait(false);
  343. }
  344. }
  345. public override IEnumerable<string> GetDeletePaths()
  346. {
  347. if (!IsInMixedFolder)
  348. {
  349. return new[] { ContainingFolderPath };
  350. }
  351. return base.GetDeletePaths();
  352. }
  353. public IEnumerable<MediaStream> GetMediaStreams()
  354. {
  355. var mediaSource = GetMediaSources(false)
  356. .FirstOrDefault();
  357. if (mediaSource == null)
  358. {
  359. return new List<MediaStream>();
  360. }
  361. return mediaSource.MediaStreams;
  362. }
  363. public virtual MediaStream GetDefaultVideoStream()
  364. {
  365. if (!DefaultVideoStreamIndex.HasValue)
  366. {
  367. return null;
  368. }
  369. return MediaSourceManager.GetMediaStreams(new MediaStreamQuery
  370. {
  371. ItemId = Id,
  372. Index = DefaultVideoStreamIndex.Value
  373. }).FirstOrDefault();
  374. }
  375. public virtual IEnumerable<MediaSourceInfo> GetMediaSources(bool enablePathSubstitution)
  376. {
  377. var item = this;
  378. var result = item.GetAlternateVersions()
  379. .Select(i => GetVersionInfo(enablePathSubstitution, i, MediaSourceType.Grouping))
  380. .ToList();
  381. result.Add(GetVersionInfo(enablePathSubstitution, item, MediaSourceType.Default));
  382. return result.OrderBy(i =>
  383. {
  384. if (i.VideoType == VideoType.VideoFile)
  385. {
  386. return 0;
  387. }
  388. return 1;
  389. }).ThenBy(i => i.Video3DFormat.HasValue ? 1 : 0)
  390. .ThenByDescending(i =>
  391. {
  392. var stream = i.VideoStream;
  393. return stream == null || stream.Width == null ? 0 : stream.Width.Value;
  394. })
  395. .ToList();
  396. }
  397. private static MediaSourceInfo GetVersionInfo(bool enablePathSubstitution, Video i, MediaSourceType type)
  398. {
  399. var mediaStreams = MediaSourceManager.GetMediaStreams(i.Id)
  400. .ToList();
  401. var locationType = i.LocationType;
  402. var info = new MediaSourceInfo
  403. {
  404. Id = i.Id.ToString("N"),
  405. IsoType = i.IsoType,
  406. Protocol = locationType == LocationType.Remote ? MediaProtocol.Http : MediaProtocol.File,
  407. MediaStreams = mediaStreams,
  408. Name = GetMediaSourceName(i, mediaStreams),
  409. Path = enablePathSubstitution ? GetMappedPath(i.Path, locationType) : i.Path,
  410. RunTimeTicks = i.RunTimeTicks,
  411. Video3DFormat = i.Video3DFormat,
  412. VideoType = i.VideoType,
  413. Container = i.Container,
  414. Size = i.Size,
  415. Timestamp = i.Timestamp,
  416. Type = type,
  417. PlayableStreamFileNames = i.PlayableStreamFileNames.ToList(),
  418. SupportsDirectStream = i.VideoType == VideoType.VideoFile
  419. };
  420. if (i.IsShortcut)
  421. {
  422. info.Path = i.ShortcutPath;
  423. if (info.Path.StartsWith("Http", StringComparison.OrdinalIgnoreCase))
  424. {
  425. info.Protocol = MediaProtocol.Http;
  426. }
  427. else if (info.Path.StartsWith("Rtmp", StringComparison.OrdinalIgnoreCase))
  428. {
  429. info.Protocol = MediaProtocol.Rtmp;
  430. }
  431. else if (info.Path.StartsWith("Rtsp", StringComparison.OrdinalIgnoreCase))
  432. {
  433. info.Protocol = MediaProtocol.Rtsp;
  434. }
  435. else
  436. {
  437. info.Protocol = MediaProtocol.File;
  438. }
  439. }
  440. if (string.IsNullOrEmpty(info.Container))
  441. {
  442. if (i.VideoType == VideoType.VideoFile || i.VideoType == VideoType.Iso)
  443. {
  444. if (!string.IsNullOrWhiteSpace(i.Path) && locationType != LocationType.Remote && locationType != LocationType.Virtual)
  445. {
  446. info.Container = System.IO.Path.GetExtension(i.Path).TrimStart('.');
  447. }
  448. }
  449. }
  450. try
  451. {
  452. var bitrate = i.TotalBitrate ??
  453. info.MediaStreams.Where(m => m.Type != MediaStreamType.Subtitle && !string.Equals(m.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase))
  454. .Select(m => m.BitRate ?? 0)
  455. .Sum();
  456. if (bitrate > 0)
  457. {
  458. info.Bitrate = bitrate;
  459. }
  460. }
  461. catch (OverflowException ex)
  462. {
  463. Logger.ErrorException("Error calculating total bitrate", ex);
  464. }
  465. return info;
  466. }
  467. private static string GetMediaSourceName(Video video, List<MediaStream> mediaStreams)
  468. {
  469. var terms = new List<string>();
  470. var videoStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video);
  471. var audioStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);
  472. if (video.Video3DFormat.HasValue)
  473. {
  474. terms.Add("3D");
  475. }
  476. if (video.VideoType == VideoType.BluRay)
  477. {
  478. terms.Add("Bluray");
  479. }
  480. else if (video.VideoType == VideoType.Dvd)
  481. {
  482. terms.Add("DVD");
  483. }
  484. else if (video.VideoType == VideoType.HdDvd)
  485. {
  486. terms.Add("HD-DVD");
  487. }
  488. else if (video.VideoType == VideoType.Iso)
  489. {
  490. if (video.IsoType.HasValue)
  491. {
  492. if (video.IsoType.Value == Model.Entities.IsoType.BluRay)
  493. {
  494. terms.Add("Bluray");
  495. }
  496. else if (video.IsoType.Value == Model.Entities.IsoType.Dvd)
  497. {
  498. terms.Add("DVD");
  499. }
  500. }
  501. else
  502. {
  503. terms.Add("ISO");
  504. }
  505. }
  506. if (videoStream != null)
  507. {
  508. if (videoStream.Width.HasValue)
  509. {
  510. if (videoStream.Width.Value >= 3800)
  511. {
  512. terms.Add("4K");
  513. }
  514. else if (videoStream.Width.Value >= 1900)
  515. {
  516. terms.Add("1080P");
  517. }
  518. else if (videoStream.Width.Value >= 1270)
  519. {
  520. terms.Add("720P");
  521. }
  522. else if (videoStream.Width.Value >= 700)
  523. {
  524. terms.Add("480P");
  525. }
  526. else
  527. {
  528. terms.Add("SD");
  529. }
  530. }
  531. }
  532. if (videoStream != null && !string.IsNullOrWhiteSpace(videoStream.Codec))
  533. {
  534. terms.Add(videoStream.Codec.ToUpper());
  535. }
  536. if (audioStream != null)
  537. {
  538. var audioCodec = string.Equals(audioStream.Codec, "dca", StringComparison.OrdinalIgnoreCase)
  539. ? audioStream.Profile
  540. : audioStream.Codec;
  541. if (!string.IsNullOrEmpty(audioCodec))
  542. {
  543. terms.Add(audioCodec.ToUpper());
  544. }
  545. }
  546. return string.Join("/", terms.ToArray());
  547. }
  548. }
  549. }