1
0

bmpload.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  1. // BMP loader
  2. //
  3. // See: https://en.wikipedia.org/wiki/BMP_file_format
  4. #include "vips.h"
  5. #include <stdlib.h>
  6. #include <stdint.h>
  7. #include <stdbool.h>
  8. #define BMP_ROW_ADDR(BMP, OR, R, Y) \
  9. VIPS_REGION_ADDR(OR, 0, R->top + (BMP->top_down ? Y : R->height - 1 - Y))
  10. /**
  11. * BMP ForeignLoad VIPS class implementation (generic)
  12. */
  13. typedef struct _VipsForeignLoadBmp {
  14. VipsForeignLoad parent_object;
  15. VipsSource *source;
  16. int32_t width;
  17. int32_t height;
  18. uint16_t planes;
  19. uint16_t bpp;
  20. uint16_t compression;
  21. uint16_t offset;
  22. uint32_t rmask;
  23. uint32_t gmask;
  24. uint32_t bmask;
  25. uint32_t amask;
  26. uint32_t num_colors;
  27. int bands; // target image bands
  28. int bytes_per_pixel; // source image bytes per pixel (not used when bpp<8)
  29. bool top_down; // true if image is vertically reversed
  30. bool rle; // true if image is compressed with RLE
  31. bool bmp565; // 16-bit
  32. uint32_t *palette; // palette for 1, 2, 4 or 8 bits per pixel BMP palette
  33. int y_pos; // current position in the image, used when sequential access is possible
  34. int dy; // in RLE mode this indicates how many lines to skip
  35. int dx; // in RLE mode this indicates start pixel X
  36. VipsPel *row_buffer; // buffer for the current row, long enough to hold the whole 32-bit row+padding
  37. } VipsForeignLoadBmp;
  38. typedef VipsForeignLoadClass VipsForeignLoadBmpClass;
  39. G_DEFINE_ABSTRACT_TYPE(VipsForeignLoadBmp, vips_foreign_load_bmp,
  40. VIPS_TYPE_FOREIGN_LOAD);
  41. static void
  42. vips_foreign_load_bmp_dispose(GObject *gobject)
  43. {
  44. VipsForeignLoadBmp *bmp = (VipsForeignLoadBmp *) gobject;
  45. VIPS_UNREF(bmp->source);
  46. G_OBJECT_CLASS(vips_foreign_load_bmp_parent_class)->dispose(gobject);
  47. }
  48. static int
  49. vips_foreign_load_bmp_build(VipsObject *object)
  50. {
  51. VipsForeignLoadBmp *bmp = (VipsForeignLoadBmp *) object;
  52. return VIPS_OBJECT_CLASS(vips_foreign_load_bmp_parent_class)
  53. ->build(object);
  54. }
  55. static VipsForeignFlags
  56. vips_foreign_load_bmp_get_flags(VipsForeignLoad *load)
  57. {
  58. return VIPS_FOREIGN_SEQUENTIAL;
  59. }
  60. /**
  61. * Sets the image header for the output image
  62. */
  63. static int
  64. vips_foreign_load_bmp_set_image_header(VipsForeignLoadBmp *bmp, VipsImage *out)
  65. {
  66. vips_image_init_fields(
  67. out,
  68. bmp->width,
  69. bmp->height,
  70. bmp->bands,
  71. VIPS_FORMAT_UCHAR,
  72. VIPS_CODING_NONE,
  73. VIPS_INTERPRETATION_sRGB,
  74. 1.0,
  75. 1.0);
  76. if (bmp->palette != NULL) {
  77. int bd;
  78. if (bmp->num_colors > 16) {
  79. bd = 8; // 8-bit palette
  80. }
  81. else if (bmp->num_colors > 4) {
  82. bd = 4; // 4-bit palette
  83. }
  84. else if (bmp->num_colors > 2) {
  85. bd = 2; // 2-bit palette
  86. }
  87. else {
  88. bd = 1; // 1-bit palette
  89. }
  90. vips_image_set_int(out, "palette-bit-depth", bd);
  91. #ifdef VIPS_META_BITS_PER_SAMPLE
  92. vips_image_set_int(out, VIPS_META_BITS_PER_SAMPLE, bd);
  93. #endif
  94. #ifdef VIPS_META_PALETTE
  95. vips_image_set_int(out, VIPS_META_PALETTE, TRUE);
  96. #endif
  97. }
  98. if (vips_image_pipelinev(out, VIPS_DEMAND_STYLE_THINSTRIP, NULL))
  99. return -1;
  100. return 0;
  101. }
  102. /**
  103. * Checks if the source is a BMP image
  104. */
  105. static gboolean
  106. vips_foreign_load_bmp_source_is_a_source(VipsSource *source)
  107. {
  108. unsigned char *bbuf = vips_source_sniff(source, 2);
  109. if (!bbuf) {
  110. vips_error("vips_foreign_load_bmp_source_is_a_source", "unable to sniff source");
  111. return 0;
  112. }
  113. return bbuf[0] == 'B' &&
  114. bbuf[1] == 'M';
  115. }
  116. /**
  117. * Loads the header of the BMP image from the source.
  118. */
  119. static int
  120. vips_foreign_load_bmp_header(VipsForeignLoad *load)
  121. {
  122. VipsForeignLoadBmp *bmp = (VipsForeignLoadBmp *) load;
  123. // Rewind the source to the beginning
  124. if (vips_source_rewind(bmp->source))
  125. return -1;
  126. VipsPel file_header_buf[BMP_FILE_HEADER_LEN + 4];
  127. // Read the header + the next uint32 after
  128. if (vips_foreign_load_read_full(bmp->source, &file_header_buf, BMP_FILE_HEADER_LEN + 4) <= 0) {
  129. vips_error("vips_foreign_load_bmp_header", "unable to read file header from the source");
  130. return -1;
  131. }
  132. // Check if the info header length is valid
  133. uint32_t offset = GUINT32_FROM_LE(*(uint32_t *) (file_header_buf + 10));
  134. uint32_t info_header_len = GUINT32_FROM_LE(*(uint32_t *) (file_header_buf + 14));
  135. if (
  136. (info_header_len != BMP_BITMAP_INFO_HEADER_LEN) &&
  137. (info_header_len != BMP_V4_INFO_HEADER_LEN) &&
  138. (info_header_len != BMP_V5_INFO_HEADER_LEN)) {
  139. vips_error("vips_foreign_load_bmp_header", "incorrect BMP header length");
  140. return -1;
  141. }
  142. // Now, read the info header. -4 bytes is because we've already read the first 4 bytes of
  143. // the header (info_header_len) at the previous step. Constants include those 4 bytes.
  144. VipsPel *info_header = VIPS_ARRAY(load, info_header_len - 4, VipsPel);
  145. if (vips_foreign_load_read_full(bmp->source, info_header, info_header_len - 4) <= 0) {
  146. vips_error("vips_foreign_load_bmp_header", "unable to read BMP info header");
  147. return -1;
  148. }
  149. int32_t width = GINT32_FROM_LE(*(int32_t *) (info_header));
  150. int32_t height = GINT32_FROM_LE(*(int32_t *) (info_header + 4));
  151. uint16_t planes = GUINT16_FROM_LE(*(uint16_t *) (info_header + 8));
  152. uint16_t bpp = GUINT16_FROM_LE(*(uint16_t *) (info_header + 10));
  153. uint32_t compression = GUINT32_FROM_LE(*(uint32_t *) (info_header + 12));
  154. uint32_t num_colors = GUINT32_FROM_LE(*(uint32_t *) (info_header + 28));
  155. bool top_down = FALSE;
  156. bool rle = FALSE;
  157. bool bmp565 = FALSE;
  158. uint32_t rmask = 0;
  159. uint32_t gmask = 0;
  160. uint32_t bmask = 0;
  161. uint32_t amask = 0;
  162. int bands = 3; // 3 bands by default (RGB)
  163. // Let's determine if the image has an alpha channel
  164. bool has_alpha = bpp == 32;
  165. // If the info header is V4 or V5, check for alpha channel mask explicitly.
  166. // If it's non-zero, then the target image should have an alpha channel.
  167. if ((has_alpha) && (info_header_len > BMP_BITMAP_INFO_HEADER_LEN)) {
  168. has_alpha = GUINT32_FROM_LE(*(uint32_t *) (info_header + 48)) != 0;
  169. }
  170. // Target image should have alpha channel only in case source image has alpha channel
  171. // AND source image alpha mask is not zero
  172. if (has_alpha) {
  173. bands = 4;
  174. }
  175. // Source image bytes per pixel. It does not depend on the alpha mask, just on the bpp.
  176. int bytes_per_pixel = bpp >= 8 ? bpp / 8 : 1; // bytes per pixel in the source image
  177. if (height < 0) {
  178. height = -height;
  179. top_down = TRUE;
  180. }
  181. if ((width <= 0) || (height <= 0)) {
  182. vips_error("vips_foreign_load_bmp_header", "unsupported BMP image dimensions");
  183. return -1;
  184. }
  185. // we only support 1 plane and 8, 24 or 32 bits per pixel
  186. if (planes != 1) {
  187. vips_error("vips_foreign_load_bmp_header", "unsupported BMP image: planes != 1");
  188. return -1;
  189. }
  190. if (compression == COMPRESSION_BI_RGB) {
  191. // go ahead: no compression
  192. }
  193. else if (
  194. ((compression == COMPRESSION_BI_RLE8) && (bpp == 8)) ||
  195. ((compression == COMPRESSION_BI_RLE4) && (bpp == 4))) {
  196. // rle compression is used for 8-bit or 4-bit images
  197. rle = TRUE;
  198. }
  199. else if (
  200. (compression == COMPRESSION_BI_BITFIELDS) ||
  201. (compression == COMPRESSION_BI_BITFIELDS_ALPHA)) {
  202. int color_mask_len = 3;
  203. if (bpp > 24) {
  204. color_mask_len = 4;
  205. }
  206. uint32_t color_mask_buf[4];
  207. uint32_t *color_mask;
  208. // for the non-v4/v5 bmp image we need to load color mask separately since
  209. // it is not included in the header
  210. if (info_header_len == BMP_BITMAP_INFO_HEADER_LEN) {
  211. // let's attach it to load itself so we won't care about conditionally freeing it
  212. if (vips_foreign_load_read_full(bmp->source, color_mask_buf, color_mask_len * sizeof(uint32_t)) <= 0) {
  213. vips_error("vips_foreign_load_bmp_header", "unable to read BMP color mask");
  214. return -1;
  215. }
  216. color_mask = color_mask_buf;
  217. }
  218. else {
  219. // In case of v4/v5 info header, the color mask is already included in the info header,
  220. // we just need to read it
  221. color_mask = (uint32_t *) ((VipsPel *) info_header + 36);
  222. }
  223. // Standard says that color masks are in BE order. However, we do all the
  224. // checks and calculations as like as masks were in LE order.
  225. rmask = GUINT32_FROM_LE(color_mask[0]);
  226. gmask = GUINT32_FROM_LE(color_mask[1]);
  227. bmask = GUINT32_FROM_LE(color_mask[2]);
  228. amask = 0; // default alpha mask is 0
  229. if (color_mask_len > 3) {
  230. amask = GUINT32_FROM_LE(color_mask[3]);
  231. }
  232. if ((bpp == 16) && (rmask = 0xF800) && (gmask == 0x7E0) && (bmask == 0x1F)) {
  233. bmp565 = TRUE;
  234. }
  235. else if ((bpp == 16) && (rmask == 0x7C00) && (gmask == 0x3E0) && (bmask == 0x1F)) {
  236. // Go ahead, it's a regular 16 bit image
  237. }
  238. else if ((bpp == 32) && (rmask == 0xff0000) && (gmask == 0xff00) && (bmask == 0xff) && (amask == 0xff000000)) {
  239. // Go ahead, it's a regular 32-bit image
  240. }
  241. else {
  242. vips_error("vips_foreign_load_bmp_header", "unsupported BMP image: unsupported color masks");
  243. return -1;
  244. }
  245. }
  246. else {
  247. vips_error("vips_foreign_load_bmp_header", "unsupported BMP image: compression not supported");
  248. return -1;
  249. }
  250. // BMP images with 1, 2, 4 or 8 bits per pixel
  251. if (bpp <= 8) {
  252. // They could not have num_colors == 0, this is a bug in the BMP file.
  253. if (num_colors == 0) {
  254. num_colors = 1 << bpp;
  255. }
  256. // Please note, that BMP images are stored in BGR order rather than RGB order.
  257. // Every 4th byte is padding.
  258. bmp->palette = VIPS_MALLOC(load, num_colors * BMP_PALETTE_ITEM_SIZE);
  259. if (vips_foreign_load_read_full(bmp->source, bmp->palette, num_colors * BMP_PALETTE_ITEM_SIZE) <= 0) {
  260. vips_error("vips_foreign_load_bmp_header", "unable to read BMP palette");
  261. return -1;
  262. }
  263. }
  264. bmp->width = width;
  265. bmp->height = height;
  266. bmp->planes = planes;
  267. bmp->bpp = bpp;
  268. bmp->compression = compression;
  269. bmp->offset = offset;
  270. bmp->top_down = top_down;
  271. bmp->rle = rle;
  272. bmp->bmp565 = bmp565;
  273. bmp->num_colors = num_colors;
  274. bmp->bands = bands;
  275. bmp->rmask = rmask;
  276. bmp->gmask = gmask;
  277. bmp->bmask = bmask;
  278. bmp->amask = amask;
  279. bmp->bytes_per_pixel = bytes_per_pixel;
  280. bmp->y_pos = 0;
  281. bmp->dx = 0; // In sequential access this indicates that we need to skip n lines
  282. bmp->dy = 0; // n pixels
  283. // set the image header of the out image
  284. if (vips_foreign_load_bmp_set_image_header(bmp, load->out)) {
  285. return -1;
  286. }
  287. // seek to the beginning of image data
  288. if (vips_source_seek(bmp->source, offset, SEEK_SET) < 0) {
  289. vips_error("vips_foreign_load_bmp_header", "unable to seek to BMP image data");
  290. return -1;
  291. }
  292. vips_source_minimise(bmp->source);
  293. return 0;
  294. }
  295. /**
  296. * Generates a strip for 24/32 bpp BMP image.
  297. */
  298. static int
  299. vips_foreign_load_bmp_24_32_generate_strip(VipsRect *r, VipsRegion *out_region, VipsForeignLoadBmp *bmp)
  300. {
  301. // Align the row size to 4 bytes, as BMP rows are 4-byte aligned.
  302. int row_size = (bmp->bytes_per_pixel * r->width + 3) & (~3);
  303. VipsPel *src;
  304. VipsPel *dest;
  305. for (int y = 0; y < r->height; y++) {
  306. src = bmp->row_buffer;
  307. dest = BMP_ROW_ADDR(bmp, out_region, r, y);
  308. if (vips_foreign_load_read_full(bmp->source, src, row_size) <= 0) {
  309. vips_error("vips_foreign_load_bmp_24_32_generate_strip", "failed to read raw data");
  310. return -1;
  311. }
  312. for (int x = 0; x < r->width; x++) {
  313. dest[0] = src[2]; // B
  314. dest[1] = src[1]; // G
  315. dest[2] = src[0]; // R
  316. // if the image has alpha channel, copy it too
  317. if (bmp->bands == 4) {
  318. dest[3] = src[3]; // A
  319. }
  320. dest += bmp->bands;
  321. src += bmp->bytes_per_pixel;
  322. }
  323. bmp->y_pos += 1;
  324. }
  325. return 0;
  326. }
  327. /**
  328. * Generates a strip for 16 bpp BMP image.
  329. */
  330. static int
  331. vips_foreign_load_bmp_16_generate_strip(VipsRect *r, VipsRegion *out_region, VipsForeignLoadBmp *bmp)
  332. {
  333. // Align the row size to 4 bytes, as BMP rows are 4-byte aligned, 16 bpp = 2 bytes per pixel
  334. int row_size = (bmp->bytes_per_pixel * r->width + 3) & (~3);
  335. VipsPel *src;
  336. VipsPel *dest;
  337. for (int y = 0; y < r->height; y++) {
  338. src = bmp->row_buffer;
  339. dest = BMP_ROW_ADDR(bmp, out_region, r, y);
  340. if (vips_foreign_load_read_full(bmp->source, src, row_size) <= 0) {
  341. vips_error("vips_foreign_load_bmp_16_generate_strip", "failed to read raw data");
  342. return -1;
  343. }
  344. for (int x = 0; x < r->width; x++) {
  345. uint16_t pixel = GUINT16_FROM_LE(*(uint16_t *) src);
  346. // 565 and non-565 formats both are handled here: they differ by the masks
  347. dest[0] = (uint8_t) ((pixel & bmp->rmask) >> 11) << 3;
  348. dest[1] = (uint8_t) ((pixel & bmp->gmask) >> 5) << 2;
  349. dest[2] = (uint8_t) (pixel & bmp->bmask) << 3;
  350. dest += bmp->bands;
  351. src += bmp->bytes_per_pixel; // 2 bytes per pixel for 16 bpp
  352. }
  353. bmp->y_pos += 1;
  354. }
  355. return 0;
  356. }
  357. /**
  358. * Writes pixels for 1/2/4/8 bpp BMP image using palette. Pixels are taken from the src (if present), or src_byte (RLE case).
  359. */
  360. void
  361. vips_foreign_load_bpp_1_8_write_pixels_palette(VipsForeignLoadBmp *bmp, VipsPel *dest, VipsPel *src, int width, VipsPel src_byte)
  362. {
  363. int bit = 8 - bmp->bpp;
  364. int src_offset = 0;
  365. for (int x = 0; x < width; x++) {
  366. // Read the palette index from the source
  367. int pixel;
  368. if (src != NULL) {
  369. pixel = (int) src[src_offset] >> bit;
  370. }
  371. else {
  372. pixel = src_byte >> bit;
  373. }
  374. int mask = (1 << bmp->bpp) - 1;
  375. int palette_index = pixel & mask;
  376. int dest_offset = x * bmp->bands;
  377. if (bit == 0) {
  378. bit = 8 - bmp->bpp;
  379. src_offset++;
  380. }
  381. else {
  382. bit -= bmp->bpp;
  383. }
  384. VipsPel *color = (VipsPel *) &bmp->palette[palette_index];
  385. dest[dest_offset + 0] = color[2]; // BGR, reversed
  386. dest[dest_offset + 1] = color[1];
  387. dest[dest_offset + 2] = color[0];
  388. }
  389. }
  390. /**
  391. * Generates a strip for 1/2/4/8 bpp BMP image.
  392. */
  393. static int
  394. vips_foreign_load_bmp_1_8_generate_strip(VipsRect *r, VipsRegion *out_region, VipsForeignLoadBmp *bmp)
  395. {
  396. // Align the row size to 4 bytes, as BMP rows are 4-byte aligned
  397. char cap = 8 / bmp->bpp;
  398. int row_size = ((r->width + cap - 1) / cap + 3) & (~3);
  399. VipsPel *src = bmp->row_buffer; // just a shortcut
  400. VipsPel *dest;
  401. for (int y = 0; y < r->height; y++) {
  402. if (vips_foreign_load_read_full(bmp->source, src, row_size) <= 0) {
  403. vips_error("vips_foreign_load_bmp_16_generate_strip", "failed to read raw data");
  404. return -1;
  405. }
  406. dest = BMP_ROW_ADDR(bmp, out_region, r, y);
  407. vips_foreign_load_bpp_1_8_write_pixels_palette(bmp, dest, src, r->width, -1);
  408. bmp->y_pos += 1;
  409. }
  410. return 0;
  411. }
  412. /**
  413. * Generates a strip for 1/2/4/8 bpp BMP image.
  414. *
  415. * BMP RLE is encoded per-line (so, each line has 0x00 00 - LE control byte at the end).
  416. */
  417. static int
  418. vips_foreign_load_bmp_rle_generate_strip(VipsRect *r, VipsRegion *out_region, VipsForeignLoadBmp *bmp)
  419. {
  420. // Align the row size to 4 bytes, as BMP rows are 4-byte aligned
  421. char cap = 8 / bmp->bpp;
  422. VipsPel *src = bmp->row_buffer; // just a shortcut
  423. VipsPel *dest;
  424. VipsPel cmd[2];
  425. VipsPel dxdy[2];
  426. for (int y = 0; y < r->height; y++) {
  427. dest = BMP_ROW_ADDR(bmp, out_region, r, y);
  428. // fill the line with zeros (move to skips)
  429. memset(dest, 0, r->width * bmp->bands);
  430. // Skip lines if needed, this might be the whole region
  431. if (bmp->dy > 0) {
  432. bmp->dy--;
  433. bmp->y_pos += 1;
  434. continue;
  435. }
  436. int x = 0;
  437. if (bmp->dx > 0) {
  438. x = bmp->dx;
  439. bmp->dx = 0;
  440. }
  441. do {
  442. // Read next command
  443. //
  444. // NOTE: This might not be very efficient, unless underlying vips buffer is memory-buffered
  445. if (vips_foreign_load_read_full(bmp->source, &cmd, 2) <= 0) {
  446. vips_error("vips_foreign_load_bmp_rle_generate_strip", "failed to read next RLE command");
  447. return -1;
  448. }
  449. // Check control byte
  450. if (cmd[0] == 0) {
  451. if (cmd[1] == BMP_RLE_EOL) {
  452. break;
  453. }
  454. else if (cmd[1] == BMP_RLE_EOF) {
  455. bmp->dy = G_MAXUINT32; // set dy to max, so all the leftover lines will be skipped
  456. bmp->dx = 0;
  457. break; // exit the loop, we reached EOF
  458. }
  459. else if (cmd[1] == BMP_RLE_MOVE_TO) {
  460. if (vips_foreign_load_read_full(bmp->source, &dxdy, 2) <= 0) {
  461. vips_error("vips_foreign_load_bmp_rle_generate_strip", "failed to read RLE move command");
  462. return -1;
  463. }
  464. int dx = dxdy[0]; // relative X offset
  465. int dy = dxdy[1]; // relative Y offset
  466. // We treat movement by Y as EOL
  467. if (dy > 0) {
  468. bmp->dx = MIN(x + dx, r->width); // New X position must not exceed the width of the image
  469. bmp->dy = dy; // We do not care if Y pos is outside of the impage, it's a separate check
  470. break; // we need to skip lines, so we exit the loop
  471. } // Movement by X might not lead to EOL, so we continue
  472. else {
  473. bmp->dy = dy; // 0
  474. x = MIN(x + dx, r->width); // Move to the desired pixel
  475. }
  476. }
  477. else { // Directly read next n bytes
  478. int pixels_count = cmd[1];
  479. int bytes_count = ((pixels_count + cap - 1) / cap + 1) & ~1;
  480. pixels_count = MIN(pixels_count, r->width - x);
  481. if (vips_foreign_load_read_full(bmp->source, src, bytes_count) <= 0) {
  482. vips_error("vips_foreign_load_bmp_rle_generate_strip", "failed to read RLE data");
  483. return -1;
  484. }
  485. vips_foreign_load_bpp_1_8_write_pixels_palette(bmp, dest + (x * bmp->bands), src, pixels_count, -1);
  486. x += pixels_count;
  487. }
  488. }
  489. else { // read RLE-encoded pixels
  490. VipsPel pixels_count = cmd[0];
  491. VipsPel pixel = cmd[1];
  492. pixels_count = MIN(pixels_count, r->width - x);
  493. vips_foreign_load_bpp_1_8_write_pixels_palette(bmp, dest + (x * bmp->bands), NULL, pixels_count, pixel);
  494. x += pixels_count;
  495. }
  496. } while (1);
  497. bmp->y_pos += 1; // Move to the next line
  498. }
  499. return 0;
  500. }
  501. /**
  502. * Loads a strip of non-rle bmp image, access must be sequential, demand
  503. * style must be thinstrip + strip height set to max.
  504. */
  505. static int
  506. vips_foreign_load_bmp_rgb_generate(VipsRegion *out_region,
  507. void *seq, void *a, void *b, gboolean *stop)
  508. {
  509. VipsForeignLoadBmp *bmp = (VipsForeignLoadBmp *) a;
  510. VipsRect *r = &out_region->valid;
  511. /**
  512. * Sanity checks which assure that the requested region has the correct shape.
  513. *
  514. * We use sequential access + thinstrip demand style which means that image would
  515. * be read in strips, where each strip represents image-wide set of rows.
  516. */
  517. g_assert(r->left == 0); // Strip starts at the left edge of the image
  518. g_assert(r->width == out_region->im->Xsize); // Has width of the image
  519. g_assert(VIPS_RECT_BOTTOM(r) <= out_region->im->Ysize); // Equals or less of image height
  520. // Equals to the maximum height of the strip or less (last strip)
  521. if (bmp->top_down)
  522. g_assert(r->height ==
  523. VIPS_MIN(VIPS__FATSTRIP_HEIGHT, out_region->im->Ysize - r->top));
  524. else
  525. g_assert(r->height == out_region->im->Ysize);
  526. // Check if the requested strip is in order
  527. if (r->top != bmp->y_pos) {
  528. vips_error("vips_foreign_load_bmp_generate", "out of order read at line %d", bmp->y_pos);
  529. return -1;
  530. }
  531. if (bmp->rle) {
  532. return vips_foreign_load_bmp_rle_generate_strip(r, out_region, bmp);
  533. }
  534. else if (bmp->bpp >= 24) {
  535. return vips_foreign_load_bmp_24_32_generate_strip(r, out_region, bmp);
  536. }
  537. else if (bmp->bpp == 16) {
  538. return vips_foreign_load_bmp_16_generate_strip(r, out_region, bmp);
  539. }
  540. return vips_foreign_load_bmp_1_8_generate_strip(r, out_region, bmp);
  541. }
  542. /**
  543. * Loads a BMP image from the source.
  544. */
  545. static int
  546. vips_foreign_load_bmp_load(VipsForeignLoad *load)
  547. {
  548. VipsForeignLoadBmp *bmp = (VipsForeignLoadBmp *) load;
  549. // For a case when we encounter buggy BMP image which has RLE command to read next
  550. // 255 bytes, and our buffer is smaller than that, we need it to be at least 255 bytes.
  551. int row_buffer_length = (bmp->width * 4) + 4;
  552. if (row_buffer_length < 255) {
  553. row_buffer_length = 255;
  554. }
  555. // Allocate a row buffer for the current row in all generate* functions.
  556. // 4 * width + 4 is guaranteed to be enough for the longest (32-bit per pixel) row + padding.
  557. bmp->row_buffer = VIPS_ARRAY(load, row_buffer_length, VipsPel);
  558. VipsImage **t = (VipsImage **)
  559. vips_object_local_array(VIPS_OBJECT(load), 2);
  560. t[0] = vips_image_new();
  561. if (
  562. vips_foreign_load_bmp_set_image_header(bmp, t[0]) ||
  563. vips_image_generate(t[0],
  564. NULL, vips_foreign_load_bmp_rgb_generate, NULL,
  565. bmp, NULL) ||
  566. // For bottom-up BMP images we need to flip the image vertically.
  567. // We do this in vips_image_generate callback, so we need to be sure that
  568. // we generate regions size of the whole image.
  569. vips_sequential(t[0], &t[1],
  570. "tile_height", bmp->top_down ? VIPS__FATSTRIP_HEIGHT : t[0]->Ysize,
  571. NULL) ||
  572. vips_image_write(t[1], load->real) ||
  573. vips_source_decode(bmp->source)) {
  574. return -1;
  575. }
  576. return 0;
  577. }
  578. static void
  579. vips_foreign_load_bmp_class_init(VipsForeignLoadBmpClass *class)
  580. {
  581. GObjectClass *gobject_class = G_OBJECT_CLASS(class);
  582. VipsObjectClass *object_class = (VipsObjectClass *) class;
  583. VipsForeignClass *foreign_class = (VipsForeignClass *) class;
  584. VipsForeignLoadClass *load_class = (VipsForeignLoadClass *) class;
  585. gobject_class->dispose = vips_foreign_load_bmp_dispose;
  586. gobject_class->set_property = vips_object_set_property;
  587. gobject_class->get_property = vips_object_get_property;
  588. object_class->nickname = "bmpload_base";
  589. object_class->description = "load bmp image (internal format for video thumbs)";
  590. object_class->build = vips_foreign_load_bmp_build;
  591. load_class->get_flags = vips_foreign_load_bmp_get_flags;
  592. load_class->header = vips_foreign_load_bmp_header;
  593. load_class->load = vips_foreign_load_bmp_load;
  594. }
  595. static void
  596. vips_foreign_load_bmp_init(VipsForeignLoadBmp *load)
  597. {
  598. load->palette = NULL;
  599. }
  600. typedef struct _VipsForeignLoadBmpSource {
  601. VipsForeignLoadBmp parent_object;
  602. VipsSource *source;
  603. } VipsForeignLoadBmpSource;
  604. typedef VipsForeignLoadBmpClass VipsForeignLoadBmpSourceClass;
  605. G_DEFINE_TYPE(VipsForeignLoadBmpSource, vips_foreign_load_bmp_source,
  606. vips_foreign_load_bmp_get_type());
  607. static int
  608. vips_foreign_load_bmp_source_build(VipsObject *object)
  609. {
  610. VipsForeignLoadBmp *bmp = (VipsForeignLoadBmp *) object;
  611. VipsForeignLoadBmpSource *source =
  612. (VipsForeignLoadBmpSource *) object;
  613. if (source->source) {
  614. bmp->source = source->source;
  615. g_object_ref(bmp->source);
  616. }
  617. return VIPS_OBJECT_CLASS(vips_foreign_load_bmp_source_parent_class)
  618. ->build(object);
  619. }
  620. static void
  621. vips_foreign_load_bmp_source_class_init(
  622. VipsForeignLoadBmpSourceClass *class)
  623. {
  624. GObjectClass *gobject_class = G_OBJECT_CLASS(class);
  625. VipsObjectClass *object_class = (VipsObjectClass *) class;
  626. VipsOperationClass *operation_class = VIPS_OPERATION_CLASS(class);
  627. VipsForeignLoadClass *load_class = (VipsForeignLoadClass *) class;
  628. gobject_class->set_property = vips_object_set_property;
  629. gobject_class->get_property = vips_object_get_property;
  630. load_class->is_a_source = vips_foreign_load_bmp_source_is_a_source;
  631. object_class->nickname = "bmpload_source";
  632. object_class->description = "load image from bmp source";
  633. object_class->build = vips_foreign_load_bmp_source_build;
  634. VIPS_ARG_OBJECT(class, "source", 1,
  635. "Source",
  636. "Source to load from",
  637. VIPS_ARGUMENT_REQUIRED_INPUT,
  638. G_STRUCT_OFFSET(VipsForeignLoadBmpSource, source),
  639. VIPS_TYPE_SOURCE);
  640. }
  641. static void
  642. vips_foreign_load_bmp_source_init(VipsForeignLoadBmpSource *source)
  643. {
  644. }
  645. typedef struct _VipsForeignLoadBmpBuffer {
  646. VipsForeignLoadBmp parent_object;
  647. /* Load from a buffer.
  648. */
  649. VipsBlob *blob;
  650. } VipsForeignLoadBmpBuffer;
  651. typedef VipsForeignLoadBmpClass VipsForeignLoadBmpBufferClass;
  652. G_DEFINE_TYPE(VipsForeignLoadBmpBuffer, vips_foreign_load_bmp_buffer,
  653. vips_foreign_load_bmp_get_type());
  654. static int
  655. vips_foreign_load_bmp_buffer_build(VipsObject *object)
  656. {
  657. VipsForeignLoadBmp *bmp = (VipsForeignLoadBmp *) object;
  658. VipsForeignLoadBmpBuffer *buffer = (VipsForeignLoadBmpBuffer *) object;
  659. if (buffer->blob &&
  660. !(bmp->source = vips_source_new_from_memory(
  661. VIPS_AREA(buffer->blob)->data,
  662. VIPS_AREA(buffer->blob)->length)))
  663. return -1;
  664. return VIPS_OBJECT_CLASS(vips_foreign_load_bmp_buffer_parent_class)
  665. ->build(object);
  666. }
  667. /**
  668. * Checks if the source is a BMP image
  669. */
  670. static gboolean
  671. vips_foreign_load_bmp_buffer_is_a_buffer(const void *buf, size_t len)
  672. {
  673. if (len < 2) {
  674. vips_error("vips_foreign_load_bmp_buffer_is_a_buffer", "buffer too short");
  675. return 0;
  676. }
  677. return ((VipsPel *) buf)[0] == 'B' &&
  678. ((VipsPel *) buf)[1] == 'M';
  679. }
  680. static void
  681. vips_foreign_load_bmp_buffer_class_init(VipsForeignLoadBmpBufferClass *class)
  682. {
  683. GObjectClass *gobject_class = G_OBJECT_CLASS(class);
  684. VipsObjectClass *object_class = (VipsObjectClass *) class;
  685. VipsForeignLoadClass *load_class = (VipsForeignLoadClass *) class;
  686. gobject_class->set_property = vips_object_set_property;
  687. gobject_class->get_property = vips_object_get_property;
  688. object_class->nickname = "bmpload_buffer";
  689. object_class->description = "load bmp from buffer";
  690. object_class->build = vips_foreign_load_bmp_buffer_build;
  691. load_class->is_a_buffer = vips_foreign_load_bmp_buffer_is_a_buffer;
  692. VIPS_ARG_BOXED(class, "buffer", 1,
  693. "Buffer",
  694. "Buffer to load from",
  695. VIPS_ARGUMENT_REQUIRED_INPUT,
  696. G_STRUCT_OFFSET(VipsForeignLoadBmpBuffer, blob),
  697. VIPS_TYPE_BLOB);
  698. }
  699. static void
  700. vips_foreign_load_bmp_buffer_init(VipsForeignLoadBmpBuffer *buffer)
  701. {
  702. }
  703. /**
  704. * vips_bmpload_buffer:
  705. * @buf: (array length=len) (element-type guint8): memory area to load
  706. * @len: (type gsize): size of memory area
  707. * @out: (out): image to write
  708. * @...: `NULL`-terminated list of optional named arguments
  709. *
  710. * Exactly as [ctor@Image.pngload], but read from a PNG-formatted memory block.
  711. *
  712. * You must not free the buffer while @out is active. The
  713. * [signal@Object::postclose] signal on @out is a good place to free.
  714. *
  715. * ::: seealso
  716. * [ctor@Image.pngload].
  717. *
  718. * Returns: 0 on success, -1 on error.
  719. */
  720. int
  721. vips_bmpload_buffer(void *buf, size_t len, VipsImage **out, ...)
  722. {
  723. va_list ap;
  724. VipsBlob *blob;
  725. int result;
  726. /* We don't take a copy of the data or free it.
  727. */
  728. blob = vips_blob_new(NULL, buf, len);
  729. va_start(ap, out);
  730. result = vips_call_split("bmpload_buffer", ap, blob, out);
  731. va_end(ap);
  732. vips_area_unref(VIPS_AREA(blob));
  733. return result;
  734. }
  735. /**
  736. * vips_bmpload_source:
  737. * @source: source to load
  738. * @out: (out): image to write
  739. * @...: `NULL`-terminated list of optional named arguments
  740. *
  741. * Read a RAWRGB-formatted memory block into a VIPS image.
  742. *
  743. * Returns: 0 on success, -1 on error.
  744. */
  745. int
  746. vips_bmpload_source(VipsSource *source, VipsImage **out, ...)
  747. {
  748. va_list ap;
  749. int result;
  750. va_start(ap, out);
  751. result = vips_call_split("bmpload_source", ap, source, out);
  752. va_end(ap);
  753. return result;
  754. }
  755. // wrapper function which hiders varargs (...) from CGo
  756. int
  757. vips_bmpload_source_go(VipsImgproxySource *source, VipsImage **out, ImgproxyLoadOptions lo)
  758. {
  759. return vips_bmpload_source(
  760. VIPS_SOURCE(source), out,
  761. "access", VIPS_ACCESS_SEQUENTIAL,
  762. NULL);
  763. }