AvatarProfileViewModel.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. using Avalonia.Media;
  2. using DynamicData;
  3. using LibHac.Common;
  4. using LibHac.Fs;
  5. using LibHac.Fs.Fsa;
  6. using LibHac.FsSystem;
  7. using LibHac.Ncm;
  8. using LibHac.Tools.Fs;
  9. using LibHac.Tools.FsSystem;
  10. using LibHac.Tools.FsSystem.NcaUtils;
  11. using Ryujinx.Ava.UI.Models;
  12. using Ryujinx.HLE.FileSystem;
  13. using SixLabors.ImageSharp;
  14. using SixLabors.ImageSharp.Formats.Png;
  15. using SixLabors.ImageSharp.PixelFormats;
  16. using SixLabors.ImageSharp.Processing;
  17. using System;
  18. using System.Buffers.Binary;
  19. using System.Collections.Generic;
  20. using System.Collections.ObjectModel;
  21. using System.IO;
  22. using System.Linq;
  23. using System.Threading;
  24. using System.Threading.Tasks;
  25. using Color = Avalonia.Media.Color;
  26. namespace Ryujinx.Ava.UI.ViewModels
  27. {
  28. internal class AvatarProfileViewModel : BaseModel, IDisposable
  29. {
  30. private const int MaxImageTasks = 4;
  31. private static readonly Dictionary<string, byte[]> _avatarStore = new();
  32. private static bool _isPreloading;
  33. private static Action _loadCompleteAction;
  34. private ObservableCollection<ProfileImageModel> _images;
  35. private Color _backgroundColor = Colors.White;
  36. private int _selectedIndex;
  37. private int _imagesLoaded;
  38. private bool _isActive;
  39. private byte[] _selectedImage;
  40. private bool _isIndeterminate = true;
  41. public bool IsActive
  42. {
  43. get => _isActive;
  44. set => _isActive = value;
  45. }
  46. public AvatarProfileViewModel()
  47. {
  48. _images = new ObservableCollection<ProfileImageModel>();
  49. }
  50. public AvatarProfileViewModel(Action loadCompleteAction)
  51. {
  52. _images = new ObservableCollection<ProfileImageModel>();
  53. if (_isPreloading)
  54. {
  55. _loadCompleteAction = loadCompleteAction;
  56. }
  57. else
  58. {
  59. ReloadImages();
  60. }
  61. }
  62. public Color BackgroundColor
  63. {
  64. get => _backgroundColor;
  65. set
  66. {
  67. _backgroundColor = value;
  68. IsActive = false;
  69. ReloadImages();
  70. }
  71. }
  72. public ObservableCollection<ProfileImageModel> Images
  73. {
  74. get => _images;
  75. set
  76. {
  77. _images = value;
  78. OnPropertyChanged();
  79. }
  80. }
  81. public bool IsIndeterminate
  82. {
  83. get => _isIndeterminate;
  84. set
  85. {
  86. _isIndeterminate = value;
  87. OnPropertyChanged();
  88. }
  89. }
  90. public int ImageCount => _avatarStore.Count;
  91. public int ImagesLoaded
  92. {
  93. get => _imagesLoaded;
  94. set
  95. {
  96. _imagesLoaded = value;
  97. OnPropertyChanged();
  98. }
  99. }
  100. public int SelectedIndex
  101. {
  102. get => _selectedIndex;
  103. set
  104. {
  105. _selectedIndex = value;
  106. if (_selectedIndex == -1)
  107. {
  108. SelectedImage = null;
  109. }
  110. else
  111. {
  112. SelectedImage = _images[_selectedIndex].Data;
  113. }
  114. OnPropertyChanged();
  115. }
  116. }
  117. public byte[] SelectedImage
  118. {
  119. get => _selectedImage;
  120. private set => _selectedImage = value;
  121. }
  122. public void ReloadImages()
  123. {
  124. if (_isPreloading)
  125. {
  126. IsIndeterminate = false;
  127. return;
  128. }
  129. Task.Run(() =>
  130. {
  131. IsActive = true;
  132. Images.Clear();
  133. int selectedIndex = _selectedIndex;
  134. int index = 0;
  135. ImagesLoaded = 0;
  136. IsIndeterminate = false;
  137. var keys = _avatarStore.Keys.ToList();
  138. var newImages = new List<ProfileImageModel>();
  139. var tasks = new List<Task>();
  140. for (int i = 0; i < MaxImageTasks; i++)
  141. {
  142. var start = i;
  143. tasks.Add(Task.Run(() => ImageTask(start)));
  144. }
  145. Task.WaitAll(tasks.ToArray());
  146. Images.AddRange(newImages);
  147. void ImageTask(int start)
  148. {
  149. for (int i = start; i < keys.Count; i += MaxImageTasks)
  150. {
  151. if (!IsActive)
  152. {
  153. return;
  154. }
  155. var key = keys[i];
  156. var image = _avatarStore[keys[i]];
  157. var data = ProcessImage(image);
  158. newImages.Add(new ProfileImageModel(key, data));
  159. if (index++ == selectedIndex)
  160. {
  161. SelectedImage = data;
  162. }
  163. Interlocked.Increment(ref _imagesLoaded);
  164. OnPropertyChanged(nameof(ImagesLoaded));
  165. }
  166. }
  167. });
  168. }
  169. private byte[] ProcessImage(byte[] data)
  170. {
  171. using (MemoryStream streamJpg = new())
  172. {
  173. Image avatarImage = Image.Load(data, new PngDecoder());
  174. avatarImage.Mutate(x => x.BackgroundColor(new Rgba32(BackgroundColor.R,
  175. BackgroundColor.G,
  176. BackgroundColor.B,
  177. BackgroundColor.A)));
  178. avatarImage.SaveAsJpeg(streamJpg);
  179. return streamJpg.ToArray();
  180. }
  181. }
  182. public static void PreloadAvatars(ContentManager contentManager, VirtualFileSystem virtualFileSystem)
  183. {
  184. try
  185. {
  186. if (_avatarStore.Count > 0)
  187. {
  188. return;
  189. }
  190. _isPreloading = true;
  191. string contentPath =
  192. contentManager.GetInstalledContentPath(0x010000000000080A, StorageId.BuiltInSystem,
  193. NcaContentType.Data);
  194. string avatarPath = virtualFileSystem.SwitchPathToSystemPath(contentPath);
  195. if (!string.IsNullOrWhiteSpace(avatarPath))
  196. {
  197. using (IStorage ncaFileStream = new LocalStorage(avatarPath, FileAccess.Read, FileMode.Open))
  198. {
  199. Nca nca = new(virtualFileSystem.KeySet, ncaFileStream);
  200. IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid);
  201. foreach (DirectoryEntryEx item in romfs.EnumerateEntries())
  202. {
  203. // TODO: Parse DatabaseInfo.bin and table.bin files for more accuracy.
  204. if (item.Type == DirectoryEntryType.File && item.FullPath.Contains("chara") &&
  205. item.FullPath.Contains("szs"))
  206. {
  207. using var file = new UniqueRef<IFile>();
  208. romfs.OpenFile(ref file.Ref, ("/" + item.FullPath).ToU8Span(), OpenMode.Read)
  209. .ThrowIfFailure();
  210. using (MemoryStream stream = new())
  211. using (MemoryStream streamPng = new())
  212. {
  213. file.Get.AsStream().CopyTo(stream);
  214. stream.Position = 0;
  215. Image avatarImage = Image.LoadPixelData<Rgba32>(DecompressYaz0(stream), 256, 256);
  216. avatarImage.SaveAsPng(streamPng);
  217. _avatarStore.Add(item.FullPath, streamPng.ToArray());
  218. }
  219. }
  220. }
  221. }
  222. }
  223. }
  224. finally
  225. {
  226. _isPreloading = false;
  227. _loadCompleteAction?.Invoke();
  228. }
  229. }
  230. private static byte[] DecompressYaz0(Stream stream)
  231. {
  232. using (BinaryReader reader = new(stream))
  233. {
  234. reader.ReadInt32(); // Magic
  235. uint decodedLength = BinaryPrimitives.ReverseEndianness(reader.ReadUInt32());
  236. reader.ReadInt64(); // Padding
  237. byte[] input = new byte[stream.Length - stream.Position];
  238. stream.Read(input, 0, input.Length);
  239. uint inputOffset = 0;
  240. byte[] output = new byte[decodedLength];
  241. uint outputOffset = 0;
  242. ushort mask = 0;
  243. byte header = 0;
  244. while (outputOffset < decodedLength)
  245. {
  246. if ((mask >>= 1) == 0)
  247. {
  248. header = input[inputOffset++];
  249. mask = 0x80;
  250. }
  251. if ((header & mask) != 0)
  252. {
  253. if (outputOffset == output.Length)
  254. {
  255. break;
  256. }
  257. output[outputOffset++] = input[inputOffset++];
  258. }
  259. else
  260. {
  261. byte byte1 = input[inputOffset++];
  262. byte byte2 = input[inputOffset++];
  263. uint dist = (uint)((byte1 & 0xF) << 8) | byte2;
  264. uint position = outputOffset - (dist + 1);
  265. uint length = (uint)byte1 >> 4;
  266. if (length == 0)
  267. {
  268. length = (uint)input[inputOffset++] + 0x12;
  269. }
  270. else
  271. {
  272. length += 2;
  273. }
  274. uint gap = outputOffset - position;
  275. uint nonOverlappingLength = length;
  276. if (nonOverlappingLength > gap)
  277. {
  278. nonOverlappingLength = gap;
  279. }
  280. Buffer.BlockCopy(output, (int)position, output, (int)outputOffset, (int)nonOverlappingLength);
  281. outputOffset += nonOverlappingLength;
  282. position += nonOverlappingLength;
  283. length -= nonOverlappingLength;
  284. while (length-- > 0)
  285. {
  286. output[outputOffset++] = output[position++];
  287. }
  288. }
  289. }
  290. return output;
  291. }
  292. }
  293. public void Dispose()
  294. {
  295. _loadCompleteAction = null;
  296. IsActive = false;
  297. }
  298. }
  299. }