Video.cs 22 KB

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