summaryrefslogtreecommitdiff
path: root/docs/overview.txt
blob: 0fd7b90ab42212d177d52f2ca5ee93fa17f8f388 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
Contents
========

* Basic MuPDF usage example
* Common function arguments
* Error Handling
* Multi-threading
* Cloning the context
* Bound contexts

Basic MuPDF usage example
=========================

For an example of how to use MuPDF in the most basic way, see
doc/example.c. To limit the complexity and give an easier introduction
this code has no error handling at all, but any serious piece of code
using MuPDF should use the error handling strategies described below.

Common function arguments
=========================

Many functions in MuPDFs interface take a context argument.

A context contains global state used by MuPDF inside functions when
parsing or rendering pages of the document. It contains for example:

	an exception stack (see error handling below),

	a memory allocator (allowing for custom allocators)

	a resource store (for caching of images, fonts, etc.)

	a set of locks and (un-)locking functions (for multi-threading)

Other functions in MuPDF's interface take arguments such as document,
stream and device which contain state for each type of object. Those
arguments each have a reference to a context and therefore act as
proxies for a context.

Without the set of locks and accompanying functions the context and
its proxies may only be used in a single-threaded application.

Error handling
==============

MuPDF uses a set of exception handling macros to simplify error return
and cleanup. Conceptually, they work a lot like C++'s try/catch
system, but do not require any special compiler support.

The basic formulation is as follows:

	fz_try(ctx)
	{
		// Try to perform a task. Never 'return', 'goto' or
		// 'longjmp' out of here. 'break' may be used to
		// safely exit (just) the try block scope.
	}
	fz_always(ctx)
	{
		// Any code here is always executed, regardless of
		// whether an exception was thrown within the try or
		// not. Never 'return', 'goto' or longjmp out from
		// here. 'break' may be used to safely exit (just) the
		// always block scope.
	}
	fz_catch(ctx)
	{
		// This code is called (after any always block) only
		// if something within the fz_try block (including any
		// functions it called) threw an exception. The code
		// here is expected to handle the exception (maybe
		// record/report the error, cleanup any stray state
		// etc) and can then either exit the block, or pass on
		// the exception to a higher level (enclosing) fz_try
		// block (using fz_throw, or fz_rethrow).
	}

The fz_always block is optional, and can safely be omitted.

The macro based nature of this system has 3 main limitations:

1)	Never return from within try (or 'goto' or longjmp out of it).
	This upsets the internal housekeeping of the macros and will
	cause problems later on. The code will detect such things
	happening, but by then it is too late to give a helpful error
	report as to where the original infraction occurred.

2)	The fz_try(ctx) { ... } fz_always(ctx) { ... } fz_catch(ctx) { ... }
	is not one atomic C statement. That is to say, if you do:

		if (condition)
			fz_try(ctx) { ... }
			fz_catch(ctx) { ... }

	then you will not get what you want. Use the following instead:

		if (condition) {
			fz_try(ctx) { ... }
			fz_catch(ctx) { ... }
		}

3)	The macros are implemented using setjmp and longjmp, and so
	the standard C restrictions on the use of those functions
	apply to fz_try/fz_catch too. In particular, any "truly local"
	variable that is set between the start of fz_try and something
	in fz_try throwing an exception may become undefined as part
	of the process of throwing that exception.

	As a way of mitigating this problem, we provide an fz_var()
	macro that tells the compiler to ensure that that variable is
	not unset by the act of throwing the exception.

A model piece of code using these macros then might be:

	house build_house(plans *p)
	{
		material m = NULL;
		walls w = NULL;
		roof r = NULL;
		house h = NULL;
		tiles t = make_tiles();

		fz_var(w);
		fz_var(r);
		fz_var(h);

		fz_try(ctx)
		{
			fz_try(ctx)
			{
				m = make_bricks();
			}
			fz_catch(ctx)
			{
				// No bricks available, make do with straw?
				m = make_straw();
			}
			w = make_walls(m, p);
			r = make_roof(m, t);
			// Note, NOT: return combine(w,r);
			h = combine(w, r);
		}
		fz_always(ctx)
		{
			drop_walls(w);
			drop_roof(r);
			drop_material(m);
			drop_tiles(t);
		}
		fz_catch(ctx)
		{
			fz_throw(ctx, "build_house failed");
		}
		return h;
	}

Things to note about this:

a)	If make_tiles throws an exception, this will immediately be
	handled by some higher level exception handler. If it
	succeeds, t will be set before fz_try starts, so there is no
	need to fz_var(t);

b)	We try first off to make some bricks as our building material.
	If this fails, we fall back to straw. If this fails, we'll end
	up in the fz_catch, and the process will fail neatly.

c)	We assume in this code that combine takes new reference to
	both the walls and the roof it uses, and therefore that w and
	r need to be cleaned up in all cases.

d)	We assume the standard C convention that it is safe to destroy
	NULL things.

Multi-threading
===============

First off, study the basic usage example in doc/example.c and make
sure you understand how it works as the data structures manipulated
there will be refered to in this section too.

MuPDF can usefully be built into a multi-threaded application without
the library needing to know anything threading at all. If the library
opens a document in one thread, and then sits there as a 'server'
requesting pages and rendering them for other threads that need them,
then the library is only ever being called from this one thread.

Other threads can still be used to handle UI requests etc, but as far
as MuPDF is concerned it is only being used in a single threaded way.
In this instance, there are no threading issues with MuPDF at all,
and it can safely be used without any locking, as described in the
previous sections.

This section will attempt to explain how to use MuPDF in the more
complex case; where we genuinely want to call the MuPDF library
concurrently from multiple threads within a single application.

MuPDF can be invoked with a user supplied set of locking functions.
It uses these to take mutexes around operations that would conflict
if performed concurrently in multiple threads. By leaving the
exact implementation of locks to the caller MuPDF remains threading
library agnostic.

The following simple rules should be followed to ensure that
multi-threaded operations run smoothly:

1)	"No simultaneous calls to MuPDF in different threads are
	allowed to use the same context."

	Most of the time it is simplest to just use a different
	context for every thread; just create a new context at the
	same time as you create the thread. For more details see
	"Cloning the context" below.

2)	"The document is bound to the context with which it is created."

	All subsequent accesses to the document implicitly use the same
	context; this means that only 1 thread can ever be accessing
	the document at once. This does not mean that the document can
	only ever be used from one thread, though in many cases this
	is the simplest structure overall. See "Bound contexts" below.

3)	"Any device is bound to the context with which it is created."

	All subsequent uses of a device implicitly use the context with
	which it was created; this means that if a device is used with
	a document, it should be created with the same context as that
	document was. This does not mean that the device can only ever
	be used from one thread, though in many cases this is the
	simplest structure overall. See "Bound contexts" below.

So, how does a multi-threaded example differ from a non-multithreaded
one?

Firstly, when we create the first context, we call fz_new_context
as before, but the second argument should be a pointer to a set
of locking functions.

The calling code should provide FZ_LOCK_MAX mutexes, which will be
locked/unlocked by MuPDF calling the lock/unlock function pointers
in the supplied structure with the user pointer from the structure
and the lock number, i (0 <= i < FZ_LOCK_MAX). These mutexes can
safely be recursive or non-recursive as MuPDF only calls in a non-
recursive style.

To make subsequent contexts, the user should NOT call fz_new_context
again (as this will fail to share important resources such as the
store and glyphcache), but should rather call fz_clone_context.
Each of these cloned contexts can be freed by fz_free_context as
usual. They will share the important data structures (like store,
glyph cache etc) with the original context, but will have their
own exception stacks.

To open a document, call fz_open_document as usual, passing a context
and a filename; this context is bound to the document. All future
calls to access the document will use this context internally.

Only one thread at a time can therefore perform operations such as
fetching a page, or rendering that page to a display list. Once a
display list has been obtained however, it can be rendered from any
other thread (or even from several threads simultaneously, giving
banded rendering).

This means that an implementer has 2 basic choices when constructing
an application to use MuPDF in multi-threaded mode. Either he can
construct it so that a single nominated thread opens the document
and then acts as a 'server' creating display lists for other threads
to render, or he can add his own mutex around calls to mupdf that
use the document. The former is likely to be far more efficient in
the long run.

For an example of how to do multi-threading see doc/multi-threaded.c
which has a main thread and one rendering thread per page.

Cloning the context
===================

As described above, every context contains an exception stack which is
manipulated during the course of nested fz_try/fz_catches. For obvious
reasons the same exception stack cannot be used from more than one
thread at a time.

If, however, we simply created a new context (using fz_new_context) for
every thread, we would end up with separate stores/glyph caches etc,
which is not (generally) what is desired. MuPDF therefore provides a
mechanism for "cloning" a context. This creates a new context that
shares everything with the given context, except for the exception
stack.

A commonly used general scheme is therefore to create a 'base' context
at program start up, and to clone this repeatedly to get new contexts
that can be used on new threads.

Bound contexts
==============

Certain objects, bind themselves to the context with which they are
created. For instance, when a document (or device) is created it
remembers the context which it was initially passed. The advantage
of this is that any subsequent calls to the document do not need a
context to be passed (and internally, we only need to pass a document
pointer around rather than both a document and a context pointer).

The downside to this is that care must be taken to only use the
document pointer with the same context. For example consider the
following pseudo code:

	// Create the base context
	base_ctx = fz_new_context(...);

	// Open the document. doc remembers ctx.
	doc = fz_open_document(ctx, ...);

	// Create a new context, possibly to use in another thread
	ctx2 = fz_clone_context(ctx);

	// Get a page using that new context
	fz_try(ctx2)
	{
		page = fz_load_page(doc, page_number);
	}
	fz_catch(ctx2)
	{
		// handle the error
		...
	}

On the face of it, this seems fine, until you consider what happens
internally to fz_load_page. The internals of fz_load_page will use
error handling too, and so will fz_throw in some circumstances (and
will probably do fz_try/fz_catch for themselves). In order to do so,
they will retrieve the ctx that doc was created with - in the above
example this will be base_ctx.

This means that in the case of an error being thrown from within
fz_load_page we'll end up with something like the following:

	fz_try(ctx2)
	{
		...
		// inside fz_load_page, an error occurs
		fz_throw(base_ctx, ... };
		...

	}
	fz_catch(ctx2)
	{
		// Handle the error
	}

The error will be thrown using the exception stack from base_ctx, but
the caller has set up the code to catch the error using the exception
stack from ctx2. Code that gets this wrong may well appear to work
perfectly well for long periods, and then only fail with files that
raise errors in particular places. This will cause the program to
terminate abnormally (or crash), and can be very hard to debug.