Video.cs 22 KB

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