Video.cs 21 KB

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