Video.cs 21 KB

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