poppler: update to version 0.22.1
[fbpdf.git] / djvulibre.c
blob8f54cdcc35a2216349d3553ba57ecce37784eddd
1 #include <stdlib.h>
2 #include <string.h>
3 #include <unistd.h>
4 #include <libdjvu/ddjvuapi.h>
5 #include "draw.h"
6 #include "doc.h"
8 #define MIN(a, b) ((a) < (b) ? (a) : (b))
10 struct doc {
11 ddjvu_context_t *ctx;
12 ddjvu_document_t *doc;
15 int djvu_handle(struct doc *doc)
17 ddjvu_message_t *msg;
18 msg = ddjvu_message_wait(doc->ctx);
19 while ((msg = ddjvu_message_peek(doc->ctx))) {
20 if (msg->m_any.tag == DDJVU_ERROR) {
21 fprintf(stderr,"ddjvu: %s\n", msg->m_error.message);
22 return 1;
24 ddjvu_message_pop(doc->ctx);
26 return 0;
29 static void djvu_render(ddjvu_page_t *page, int mode, void *bitmap, int cols,
30 ddjvu_rect_t *prect, ddjvu_rect_t *rrect)
32 ddjvu_format_t *fmt;
33 int i = 0;
34 fmt = ddjvu_format_create(DDJVU_FORMAT_GREY8, 0, 0);
35 ddjvu_format_set_row_order(fmt, 1);
37 while (i++ < 2 && !ddjvu_page_render(page, mode, prect,
38 rrect, fmt, cols, bitmap))
39 usleep(100000);
40 ddjvu_format_release(fmt);
43 #define SIZE (1 << 13)
44 static char img[SIZE * SIZE];
46 int doc_draw(struct doc *doc, int p, int zoom, int rotate,
47 fbval_t *bitmap, int *rows, int *cols)
49 ddjvu_page_t *page;
50 ddjvu_rect_t rect;
51 ddjvu_pageinfo_t info;
52 int w, h;
53 int i, j;
54 page = ddjvu_page_create_by_pageno(doc->doc, p - 1);
55 if (!page)
56 return -1;
57 if (!ddjvu_page_decoding_done(page))
58 if (djvu_handle(doc))
59 return -1;
61 ddjvu_document_get_pageinfo(doc->doc, p - 1, &info);
62 rect.x = 0;
63 rect.y = 0;
64 rect.w = ddjvu_page_get_width(page);
65 rect.h = ddjvu_page_get_height(page);
67 /* mode: DDJVU_RENDER_(BLACK|COLOR|BACKGROUND|FOREGROUND) */
68 djvu_render(page, DDJVU_RENDER_FOREGROUND, img, SIZE, &rect, &rect);
69 ddjvu_page_release(page);
70 zoom /= 4;
71 w = MIN(*cols, rect.w * zoom / 10);
72 h = MIN(*rows, rect.h * zoom / 10);
73 for (i = 0; i < h; i++) {
74 int xs = i * *cols + (*cols - w) / 2;
75 for (j = 0; j < w; j++)
76 bitmap[xs + j] = img[i * 10 / zoom * SIZE + j * 10 / zoom];
78 *cols = w;
79 *rows = h;
80 return 0;
83 int doc_pages(struct doc *doc)
85 return ddjvu_document_get_pagenum(doc->doc);
88 struct doc *doc_open(char *path)
90 struct doc *doc = malloc(sizeof(*doc));
91 doc->ctx = ddjvu_context_create("fbpdf");
92 if (!doc->ctx)
93 goto fail;
94 doc->doc = ddjvu_document_create_by_filename(doc->ctx, path, 1);
95 if (!doc->doc)
96 goto fail;
97 if (!ddjvu_document_decoding_done(doc->doc))
98 if (djvu_handle(doc))
99 goto fail;
100 return doc;
101 fail:
102 doc_close(doc);
103 return NULL;
106 void doc_close(struct doc *doc)
108 if (doc->doc)
109 ddjvu_context_release(doc->ctx);
110 if (doc->ctx)
111 ddjvu_document_release(doc->doc);
112 free(doc);