Video.cs 21 KB

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