Video.cs 22 KB

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