Video.cs 20 KB

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