1
0

Generator.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-License-Identifier: AGPL-3.0-or-later
  5. */
  6. namespace OC\Preview;
  7. use OCP\EventDispatcher\IEventDispatcher;
  8. use OCP\Files\File;
  9. use OCP\Files\IAppData;
  10. use OCP\Files\InvalidPathException;
  11. use OCP\Files\NotFoundException;
  12. use OCP\Files\NotPermittedException;
  13. use OCP\Files\SimpleFS\ISimpleFile;
  14. use OCP\Files\SimpleFS\ISimpleFolder;
  15. use OCP\IConfig;
  16. use OCP\IImage;
  17. use OCP\IPreview;
  18. use OCP\IStreamImage;
  19. use OCP\Preview\BeforePreviewFetchedEvent;
  20. use OCP\Preview\IProviderV2;
  21. use OCP\Preview\IVersionedPreviewFile;
  22. class Generator {
  23. public const SEMAPHORE_ID_ALL = 0x0a11;
  24. public const SEMAPHORE_ID_NEW = 0x07ea;
  25. /** @var IPreview */
  26. private $previewManager;
  27. /** @var IConfig */
  28. private $config;
  29. /** @var IAppData */
  30. private $appData;
  31. /** @var GeneratorHelper */
  32. private $helper;
  33. /** @var IEventDispatcher */
  34. private $eventDispatcher;
  35. public function __construct(
  36. IConfig $config,
  37. IPreview $previewManager,
  38. IAppData $appData,
  39. GeneratorHelper $helper,
  40. IEventDispatcher $eventDispatcher,
  41. ) {
  42. $this->config = $config;
  43. $this->previewManager = $previewManager;
  44. $this->appData = $appData;
  45. $this->helper = $helper;
  46. $this->eventDispatcher = $eventDispatcher;
  47. }
  48. /**
  49. * Returns a preview of a file
  50. *
  51. * The cache is searched first and if nothing usable was found then a preview is
  52. * generated by one of the providers
  53. *
  54. * @param File $file
  55. * @param int $width
  56. * @param int $height
  57. * @param bool $crop
  58. * @param string $mode
  59. * @param string|null $mimeType
  60. * @return ISimpleFile
  61. * @throws NotFoundException
  62. * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
  63. */
  64. public function getPreview(File $file, $width = -1, $height = -1, $crop = false, $mode = IPreview::MODE_FILL, $mimeType = null) {
  65. $specification = [
  66. 'width' => $width,
  67. 'height' => $height,
  68. 'crop' => $crop,
  69. 'mode' => $mode,
  70. ];
  71. $this->eventDispatcher->dispatchTyped(new BeforePreviewFetchedEvent(
  72. $file,
  73. $width,
  74. $height,
  75. $crop,
  76. $mode,
  77. $mimeType,
  78. ));
  79. // since we only ask for one preview, and the generate method return the last one it created, it returns the one we want
  80. return $this->generatePreviews($file, [$specification], $mimeType);
  81. }
  82. /**
  83. * Generates previews of a file
  84. *
  85. * @param File $file
  86. * @param non-empty-array $specifications
  87. * @param string $mimeType
  88. * @return ISimpleFile the last preview that was generated
  89. * @throws NotFoundException
  90. * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
  91. */
  92. public function generatePreviews(File $file, array $specifications, $mimeType = null) {
  93. //Make sure that we can read the file
  94. if (!$file->isReadable()) {
  95. throw new NotFoundException('Cannot read file');
  96. }
  97. if ($mimeType === null) {
  98. $mimeType = $file->getMimeType();
  99. }
  100. $previewFolder = $this->getPreviewFolder($file);
  101. // List every existing preview first instead of trying to find them one by one
  102. $previewFiles = $previewFolder->getDirectoryListing();
  103. $previewVersion = '';
  104. if ($file instanceof IVersionedPreviewFile) {
  105. $previewVersion = $file->getPreviewVersion() . '-';
  106. }
  107. // Get the max preview and infer the max preview sizes from that
  108. $maxPreview = $this->getMaxPreview($previewFolder, $previewFiles, $file, $mimeType, $previewVersion);
  109. $maxPreviewImage = null; // only load the image when we need it
  110. if ($maxPreview->getSize() === 0) {
  111. $maxPreview->delete();
  112. throw new NotFoundException('Max preview size 0, invalid!');
  113. }
  114. [$maxWidth, $maxHeight] = $this->getPreviewSize($maxPreview, $previewVersion);
  115. if ($maxWidth <= 0 || $maxHeight <= 0) {
  116. throw new NotFoundException('The maximum preview sizes are zero or less pixels');
  117. }
  118. $preview = null;
  119. foreach ($specifications as $specification) {
  120. $width = $specification['width'] ?? -1;
  121. $height = $specification['height'] ?? -1;
  122. $crop = $specification['crop'] ?? false;
  123. $mode = $specification['mode'] ?? IPreview::MODE_FILL;
  124. // If both width and height are -1 we just want the max preview
  125. if ($width === -1 && $height === -1) {
  126. $width = $maxWidth;
  127. $height = $maxHeight;
  128. }
  129. // Calculate the preview size
  130. [$width, $height] = $this->calculateSize($width, $height, $crop, $mode, $maxWidth, $maxHeight);
  131. // No need to generate a preview that is just the max preview
  132. if ($width === $maxWidth && $height === $maxHeight) {
  133. // ensure correct return value if this was the last one
  134. $preview = $maxPreview;
  135. continue;
  136. }
  137. // Try to get a cached preview. Else generate (and store) one
  138. try {
  139. try {
  140. $preview = $this->getCachedPreview($previewFiles, $width, $height, $crop, $maxPreview->getMimeType(), $previewVersion);
  141. } catch (NotFoundException $e) {
  142. if (!$this->previewManager->isMimeSupported($mimeType)) {
  143. throw new NotFoundException();
  144. }
  145. if ($maxPreviewImage === null) {
  146. $maxPreviewImage = $this->helper->getImage($maxPreview);
  147. }
  148. $preview = $this->generatePreview($previewFolder, $maxPreviewImage, $width, $height, $crop, $maxWidth, $maxHeight, $previewVersion);
  149. // New file, augment our array
  150. $previewFiles[] = $preview;
  151. }
  152. } catch (\InvalidArgumentException $e) {
  153. throw new NotFoundException('', 0, $e);
  154. }
  155. if ($preview->getSize() === 0) {
  156. $preview->delete();
  157. throw new NotFoundException('Cached preview size 0, invalid!');
  158. }
  159. }
  160. assert($preview !== null);
  161. // Free memory being used by the embedded image resource. Without this the image is kept in memory indefinitely.
  162. // Garbage Collection does NOT free this memory. We have to do it ourselves.
  163. if ($maxPreviewImage instanceof \OCP\Image) {
  164. $maxPreviewImage->destroy();
  165. }
  166. return $preview;
  167. }
  168. /**
  169. * Acquire a semaphore of the specified id and concurrency, blocking if necessary.
  170. * Return an identifier of the semaphore on success, which can be used to release it via
  171. * {@see Generator::unguardWithSemaphore()}.
  172. *
  173. * @param int $semId
  174. * @param int $concurrency
  175. * @return false|\SysvSemaphore the semaphore on success or false on failure
  176. */
  177. public static function guardWithSemaphore(int $semId, int $concurrency) {
  178. if (!extension_loaded('sysvsem')) {
  179. return false;
  180. }
  181. $sem = sem_get($semId, $concurrency);
  182. if ($sem === false) {
  183. return false;
  184. }
  185. if (!sem_acquire($sem)) {
  186. return false;
  187. }
  188. return $sem;
  189. }
  190. /**
  191. * Releases the semaphore acquired from {@see Generator::guardWithSemaphore()}.
  192. *
  193. * @param false|\SysvSemaphore $semId the semaphore identifier returned by guardWithSemaphore
  194. * @return bool
  195. */
  196. public static function unguardWithSemaphore(false|\SysvSemaphore $semId): bool {
  197. if ($semId === false || !($semId instanceof \SysvSemaphore)) {
  198. return false;
  199. }
  200. return sem_release($semId);
  201. }
  202. /**
  203. * Get the number of concurrent threads supported by the host.
  204. *
  205. * @return int number of concurrent threads, or 0 if it cannot be determined
  206. */
  207. public static function getHardwareConcurrency(): int {
  208. static $width;
  209. if (!isset($width)) {
  210. if (function_exists('ini_get')) {
  211. $openBasedir = ini_get('open_basedir');
  212. if (empty($openBasedir) || strpos($openBasedir, '/proc/cpuinfo') !== false) {
  213. $width = is_readable('/proc/cpuinfo') ? substr_count(file_get_contents('/proc/cpuinfo'), 'processor') : 0;
  214. } else {
  215. $width = 0;
  216. }
  217. } else {
  218. $width = 0;
  219. }
  220. }
  221. return $width;
  222. }
  223. /**
  224. * Get number of concurrent preview generations from system config
  225. *
  226. * Two config entries, `preview_concurrency_new` and `preview_concurrency_all`,
  227. * are available. If not set, the default values are determined with the hardware concurrency
  228. * of the host. In case the hardware concurrency cannot be determined, or the user sets an
  229. * invalid value, fallback values are:
  230. * For new images whose previews do not exist and need to be generated, 4;
  231. * For all preview generation requests, 8.
  232. * Value of `preview_concurrency_all` should be greater than or equal to that of
  233. * `preview_concurrency_new`, otherwise, the latter is returned.
  234. *
  235. * @param string $type either `preview_concurrency_new` or `preview_concurrency_all`
  236. * @return int number of concurrent preview generations, or -1 if $type is invalid
  237. */
  238. public function getNumConcurrentPreviews(string $type): int {
  239. static $cached = [];
  240. if (array_key_exists($type, $cached)) {
  241. return $cached[$type];
  242. }
  243. $hardwareConcurrency = self::getHardwareConcurrency();
  244. switch ($type) {
  245. case 'preview_concurrency_all':
  246. $fallback = $hardwareConcurrency > 0 ? $hardwareConcurrency * 2 : 8;
  247. $concurrency_all = $this->config->getSystemValueInt($type, $fallback);
  248. $concurrency_new = $this->getNumConcurrentPreviews('preview_concurrency_new');
  249. $cached[$type] = max($concurrency_all, $concurrency_new);
  250. break;
  251. case 'preview_concurrency_new':
  252. $fallback = $hardwareConcurrency > 0 ? $hardwareConcurrency : 4;
  253. $cached[$type] = $this->config->getSystemValueInt($type, $fallback);
  254. break;
  255. default:
  256. return -1;
  257. }
  258. return $cached[$type];
  259. }
  260. /**
  261. * @param ISimpleFolder $previewFolder
  262. * @param ISimpleFile[] $previewFiles
  263. * @param File $file
  264. * @param string $mimeType
  265. * @param string $prefix
  266. * @return ISimpleFile
  267. * @throws NotFoundException
  268. */
  269. private function getMaxPreview(ISimpleFolder $previewFolder, array $previewFiles, File $file, $mimeType, $prefix) {
  270. // We don't know the max preview size, so we can't use getCachedPreview.
  271. // It might have been generated with a higher resolution than the current value.
  272. foreach ($previewFiles as $node) {
  273. $name = $node->getName();
  274. if (($prefix === '' || str_starts_with($name, $prefix)) && strpos($name, 'max')) {
  275. return $node;
  276. }
  277. }
  278. $maxWidth = $this->config->getSystemValueInt('preview_max_x', 4096);
  279. $maxHeight = $this->config->getSystemValueInt('preview_max_y', 4096);
  280. return $this->generateProviderPreview($previewFolder, $file, $maxWidth, $maxHeight, false, true, $mimeType, $prefix);
  281. }
  282. private function generateProviderPreview(ISimpleFolder $previewFolder, File $file, int $width, int $height, bool $crop, bool $max, string $mimeType, string $prefix) {
  283. $previewProviders = $this->previewManager->getProviders();
  284. foreach ($previewProviders as $supportedMimeType => $providers) {
  285. // Filter out providers that does not support this mime
  286. if (!preg_match($supportedMimeType, $mimeType)) {
  287. continue;
  288. }
  289. foreach ($providers as $providerClosure) {
  290. $provider = $this->helper->getProvider($providerClosure);
  291. if (!($provider instanceof IProviderV2)) {
  292. continue;
  293. }
  294. if (!$provider->isAvailable($file)) {
  295. continue;
  296. }
  297. $previewConcurrency = $this->getNumConcurrentPreviews('preview_concurrency_new');
  298. $sem = self::guardWithSemaphore(self::SEMAPHORE_ID_NEW, $previewConcurrency);
  299. try {
  300. $preview = $this->helper->getThumbnail($provider, $file, $width, $height);
  301. } finally {
  302. self::unguardWithSemaphore($sem);
  303. }
  304. if (!($preview instanceof IImage)) {
  305. continue;
  306. }
  307. $path = $this->generatePath($preview->width(), $preview->height(), $crop, $max, $preview->dataMimeType(), $prefix);
  308. try {
  309. $file = $previewFolder->newFile($path);
  310. if ($preview instanceof IStreamImage) {
  311. $file->putContent($preview->resource());
  312. } else {
  313. $file->putContent($preview->data());
  314. }
  315. } catch (NotPermittedException $e) {
  316. throw new NotFoundException();
  317. }
  318. return $file;
  319. }
  320. }
  321. throw new NotFoundException('No provider successfully handled the preview generation');
  322. }
  323. /**
  324. * @param ISimpleFile $file
  325. * @param string $prefix
  326. * @return int[]
  327. */
  328. private function getPreviewSize(ISimpleFile $file, string $prefix = '') {
  329. $size = explode('-', substr($file->getName(), strlen($prefix)));
  330. return [(int)$size[0], (int)$size[1]];
  331. }
  332. /**
  333. * @param int $width
  334. * @param int $height
  335. * @param bool $crop
  336. * @param bool $max
  337. * @param string $mimeType
  338. * @param string $prefix
  339. * @return string
  340. */
  341. private function generatePath($width, $height, $crop, $max, $mimeType, $prefix) {
  342. $path = $prefix . (string)$width . '-' . (string)$height;
  343. if ($crop) {
  344. $path .= '-crop';
  345. }
  346. if ($max) {
  347. $path .= '-max';
  348. }
  349. $ext = $this->getExtension($mimeType);
  350. $path .= '.' . $ext;
  351. return $path;
  352. }
  353. /**
  354. * @param int $width
  355. * @param int $height
  356. * @param bool $crop
  357. * @param string $mode
  358. * @param int $maxWidth
  359. * @param int $maxHeight
  360. * @return int[]
  361. */
  362. private function calculateSize($width, $height, $crop, $mode, $maxWidth, $maxHeight) {
  363. /*
  364. * If we are not cropping we have to make sure the requested image
  365. * respects the aspect ratio of the original.
  366. */
  367. if (!$crop) {
  368. $ratio = $maxHeight / $maxWidth;
  369. if ($width === -1) {
  370. $width = $height / $ratio;
  371. }
  372. if ($height === -1) {
  373. $height = $width * $ratio;
  374. }
  375. $ratioH = $height / $maxHeight;
  376. $ratioW = $width / $maxWidth;
  377. /*
  378. * Fill means that the $height and $width are the max
  379. * Cover means min.
  380. */
  381. if ($mode === IPreview::MODE_FILL) {
  382. if ($ratioH > $ratioW) {
  383. $height = $width * $ratio;
  384. } else {
  385. $width = $height / $ratio;
  386. }
  387. } elseif ($mode === IPreview::MODE_COVER) {
  388. if ($ratioH > $ratioW) {
  389. $width = $height / $ratio;
  390. } else {
  391. $height = $width * $ratio;
  392. }
  393. }
  394. }
  395. if ($height !== $maxHeight && $width !== $maxWidth) {
  396. /*
  397. * Scale to the nearest power of four
  398. */
  399. $pow4height = 4 ** ceil(log($height) / log(4));
  400. $pow4width = 4 ** ceil(log($width) / log(4));
  401. // Minimum size is 64
  402. $pow4height = max($pow4height, 64);
  403. $pow4width = max($pow4width, 64);
  404. $ratioH = $height / $pow4height;
  405. $ratioW = $width / $pow4width;
  406. if ($ratioH < $ratioW) {
  407. $width = $pow4width;
  408. $height /= $ratioW;
  409. } else {
  410. $height = $pow4height;
  411. $width /= $ratioH;
  412. }
  413. }
  414. /*
  415. * Make sure the requested height and width fall within the max
  416. * of the preview.
  417. */
  418. if ($height > $maxHeight) {
  419. $ratio = $height / $maxHeight;
  420. $height = $maxHeight;
  421. $width /= $ratio;
  422. }
  423. if ($width > $maxWidth) {
  424. $ratio = $width / $maxWidth;
  425. $width = $maxWidth;
  426. $height /= $ratio;
  427. }
  428. return [(int)round($width), (int)round($height)];
  429. }
  430. /**
  431. * @param ISimpleFolder $previewFolder
  432. * @param ISimpleFile $maxPreview
  433. * @param int $width
  434. * @param int $height
  435. * @param bool $crop
  436. * @param int $maxWidth
  437. * @param int $maxHeight
  438. * @param string $prefix
  439. * @return ISimpleFile
  440. * @throws NotFoundException
  441. * @throws \InvalidArgumentException if the preview would be invalid (in case the original image is invalid)
  442. */
  443. private function generatePreview(ISimpleFolder $previewFolder, IImage $maxPreview, $width, $height, $crop, $maxWidth, $maxHeight, $prefix) {
  444. $preview = $maxPreview;
  445. if (!$preview->valid()) {
  446. throw new \InvalidArgumentException('Failed to generate preview, failed to load image');
  447. }
  448. $previewConcurrency = $this->getNumConcurrentPreviews('preview_concurrency_new');
  449. $sem = self::guardWithSemaphore(self::SEMAPHORE_ID_NEW, $previewConcurrency);
  450. try {
  451. if ($crop) {
  452. if ($height !== $preview->height() && $width !== $preview->width()) {
  453. //Resize
  454. $widthR = $preview->width() / $width;
  455. $heightR = $preview->height() / $height;
  456. if ($widthR > $heightR) {
  457. $scaleH = $height;
  458. $scaleW = $maxWidth / $heightR;
  459. } else {
  460. $scaleH = $maxHeight / $widthR;
  461. $scaleW = $width;
  462. }
  463. $preview = $preview->preciseResizeCopy((int)round($scaleW), (int)round($scaleH));
  464. }
  465. $cropX = (int)floor(abs($width - $preview->width()) * 0.5);
  466. $cropY = (int)floor(abs($height - $preview->height()) * 0.5);
  467. $preview = $preview->cropCopy($cropX, $cropY, $width, $height);
  468. } else {
  469. $preview = $maxPreview->resizeCopy(max($width, $height));
  470. }
  471. } finally {
  472. self::unguardWithSemaphore($sem);
  473. }
  474. $path = $this->generatePath($width, $height, $crop, false, $preview->dataMimeType(), $prefix);
  475. try {
  476. $file = $previewFolder->newFile($path);
  477. $file->putContent($preview->data());
  478. } catch (NotPermittedException $e) {
  479. throw new NotFoundException();
  480. }
  481. return $file;
  482. }
  483. /**
  484. * @param ISimpleFile[] $files Array of FileInfo, as the result of getDirectoryListing()
  485. * @param int $width
  486. * @param int $height
  487. * @param bool $crop
  488. * @param string $mimeType
  489. * @param string $prefix
  490. * @return ISimpleFile
  491. *
  492. * @throws NotFoundException
  493. */
  494. private function getCachedPreview($files, $width, $height, $crop, $mimeType, $prefix) {
  495. $path = $this->generatePath($width, $height, $crop, false, $mimeType, $prefix);
  496. foreach ($files as $file) {
  497. if ($file->getName() === $path) {
  498. return $file;
  499. }
  500. }
  501. throw new NotFoundException();
  502. }
  503. /**
  504. * Get the specific preview folder for this file
  505. *
  506. * @param File $file
  507. * @return ISimpleFolder
  508. *
  509. * @throws InvalidPathException
  510. * @throws NotFoundException
  511. * @throws NotPermittedException
  512. */
  513. private function getPreviewFolder(File $file) {
  514. // Obtain file id outside of try catch block to prevent the creation of an existing folder
  515. $fileId = (string)$file->getId();
  516. try {
  517. $folder = $this->appData->getFolder($fileId);
  518. } catch (NotFoundException $e) {
  519. $folder = $this->appData->newFolder($fileId);
  520. }
  521. return $folder;
  522. }
  523. /**
  524. * @param string $mimeType
  525. * @return null|string
  526. * @throws \InvalidArgumentException
  527. */
  528. private function getExtension($mimeType) {
  529. switch ($mimeType) {
  530. case 'image/png':
  531. return 'png';
  532. case 'image/jpeg':
  533. return 'jpg';
  534. case 'image/webp':
  535. return 'webp';
  536. case 'image/gif':
  537. return 'gif';
  538. default:
  539. throw new \InvalidArgumentException('Not a valid mimetype: "' . $mimeType . '"');
  540. }
  541. }
  542. }