]> git.sur5r.net Git - cc65/blob - src/sp65/pcx.c
Added the write routine.
[cc65] / src / sp65 / pcx.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                   pcx.c                                   */
4 /*                                                                           */
5 /*                              Read PCX files                               */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 2012,      Ullrich von Bassewitz                                      */
10 /*                Roemerstrasse 52                                           */
11 /*                D-70794 Filderstadt                                        */
12 /* EMail:         uz@cc65.org                                                */
13 /*                                                                           */
14 /*                                                                           */
15 /* This software is provided 'as-is', without any expressed or implied       */
16 /* warranty.  In no event will the authors be held liable for any damages    */
17 /* arising from the use of this software.                                    */
18 /*                                                                           */
19 /* Permission is granted to anyone to use this software for any purpose,     */
20 /* including commercial applications, and to alter it and redistribute it    */
21 /* freely, subject to the following restrictions:                            */
22 /*                                                                           */
23 /* 1. The origin of this software must not be misrepresented; you must not   */
24 /*    claim that you wrote the original software. If you use this software   */
25 /*    in a product, an acknowledgment in the product documentation would be  */
26 /*    appreciated but is not required.                                       */
27 /* 2. Altered source versions must be plainly marked as such, and must not   */
28 /*    be misrepresented as being the original software.                      */
29 /* 3. This notice may not be removed or altered from any source              */
30 /*    distribution.                                                          */
31 /*                                                                           */
32 /*****************************************************************************/
33
34
35
36 #include <errno.h>
37 #include <stdio.h>
38 #include <string.h>
39
40 /* common */
41 #include "print.h"
42 #include "xmalloc.h"
43
44 /* sp65 */
45 #include "error.h"
46 #include "fileio.h"
47 #include "pcx.h"
48
49
50
51 /*****************************************************************************/
52 /*                                  Macros                                   */
53 /*****************************************************************************/
54
55
56
57 /* Some PCX constants */
58 #define PCX_MAGIC_ID            0x0A
59 #define PCX_MAX_PLANES          4
60
61 /* A raw PCX header is just a block of bytes */
62 typedef unsigned char           RawPCXHeader[128];
63
64 /* Structured PCX header */
65 typedef struct PCXHeader PCXHeader;
66 struct PCXHeader {
67     unsigned        Id;
68     unsigned        FileVersion;
69     unsigned        Compressed;
70     unsigned        BPP;
71     unsigned        XMin;
72     unsigned        YMin;
73     unsigned        XMax;
74     unsigned        YMax;
75     unsigned        XDPI;
76     unsigned        YDPI;
77     unsigned        Planes;
78     unsigned        BytesPerPlane;
79     unsigned        PalInfo;
80     unsigned        ScreenWidth;
81     unsigned        ScreenHeight;
82
83     /* Calculated data */
84     unsigned        Width;
85     unsigned        Height;
86 };
87
88 /* Read a little endian word from a byte array at offset O */
89 #define WORD(H, O)              ((H)[O] | ((H)[O+1] << 8))
90
91
92
93 /*****************************************************************************/
94 /*                                   Code                                    */
95 /*****************************************************************************/
96
97
98
99 static PCXHeader* NewPCXHeader (void)
100 /* Allocate a new PCX header and return it */
101 {
102     /* No initialization here */
103     return xmalloc (sizeof (PCXHeader));
104 }
105
106
107
108 static void FreePCXHeader (PCXHeader* H)
109 /* Free a PCX header structure */
110 {
111     xfree (H);
112 }
113
114
115
116 static PCXHeader* ReadPCXHeader (FILE* F, const char* Name)
117 /* Read a structured PCX header from the given file and return it */
118 {
119     RawPCXHeader H;
120
121     /* Allocate a new PCXHeader structure */
122     PCXHeader* P = NewPCXHeader ();
123
124     /* Read the raw header */
125     ReadData (F, H, sizeof (H));
126
127     /* Convert the data into structured form */
128     P->Id               = H[0];
129     P->FileVersion      = H[1];
130     P->Compressed       = H[2];
131     P->BPP              = H[3];
132     P->XMin             = WORD (H, 4);
133     P->YMin             = WORD (H, 6);
134     P->XMax             = WORD (H, 8);
135     P->YMax             = WORD (H, 10);
136     P->XDPI             = WORD (H, 12);
137     P->YDPI             = WORD (H, 14);
138     P->Planes           = H[65];
139     P->BytesPerPlane    = WORD (H, 66);
140     P->PalInfo          = WORD (H, 68);
141     P->ScreenWidth      = WORD (H, 70);
142     P->ScreenHeight     = WORD (H, 72);
143     P->Width            = P->XMax - P->XMin + 1;
144     P->Height           = P->YMax - P->YMin + 1;
145
146     /* Check the header data */
147     if (P->Id != PCX_MAGIC_ID || P->FileVersion == 1 || P->FileVersion > 5) {
148         Error ("`%s' is not a PCX file", Name);
149     }
150     if (P->Compressed > 1) {
151         Error ("Unsupported compression (%d) in PCX file `%s'",
152                P->Compressed, Name);
153     }
154     /* We support:
155      *   - one plane with either 1 or 8 bits per pixel
156      *   - three planes with 8 bits per pixel
157      *   - four planes with 8 bits per pixel (does this exist?)
158      */
159     if (!((P->BPP == 1 && P->Planes == 1) ||
160           (P->BPP == 8 && (P->Planes == 1 || P->Planes == 3 || P->Planes == 4)))) {
161         /* We could support others, but currently we don't */
162         Error ("Unsupported PCX format: %u planes, %u bpp in PCX file `%s'",
163                P->Planes, P->BPP, Name);
164     }
165     if (P->PalInfo != 1 && P->PalInfo != 2) {
166         Error ("Unsupported palette info (%u) in PCX file `%s'",
167                P->PalInfo, Name);
168     }
169     if (!ValidBitmapSize (P->Width, P->Height)) {
170         Error ("PCX file `%s' has an unsupported size (w=%u, h=%d)",
171                Name, P->Width, P->Height);
172     }
173
174     /* Return the structured header */
175     return P;
176 }
177
178
179
180 static void DumpPCXHeader (const PCXHeader* P, const char* Name)
181 /* Dump the header of the PCX file in readable form to stdout */
182 {
183     printf ("File name:       %s\n", Name);
184     printf ("PCX Version:     ");
185     switch (P->FileVersion) {
186         case 0: puts ("2.5");                             break;
187         case 2: puts ("2.8 with palette");                break;
188         case 3: puts ("2.8 without palette");             break;
189         case 4: puts ("PCX for Windows without palette"); break;
190         case 5: puts ("3.0");                             break;
191     }
192     printf ("Image type:      %s\n", P->PalInfo? "color" : "grayscale");
193     printf ("Compression:     %s\n", P->Compressed? "RLE" : "None");
194     printf ("Structure:       %u planes of %u bits\n", P->Planes, P->BPP);
195     printf ("Bounding box:    [%u/%u - %u/%u]\n", P->XMin, P->YMin, P->XMax, P->YMax);
196     printf ("Resolution:      %u/%u DPI\n", P->XDPI, P->YDPI);
197     printf ("Screen size:     %u/%u\n", P->ScreenWidth, P->ScreenHeight);
198     printf ("Bytes per plane: %u\n", P->BytesPerPlane);
199 }
200
201
202
203 static void ReadPlane (FILE* F, PCXHeader* P, unsigned char* L)
204 /* Read one (possibly compressed) plane from the file */
205 {
206     if (P->Compressed) {
207
208         /* Uncompress RLE data */
209         unsigned Remaining = P->Width;
210         while (Remaining) {
211
212             unsigned char C;
213
214             /* Read the next byte */
215             unsigned char B = Read8 (F);
216
217             /* Check for a run length */
218             if ((B & 0xC0) == 0xC0) {
219                 C = (B & 0x3F);         /* Count */
220                 B = Read8 (F);          /* Value */
221             } else {
222                 C = 1;
223             }
224
225             /* Write the data to the buffer */
226             if (C > Remaining) {
227                 C = Remaining;
228             }
229             memset (L, B, C);
230
231             /* Bump counters */
232             L += C;
233             Remaining -= C;
234
235         }
236     } else {
237
238         /* Just read one line */
239         ReadData (F, L, P->Width);
240
241     }
242 }
243
244
245
246 Bitmap* ReadPCXFile (const char* Name)
247 /* Read a bitmap from a PCX file */
248 {
249     PCXHeader* P;
250     Bitmap* B;
251     unsigned char* L;
252     Pixel* Px;
253     unsigned MaxIdx = 0;
254     unsigned X, Y;
255
256
257
258     /* Open the file */
259     FILE* F = fopen (Name, "rb");
260     if (F == 0) {
261         Error ("Cannot open PCX file `%s': %s", Name, strerror (errno));
262     }
263
264     /* Read the PCX header */
265     P = ReadPCXHeader (F, Name);
266
267     /* Dump the header if requested */
268     if (Verbosity > 0) {
269         DumpPCXHeader (P, Name);
270     }
271
272     /* Create the bitmap */
273     B = NewBitmap (P->Width, P->Height);
274
275     /* Determine the type of the bitmap */
276     switch (P->Planes) {
277         case 1: B->Type = (P->PalInfo? bmIndexed : bmMonochrome);       break;
278         case 3: B->Type = bmRGB;                                        break;
279         case 4: B->Type = bmRGBA;                                       break;
280         default:Internal ("Unexpected number of planes");
281     }
282
283     /* Copy the name */
284     SB_CopyStr (&B->Name, Name);
285
286     /* Allocate memory for the scan line */
287     L = xmalloc (P->Width);
288
289     /* Read the pixel data */
290     Px = B->Data;
291     if (P->Planes == 1) {
292
293         /* This is either monochrome or indexed */
294         if (P->BPP == 1) {
295             /* Monochrome */
296             for (Y = 0, Px = B->Data; Y < P->Height; ++Y) {
297
298                 unsigned I;
299                 unsigned char Mask;
300
301                 /* Read the plane */
302                 ReadPlane (F, P, L);
303
304                 /* Create pixels */
305                 for (X = 0, I = 0, Mask = 0x01; X < P->Width; ++Px) {
306                     Px->Index = (L[I] & Mask) != 0;
307                     if (Mask == 0x80) {
308                         Mask = 0x01;
309                         ++I;
310                     } else {
311                         Mask <<= 1;
312                     }
313                 }
314
315             }
316         } else {
317             /* One plane with 8bpp is indexed */
318             for (Y = 0, Px = B->Data; Y < P->Height; ++Y) {
319
320                 /* Read the plane */
321                 ReadPlane (F, P, L);
322
323                 /* Create pixels */
324                 for (X = 0; X < P->Width; ++X, ++Px) {
325                     if (L[X] > MaxIdx) {
326                         MaxIdx = L[X];
327                     }
328                     Px->Index = L[X];
329                 }
330             }
331         }
332     } else {
333         /* 3 or 4 planes are RGB or RGBA (don't know if this exists) */
334         for (Y = 0, Px = B->Data; Y < P->Height; ++Y) {
335
336             /* Read the R plane and move the data */
337             ReadPlane (F, P, L);
338             for (X = 0; X < P->Width; ++X, ++Px) {
339                 Px->C.R = L[X];
340             }
341
342             /* Read the G plane and move the data */
343             ReadPlane (F, P, L);
344             for (X = 0; X < P->Width; ++X, ++Px) {
345                 Px->C.G = L[X];
346             }
347
348             /* Read the B plane and move the data */
349             ReadPlane (F, P, L);
350             for (X = 0; X < P->Width; ++X, ++Px) {
351                 Px->C.B = L[X];
352             }
353
354             /* Either read the A plane or clear it */
355             if (P->Planes == 4) {
356                 ReadPlane (F, P, L);
357                 for (X = 0; X < P->Width; ++X, ++Px) {
358                     Px->C.A = L[X];
359                 }
360             } else {
361                 for (X = 0; X < P->Width; ++X, ++Px) {
362                     Px->C.A = 0;
363                 }
364             }
365         }
366     }
367
368     /* One plane means we have a palette which is either part of the header
369      * or follows.
370      */
371     if (B->Type == bmMonochrome) {
372
373         /* Create the monochrome palette */
374         B->Pal = NewMonochromePalette ();
375
376     } else if (B->Type == bmIndexed) {
377
378         unsigned      Count;
379         unsigned      I;
380         unsigned char Palette[256][3];
381         unsigned long EndPos;
382
383         /* Determine the current file position */
384         unsigned long CurPos = FileGetPos (F);
385
386         /* Seek to the end of the file */
387         (void) fseek (F, 0, SEEK_END);
388
389         /* Get this position */
390         EndPos = FileGetPos (F);
391
392         /* There's a palette if the old location is 769 bytes from the end */
393         if (EndPos - CurPos == sizeof (Palette) + 1) {
394
395             /* Seek back */
396             FileSetPos (F, CurPos);
397
398             /* Check for palette marker */
399             if (Read8 (F) != 0x0C) {
400                 Error ("Invalid palette marker in PCX file `%s'", Name);
401             }
402
403         } else if (EndPos == CurPos) {
404
405             /* The palette is in the header */
406             FileSetPos (F, 16);
407
408             /* Check the maximum index for safety */
409             if (MaxIdx > 15) {
410                 Error ("PCX file `%s' contains more than 16 indexed colors "
411                        "but no extra palette", Name);
412             }
413
414         } else {
415             Error ("Error in PCX file `%s': %lu bytes at end of pixel data",
416                    Name, EndPos - CurPos);
417         }
418
419         /* Read the palette. We will just read what we need. */
420         Count = MaxIdx + 1;
421         ReadData (F, Palette, Count * sizeof (Palette[0]));
422
423         /* Create the palette from the data */
424         B->Pal = NewPalette (Count);
425         for (I = 0; I < Count; ++I) {
426             B->Pal->Entries[I].R = Palette[I][0];
427             B->Pal->Entries[I].G = Palette[I][1];
428             B->Pal->Entries[I].B = Palette[I][2];
429             B->Pal->Entries[I].A = 0;
430         }
431
432     }
433
434     /* Close the file */
435     fclose (F);
436
437     /* Free the PCX header */
438     FreePCXHeader (P);
439
440     /* Return the bitmap */
441     return B;
442 }
443
444
445