Video.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  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.Globalization;
  10. using System.Linq;
  11. using System.Runtime.Serialization;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using CommonIO;
  15. using MediaBrowser.Controller.Channels;
  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. public List<ChannelMediaInfo> ChannelMediaSources { get; set; }
  35. [IgnoreDataMember]
  36. public bool IsThemeMedia
  37. {
  38. get
  39. {
  40. return ExtraType.HasValue && ExtraType.Value == Model.Entities.ExtraType.ThemeVideo;
  41. }
  42. }
  43. public long? Size { get; set; }
  44. public string Container { get; set; }
  45. public int? TotalBitrate { get; set; }
  46. public string ShortOverview { get; set; }
  47. public ExtraType? ExtraType { get; set; }
  48. /// <summary>
  49. /// Gets or sets the timestamp.
  50. /// </summary>
  51. /// <value>The timestamp.</value>
  52. public TransportStreamTimestamp? Timestamp { get; set; }
  53. public Video()
  54. {
  55. PlayableStreamFileNames = new List<string>();
  56. AdditionalParts = new List<string>();
  57. LocalAlternateVersions = new List<string>();
  58. Tags = new List<string>();
  59. SubtitleFiles = new List<string>();
  60. LinkedAlternateVersions = new List<LinkedChild>();
  61. }
  62. public override bool CanDownload()
  63. {
  64. if (VideoType == VideoType.HdDvd || VideoType == VideoType.Dvd ||
  65. VideoType == VideoType.BluRay)
  66. {
  67. return false;
  68. }
  69. var locationType = LocationType;
  70. return locationType != LocationType.Remote &&
  71. locationType != LocationType.Virtual;
  72. }
  73. [IgnoreDataMember]
  74. public override bool SupportsAddingToPlaylist
  75. {
  76. get { return LocationType == LocationType.FileSystem && RunTimeTicks.HasValue; }
  77. }
  78. [IgnoreDataMember]
  79. public int MediaSourceCount
  80. {
  81. get
  82. {
  83. return LinkedAlternateVersions.Count + LocalAlternateVersions.Count + 1;
  84. }
  85. }
  86. [IgnoreDataMember]
  87. public bool IsStacked
  88. {
  89. get { return AdditionalParts.Count > 0; }
  90. }
  91. [IgnoreDataMember]
  92. public bool HasLocalAlternateVersions
  93. {
  94. get { return LocalAlternateVersions.Count > 0; }
  95. }
  96. [IgnoreDataMember]
  97. public bool IsArchive
  98. {
  99. get
  100. {
  101. if (string.IsNullOrWhiteSpace(Path))
  102. {
  103. return false;
  104. }
  105. var ext = System.IO.Path.GetExtension(Path) ?? string.Empty;
  106. return new[] { ".zip", ".rar", ".7z" }.Contains(ext, StringComparer.OrdinalIgnoreCase);
  107. }
  108. }
  109. public IEnumerable<Guid> GetAdditionalPartIds()
  110. {
  111. return AdditionalParts.Select(i => LibraryManager.GetNewItemId(i, typeof(Video)));
  112. }
  113. public IEnumerable<Guid> GetLocalAlternateVersionIds()
  114. {
  115. return LocalAlternateVersions.Select(i => LibraryManager.GetNewItemId(i, typeof(Video)));
  116. }
  117. protected override string CreateUserDataKey()
  118. {
  119. if (ExtraType.HasValue)
  120. {
  121. var key = this.GetProviderId(MetadataProviders.Imdb) ?? this.GetProviderId(MetadataProviders.Tmdb);
  122. if (!string.IsNullOrWhiteSpace(key))
  123. {
  124. key = key + "-" + ExtraType.ToString().ToLower();
  125. // Make sure different trailers have their own data.
  126. if (RunTimeTicks.HasValue)
  127. {
  128. key += "-" + RunTimeTicks.Value.ToString(CultureInfo.InvariantCulture);
  129. }
  130. return key;
  131. }
  132. }
  133. return base.CreateUserDataKey();
  134. }
  135. /// <summary>
  136. /// Gets the linked children.
  137. /// </summary>
  138. /// <returns>IEnumerable{BaseItem}.</returns>
  139. public IEnumerable<Video> GetAlternateVersions()
  140. {
  141. var filesWithinSameDirectory = GetLocalAlternateVersionIds()
  142. .Select(i => LibraryManager.GetItemById(i))
  143. .Where(i => i != null)
  144. .OfType<Video>();
  145. return filesWithinSameDirectory.Concat(GetLinkedAlternateVersions())
  146. .OrderBy(i => i.SortName);
  147. }
  148. public IEnumerable<Video> GetLinkedAlternateVersions()
  149. {
  150. var linkedVersions = LinkedAlternateVersions
  151. .Select(GetLinkedChild)
  152. .Where(i => i != null)
  153. .OfType<Video>();
  154. return linkedVersions
  155. .OrderBy(i => i.SortName);
  156. }
  157. /// <summary>
  158. /// Gets the additional parts.
  159. /// </summary>
  160. /// <returns>IEnumerable{Video}.</returns>
  161. public IEnumerable<Video> GetAdditionalParts()
  162. {
  163. return GetAdditionalPartIds()
  164. .Select(i => LibraryManager.GetItemById(i))
  165. .Where(i => i != null)
  166. .OfType<Video>()
  167. .OrderBy(i => i.SortName);
  168. }
  169. /// <summary>
  170. /// Gets or sets the subtitle paths.
  171. /// </summary>
  172. /// <value>The subtitle paths.</value>
  173. public List<string> SubtitleFiles { get; set; }
  174. /// <summary>
  175. /// Gets or sets a value indicating whether this instance has subtitles.
  176. /// </summary>
  177. /// <value><c>true</c> if this instance has subtitles; otherwise, <c>false</c>.</value>
  178. public bool HasSubtitles { get; set; }
  179. public bool IsPlaceHolder { get; set; }
  180. public bool IsShortcut { get; set; }
  181. public string ShortcutPath { get; set; }
  182. /// <summary>
  183. /// Gets or sets the video bit rate.
  184. /// </summary>
  185. /// <value>The video bit rate.</value>
  186. public int? VideoBitRate { get; set; }
  187. /// <summary>
  188. /// Gets or sets the default index of the video stream.
  189. /// </summary>
  190. /// <value>The default index of the video stream.</value>
  191. public int? DefaultVideoStreamIndex { get; set; }
  192. /// <summary>
  193. /// Gets or sets the type of the video.
  194. /// </summary>
  195. /// <value>The type of the video.</value>
  196. public VideoType VideoType { get; set; }
  197. /// <summary>
  198. /// Gets or sets the type of the iso.
  199. /// </summary>
  200. /// <value>The type of the iso.</value>
  201. public IsoType? IsoType { get; set; }
  202. /// <summary>
  203. /// Gets or sets the video3 D format.
  204. /// </summary>
  205. /// <value>The video3 D format.</value>
  206. public Video3DFormat? Video3DFormat { get; set; }
  207. /// <summary>
  208. /// If the video is a folder-rip, this will hold the file list for the largest playlist
  209. /// </summary>
  210. public List<string> PlayableStreamFileNames { get; set; }
  211. /// <summary>
  212. /// Gets the playable stream files.
  213. /// </summary>
  214. /// <returns>List{System.String}.</returns>
  215. public List<string> GetPlayableStreamFiles()
  216. {
  217. return GetPlayableStreamFiles(Path);
  218. }
  219. /// <summary>
  220. /// Gets or sets the aspect ratio.
  221. /// </summary>
  222. /// <value>The aspect ratio.</value>
  223. public string AspectRatio { get; set; }
  224. [IgnoreDataMember]
  225. public override string ContainingFolderPath
  226. {
  227. get
  228. {
  229. if (IsStacked)
  230. {
  231. return System.IO.Path.GetDirectoryName(Path);
  232. }
  233. if (!IsPlaceHolder)
  234. {
  235. if (VideoType == VideoType.BluRay || VideoType == VideoType.Dvd ||
  236. VideoType == VideoType.HdDvd)
  237. {
  238. return Path;
  239. }
  240. }
  241. return base.ContainingFolderPath;
  242. }
  243. }
  244. [IgnoreDataMember]
  245. public override string FileNameWithoutExtension
  246. {
  247. get
  248. {
  249. if (LocationType == LocationType.FileSystem)
  250. {
  251. if (VideoType == VideoType.BluRay || VideoType == VideoType.Dvd || VideoType == VideoType.HdDvd)
  252. {
  253. return System.IO.Path.GetFileName(Path);
  254. }
  255. return System.IO.Path.GetFileNameWithoutExtension(Path);
  256. }
  257. return null;
  258. }
  259. }
  260. internal override bool IsValidFromResolver(BaseItem newItem)
  261. {
  262. var current = this;
  263. var newAsVideo = newItem as Video;
  264. if (newAsVideo != null)
  265. {
  266. if (!current.AdditionalParts.SequenceEqual(newAsVideo.AdditionalParts, StringComparer.OrdinalIgnoreCase))
  267. {
  268. return false;
  269. }
  270. if (!current.LocalAlternateVersions.SequenceEqual(newAsVideo.LocalAlternateVersions, StringComparer.OrdinalIgnoreCase))
  271. {
  272. return false;
  273. }
  274. if (newAsVideo.VideoType != VideoType)
  275. {
  276. return false;
  277. }
  278. }
  279. return base.IsValidFromResolver(newItem);
  280. }
  281. /// <summary>
  282. /// Gets the playable stream files.
  283. /// </summary>
  284. /// <param name="rootPath">The root path.</param>
  285. /// <returns>List{System.String}.</returns>
  286. public List<string> GetPlayableStreamFiles(string rootPath)
  287. {
  288. var allFiles = FileSystem.GetFilePaths(rootPath, true).ToList();
  289. return PlayableStreamFileNames.Select(name => allFiles.FirstOrDefault(f => string.Equals(System.IO.Path.GetFileName(f), name, StringComparison.OrdinalIgnoreCase)))
  290. .Where(f => !string.IsNullOrEmpty(f))
  291. .ToList();
  292. }
  293. /// <summary>
  294. /// Gets a value indicating whether [is3 D].
  295. /// </summary>
  296. /// <value><c>true</c> if [is3 D]; otherwise, <c>false</c>.</value>
  297. [IgnoreDataMember]
  298. public bool Is3D
  299. {
  300. get { return Video3DFormat.HasValue; }
  301. }
  302. /// <summary>
  303. /// Gets the type of the media.
  304. /// </summary>
  305. /// <value>The type of the media.</value>
  306. [IgnoreDataMember]
  307. public override string MediaType
  308. {
  309. get
  310. {
  311. return Model.Entities.MediaType.Video;
  312. }
  313. }
  314. protected override async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  315. {
  316. var hasChanges = await base.RefreshedOwnedItems(options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  317. if (IsStacked)
  318. {
  319. var tasks = AdditionalParts
  320. .Select(i => RefreshMetadataForOwnedVideo(options, i, cancellationToken));
  321. await Task.WhenAll(tasks).ConfigureAwait(false);
  322. }
  323. // Must have a parent to have additional parts or alternate versions
  324. // In other words, it must be part of the Parent/Child tree
  325. // The additional parts won't have additional parts themselves
  326. if (LocationType == LocationType.FileSystem && GetParent() != null)
  327. {
  328. if (!IsStacked)
  329. {
  330. RefreshLinkedAlternateVersions();
  331. var tasks = LocalAlternateVersions
  332. .Select(i => RefreshMetadataForOwnedVideo(options, i, cancellationToken));
  333. await Task.WhenAll(tasks).ConfigureAwait(false);
  334. }
  335. }
  336. return hasChanges;
  337. }
  338. private void RefreshLinkedAlternateVersions()
  339. {
  340. foreach (var child in LinkedAlternateVersions)
  341. {
  342. // Reset the cached value
  343. if (child.ItemId.HasValue && child.ItemId.Value == Guid.Empty)
  344. {
  345. child.ItemId = null;
  346. }
  347. }
  348. }
  349. public override async Task UpdateToRepository(ItemUpdateType updateReason, CancellationToken cancellationToken)
  350. {
  351. await base.UpdateToRepository(updateReason, cancellationToken).ConfigureAwait(false);
  352. var localAlternates = GetLocalAlternateVersionIds()
  353. .Select(i => LibraryManager.GetItemById(i))
  354. .Where(i => i != null);
  355. foreach (var item in localAlternates)
  356. {
  357. item.ImageInfos = ImageInfos;
  358. item.Overview = Overview;
  359. item.ProductionYear = ProductionYear;
  360. item.PremiereDate = PremiereDate;
  361. item.CommunityRating = CommunityRating;
  362. item.OfficialRating = OfficialRating;
  363. item.Genres = Genres;
  364. item.ProviderIds = ProviderIds;
  365. await item.UpdateToRepository(ItemUpdateType.MetadataDownload, cancellationToken).ConfigureAwait(false);
  366. }
  367. }
  368. public override IEnumerable<string> GetDeletePaths()
  369. {
  370. if (!IsInMixedFolder)
  371. {
  372. return new[] { ContainingFolderPath };
  373. }
  374. return base.GetDeletePaths();
  375. }
  376. public IEnumerable<MediaStream> GetMediaStreams()
  377. {
  378. var mediaSource = GetMediaSources(false)
  379. .FirstOrDefault();
  380. if (mediaSource == null)
  381. {
  382. return new List<MediaStream>();
  383. }
  384. return mediaSource.MediaStreams;
  385. }
  386. public virtual MediaStream GetDefaultVideoStream()
  387. {
  388. if (!DefaultVideoStreamIndex.HasValue)
  389. {
  390. return null;
  391. }
  392. return MediaSourceManager.GetMediaStreams(new MediaStreamQuery
  393. {
  394. ItemId = Id,
  395. Index = DefaultVideoStreamIndex.Value
  396. }).FirstOrDefault();
  397. }
  398. public virtual IEnumerable<MediaSourceInfo> GetMediaSources(bool enablePathSubstitution)
  399. {
  400. if (SourceType == SourceType.Channel)
  401. {
  402. var sources = ChannelManager.GetStaticMediaSources(this, false, CancellationToken.None)
  403. .Result.ToList();
  404. if (sources.Count > 0)
  405. {
  406. return sources;
  407. }
  408. return new List<MediaSourceInfo>
  409. {
  410. GetVersionInfo(enablePathSubstitution, this, MediaSourceType.Placeholder)
  411. };
  412. }
  413. var item = this;
  414. var result = item.GetAlternateVersions()
  415. .Select(i => GetVersionInfo(enablePathSubstitution, i, MediaSourceType.Grouping))
  416. .ToList();
  417. result.Add(GetVersionInfo(enablePathSubstitution, item, MediaSourceType.Default));
  418. return result.OrderBy(i =>
  419. {
  420. if (i.VideoType == VideoType.VideoFile)
  421. {
  422. return 0;
  423. }
  424. return 1;
  425. }).ThenBy(i => i.Video3DFormat.HasValue ? 1 : 0)
  426. .ThenByDescending(i =>
  427. {
  428. var stream = i.VideoStream;
  429. return stream == null || stream.Width == null ? 0 : stream.Width.Value;
  430. })
  431. .ToList();
  432. }
  433. private static MediaSourceInfo GetVersionInfo(bool enablePathSubstitution, Video i, MediaSourceType type)
  434. {
  435. var mediaStreams = MediaSourceManager.GetMediaStreams(i.Id)
  436. .ToList();
  437. var locationType = i.LocationType;
  438. var info = new MediaSourceInfo
  439. {
  440. Id = i.Id.ToString("N"),
  441. IsoType = i.IsoType,
  442. Protocol = locationType == LocationType.Remote ? MediaProtocol.Http : MediaProtocol.File,
  443. MediaStreams = mediaStreams,
  444. Name = GetMediaSourceName(i, mediaStreams),
  445. Path = enablePathSubstitution ? GetMappedPath(i.Path, locationType) : i.Path,
  446. RunTimeTicks = i.RunTimeTicks,
  447. Video3DFormat = i.Video3DFormat,
  448. VideoType = i.VideoType,
  449. Container = i.Container,
  450. Size = i.Size,
  451. Timestamp = i.Timestamp,
  452. Type = type,
  453. PlayableStreamFileNames = i.PlayableStreamFileNames.ToList(),
  454. SupportsDirectStream = i.VideoType == VideoType.VideoFile
  455. };
  456. if (i.IsShortcut)
  457. {
  458. info.Path = i.ShortcutPath;
  459. if (info.Path.StartsWith("Http", StringComparison.OrdinalIgnoreCase))
  460. {
  461. info.Protocol = MediaProtocol.Http;
  462. }
  463. else if (info.Path.StartsWith("Rtmp", StringComparison.OrdinalIgnoreCase))
  464. {
  465. info.Protocol = MediaProtocol.Rtmp;
  466. }
  467. else if (info.Path.StartsWith("Rtsp", StringComparison.OrdinalIgnoreCase))
  468. {
  469. info.Protocol = MediaProtocol.Rtsp;
  470. }
  471. else
  472. {
  473. info.Protocol = MediaProtocol.File;
  474. }
  475. }
  476. if (string.IsNullOrEmpty(info.Container))
  477. {
  478. if (i.VideoType == VideoType.VideoFile || i.VideoType == VideoType.Iso)
  479. {
  480. if (!string.IsNullOrWhiteSpace(i.Path) && locationType != LocationType.Remote && locationType != LocationType.Virtual)
  481. {
  482. info.Container = System.IO.Path.GetExtension(i.Path).TrimStart('.');
  483. }
  484. }
  485. }
  486. try
  487. {
  488. var bitrate = i.TotalBitrate ??
  489. info.MediaStreams.Where(m => m.Type != MediaStreamType.Subtitle && !string.Equals(m.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase))
  490. .Select(m => m.BitRate ?? 0)
  491. .Sum();
  492. if (bitrate > 0)
  493. {
  494. info.Bitrate = bitrate;
  495. }
  496. }
  497. catch (OverflowException ex)
  498. {
  499. Logger.ErrorException("Error calculating total bitrate", ex);
  500. }
  501. return info;
  502. }
  503. private static string GetMediaSourceName(Video video, List<MediaStream> mediaStreams)
  504. {
  505. var terms = new List<string>();
  506. var videoStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video);
  507. var audioStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);
  508. if (video.Video3DFormat.HasValue)
  509. {
  510. terms.Add("3D");
  511. }
  512. if (video.VideoType == VideoType.BluRay)
  513. {
  514. terms.Add("Bluray");
  515. }
  516. else if (video.VideoType == VideoType.Dvd)
  517. {
  518. terms.Add("DVD");
  519. }
  520. else if (video.VideoType == VideoType.HdDvd)
  521. {
  522. terms.Add("HD-DVD");
  523. }
  524. else if (video.VideoType == VideoType.Iso)
  525. {
  526. if (video.IsoType.HasValue)
  527. {
  528. if (video.IsoType.Value == Model.Entities.IsoType.BluRay)
  529. {
  530. terms.Add("Bluray");
  531. }
  532. else if (video.IsoType.Value == Model.Entities.IsoType.Dvd)
  533. {
  534. terms.Add("DVD");
  535. }
  536. }
  537. else
  538. {
  539. terms.Add("ISO");
  540. }
  541. }
  542. if (videoStream != null)
  543. {
  544. if (videoStream.Width.HasValue)
  545. {
  546. if (videoStream.Width.Value >= 3800)
  547. {
  548. terms.Add("4K");
  549. }
  550. else if (videoStream.Width.Value >= 1900)
  551. {
  552. terms.Add("1080P");
  553. }
  554. else if (videoStream.Width.Value >= 1270)
  555. {
  556. terms.Add("720P");
  557. }
  558. else if (videoStream.Width.Value >= 700)
  559. {
  560. terms.Add("480P");
  561. }
  562. else
  563. {
  564. terms.Add("SD");
  565. }
  566. }
  567. }
  568. if (videoStream != null && !string.IsNullOrWhiteSpace(videoStream.Codec))
  569. {
  570. terms.Add(videoStream.Codec.ToUpper());
  571. }
  572. if (audioStream != null)
  573. {
  574. var audioCodec = string.Equals(audioStream.Codec, "dca", StringComparison.OrdinalIgnoreCase)
  575. ? audioStream.Profile
  576. : audioStream.Codec;
  577. if (!string.IsNullOrEmpty(audioCodec))
  578. {
  579. terms.Add(audioCodec.ToUpper());
  580. }
  581. }
  582. return string.Join("/", terms.ToArray());
  583. }
  584. }
  585. }