Video.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  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. public bool IsHD { get; set; }
  286. /// <summary>
  287. /// Gets the type of the media.
  288. /// </summary>
  289. /// <value>The type of the media.</value>
  290. [IgnoreDataMember]
  291. public override string MediaType
  292. {
  293. get
  294. {
  295. return Model.Entities.MediaType.Video;
  296. }
  297. }
  298. protected override async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  299. {
  300. var hasChanges = await base.RefreshedOwnedItems(options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  301. if (IsStacked)
  302. {
  303. var tasks = AdditionalParts
  304. .Select(i => RefreshMetadataForOwnedVideo(options, i, cancellationToken));
  305. await Task.WhenAll(tasks).ConfigureAwait(false);
  306. }
  307. // Must have a parent to have additional parts or alternate versions
  308. // In other words, it must be part of the Parent/Child tree
  309. // The additional parts won't have additional parts themselves
  310. if (LocationType == LocationType.FileSystem && Parent != null)
  311. {
  312. if (!IsStacked)
  313. {
  314. RefreshLinkedAlternateVersions();
  315. var tasks = LocalAlternateVersions
  316. .Select(i => RefreshMetadataForOwnedVideo(options, i, cancellationToken));
  317. await Task.WhenAll(tasks).ConfigureAwait(false);
  318. }
  319. }
  320. return hasChanges;
  321. }
  322. private void RefreshLinkedAlternateVersions()
  323. {
  324. foreach (var child in LinkedAlternateVersions)
  325. {
  326. // Reset the cached value
  327. if (child.ItemId.HasValue && child.ItemId.Value == Guid.Empty)
  328. {
  329. child.ItemId = null;
  330. }
  331. }
  332. }
  333. public override async Task UpdateToRepository(ItemUpdateType updateReason, CancellationToken cancellationToken)
  334. {
  335. await base.UpdateToRepository(updateReason, cancellationToken).ConfigureAwait(false);
  336. var localAlternates = GetLocalAlternateVersionIds()
  337. .Select(i => LibraryManager.GetItemById(i))
  338. .Where(i => i != null);
  339. foreach (var item in localAlternates)
  340. {
  341. item.ImageInfos = ImageInfos;
  342. item.Overview = Overview;
  343. item.ProductionYear = ProductionYear;
  344. item.PremiereDate = PremiereDate;
  345. item.CommunityRating = CommunityRating;
  346. item.OfficialRating = OfficialRating;
  347. item.Genres = Genres;
  348. item.ProviderIds = ProviderIds;
  349. await item.UpdateToRepository(ItemUpdateType.MetadataDownload, cancellationToken).ConfigureAwait(false);
  350. }
  351. }
  352. public override IEnumerable<string> GetDeletePaths()
  353. {
  354. if (!IsInMixedFolder)
  355. {
  356. return new[] { ContainingFolderPath };
  357. }
  358. return base.GetDeletePaths();
  359. }
  360. public IEnumerable<MediaStream> GetMediaStreams()
  361. {
  362. var mediaSource = GetMediaSources(false)
  363. .FirstOrDefault();
  364. if (mediaSource == null)
  365. {
  366. return new List<MediaStream>();
  367. }
  368. return mediaSource.MediaStreams;
  369. }
  370. public virtual MediaStream GetDefaultVideoStream()
  371. {
  372. if (!DefaultVideoStreamIndex.HasValue)
  373. {
  374. return null;
  375. }
  376. return MediaSourceManager.GetMediaStreams(new MediaStreamQuery
  377. {
  378. ItemId = Id,
  379. Index = DefaultVideoStreamIndex.Value
  380. }).FirstOrDefault();
  381. }
  382. public virtual IEnumerable<MediaSourceInfo> GetMediaSources(bool enablePathSubstitution)
  383. {
  384. var item = this;
  385. var result = item.GetAlternateVersions()
  386. .Select(i => GetVersionInfo(enablePathSubstitution, i, MediaSourceType.Grouping))
  387. .ToList();
  388. result.Add(GetVersionInfo(enablePathSubstitution, item, MediaSourceType.Default));
  389. return result.OrderBy(i =>
  390. {
  391. if (i.VideoType == VideoType.VideoFile)
  392. {
  393. return 0;
  394. }
  395. return 1;
  396. }).ThenBy(i => i.Video3DFormat.HasValue ? 1 : 0)
  397. .ThenByDescending(i =>
  398. {
  399. var stream = i.VideoStream;
  400. return stream == null || stream.Width == null ? 0 : stream.Width.Value;
  401. })
  402. .ToList();
  403. }
  404. private static MediaSourceInfo GetVersionInfo(bool enablePathSubstitution, Video i, MediaSourceType type)
  405. {
  406. var mediaStreams = MediaSourceManager.GetMediaStreams(i.Id)
  407. .ToList();
  408. var locationType = i.LocationType;
  409. var info = new MediaSourceInfo
  410. {
  411. Id = i.Id.ToString("N"),
  412. IsoType = i.IsoType,
  413. Protocol = locationType == LocationType.Remote ? MediaProtocol.Http : MediaProtocol.File,
  414. MediaStreams = mediaStreams,
  415. Name = GetMediaSourceName(i, mediaStreams),
  416. Path = enablePathSubstitution ? GetMappedPath(i.Path, locationType) : i.Path,
  417. RunTimeTicks = i.RunTimeTicks,
  418. Video3DFormat = i.Video3DFormat,
  419. VideoType = i.VideoType,
  420. Container = i.Container,
  421. Size = i.Size,
  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. }