]> git.sesse.net Git - ffmpeg/blob - libavcodec/exr.c
exr: support for reading pixelAspectRatio
[ffmpeg] / libavcodec / exr.c
1 /*
2  * OpenEXR (.exr) image decoder
3  * Copyright (c) 2009 Jimmy Christensen
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * OpenEXR decoder
25  * @author Jimmy Christensen
26  *
27  * For more information on the OpenEXR format, visit:
28  *  http://openexr.com/
29  *
30  * exr_flt2uint() and exr_halflt2uint() is credited to  Reimar Döffinger
31  */
32
33 #include "avcodec.h"
34 #include "bytestream.h"
35 #include "libavutil/imgutils.h"
36
37 enum ExrCompr {
38     EXR_RAW   = 0,
39     EXR_RLE   = 1,
40     EXR_ZIP1  = 2,
41     EXR_ZIP16 = 3,
42     EXR_PIZ   = 4,
43     EXR_B44   = 6
44 };
45
46 typedef struct EXRContext {
47     AVFrame picture;
48     int compr;
49     int bits_per_color_id;
50     int8_t channel_offsets[4]; // 0 = red, 1 = green, 2 = blue and 3 = alpha
51 } EXRContext;
52
53 /**
54  * Converts from 32-bit float as uint32_t to uint16_t
55  *
56  * @param v 32-bit float
57  * @return normalized 16-bit unsigned int
58  */
59 static inline uint16_t exr_flt2uint(uint32_t v)
60 {
61     unsigned int exp = v >> 23;
62     // "HACK": negative values result in exp<  0, so clipping them to 0
63     // is also handled by this condition, avoids explicit check for sign bit.
64     if (exp<= 127 + 7 - 24) // we would shift out all bits anyway
65         return 0;
66     if (exp >= 127)
67         return 0xffff;
68     v &= 0x007fffff;
69     return (v + (1 << 23)) >> (127 + 7 - exp);
70 }
71
72 /**
73  * Converts from 16-bit float as uint16_t to uint16_t
74  *
75  * @param v 16-bit float
76  * @return normalized 16-bit unsigned int
77  */
78 static inline uint16_t exr_halflt2uint(uint16_t v)
79 {
80     unsigned exp = 14 - (v >> 10);
81     if (exp >= 14) {
82         if (exp == 14) return (v >> 9) & 1;
83         else           return (v & 0x8000) ? 0 : 0xffff;
84     }
85     v <<= 6;
86     return (v + (1 << 16)) >> (exp + 1);
87 }
88
89 /**
90  * Gets the size of the header variable
91  *
92  * @param **buf the current pointer location in the header where
93  * the variable data starts
94  * @param *buf_end pointer location of the end of the buffer
95  * @return size of variable data
96  */
97 static unsigned int get_header_variable_length(const uint8_t **buf,
98                                                const uint8_t *buf_end)
99 {
100     unsigned int variable_buffer_data_size = bytestream_get_le32(buf);
101     if (variable_buffer_data_size >= buf_end - *buf)
102         return 0;
103     return variable_buffer_data_size;
104 }
105
106 /**
107  * Checks if the variable name corresponds with it's data type
108  *
109  * @param *avctx the AVCodecContext
110  * @param **buf the current pointer location in the header where
111  * the variable name starts
112  * @param *buf_end pointer location of the end of the buffer
113  * @param *value_name name of the varible to check
114  * @param *value_type type of the varible to check
115  * @param minimum_length minimum length of the variable data
116  * @param variable_buffer_data_size variable length read from the header
117  * after it's checked
118  * @return negative if variable is invalid
119  */
120 static int check_header_variable(AVCodecContext *avctx,
121                                               const uint8_t **buf,
122                                               const uint8_t *buf_end,
123                                               const char *value_name,
124                                               const char *value_type,
125                                               unsigned int minimum_length,
126                                               unsigned int *variable_buffer_data_size)
127 {
128     if (buf_end - *buf >= minimum_length && !strcmp(*buf, value_name)) {
129         *buf += strlen(value_name)+1;
130         if (!strcmp(*buf, value_type)) {
131             *buf += strlen(value_type)+1;
132             *variable_buffer_data_size = get_header_variable_length(buf, buf_end);
133             if (!*variable_buffer_data_size)
134                 av_log(avctx, AV_LOG_ERROR, "Incomplete header\n");
135             if (*variable_buffer_data_size > buf_end - *buf)
136                 return -1;
137             return 1;
138         }
139         *buf -= strlen(value_name)+1;
140         av_log(avctx, AV_LOG_WARNING, "Unknown data type for header variable %s\n", value_name);
141     }
142     return -1;
143 }
144
145 static int decode_frame(AVCodecContext *avctx,
146                         void *data,
147                         int *data_size,
148                         AVPacket *avpkt)
149 {
150     const uint8_t *buf      = avpkt->data;
151     unsigned int   buf_size = avpkt->size;
152     const uint8_t *buf_end  = buf + buf_size;
153
154     EXRContext *const s = avctx->priv_data;
155     AVFrame *picture  = data;
156     AVFrame *const p = &s->picture;
157     uint8_t *ptr;
158
159     int i, x, y, stride, magic_number, version_flag;
160     int w = 0;
161     int h = 0;
162     unsigned int xmin   = ~0;
163     unsigned int xmax   = ~0;
164     unsigned int ymin   = ~0;
165     unsigned int ymax   = ~0;
166     unsigned int xdelta = ~0;
167
168     unsigned int current_channel_offset = 0;
169
170     s->channel_offsets[0] = -1;
171     s->channel_offsets[1] = -1;
172     s->channel_offsets[2] = -1;
173     s->channel_offsets[3] = -1;
174     s->bits_per_color_id = -1;
175
176     if (buf_end - buf < 10) {
177         av_log(avctx, AV_LOG_ERROR, "Too short header to parse\n");
178         return -1;
179     }
180
181     magic_number = bytestream_get_le32(&buf);
182     if (magic_number != 20000630) { // As per documentation of OpenEXR it's supposed to be int 20000630 little-endian
183         av_log(avctx, AV_LOG_ERROR, "Wrong magic number %d\n", magic_number);
184         return -1;
185     }
186
187     version_flag = bytestream_get_le32(&buf);
188     if ((version_flag & 0x200) == 0x200) {
189         av_log(avctx, AV_LOG_ERROR, "Tile based images are not supported\n");
190         return -1;
191     }
192
193     // Parse the header
194     while (buf < buf_end && buf[0]) {
195         unsigned int variable_buffer_data_size;
196         // Process the channel list
197         if (check_header_variable(avctx, &buf, buf_end, "channels", "chlist", 38, &variable_buffer_data_size) >= 0) {
198             const uint8_t *channel_list_end;
199             if (!variable_buffer_data_size)
200                 return -1;
201
202             channel_list_end = buf + variable_buffer_data_size;
203             while (channel_list_end - buf >= 19) {
204                 int current_bits_per_color_id = -1;
205                 int channel_index = -1;
206
207                 if (!strcmp(buf, "R"))
208                     channel_index = 0;
209                 if (!strcmp(buf, "G"))
210                     channel_index = 1;
211                 if (!strcmp(buf, "B"))
212                     channel_index = 2;
213                 if (!strcmp(buf, "A"))
214                     channel_index = 3;
215
216                 while (bytestream_get_byte(&buf) && buf < channel_list_end)
217                     continue; /* skip */
218
219                 if (channel_list_end - * &buf < 4) {
220                     av_log(avctx, AV_LOG_ERROR, "Incomplete header\n");
221                     return -1;
222                 }
223
224                 current_bits_per_color_id = bytestream_get_le32(&buf);
225                 if (current_bits_per_color_id > 2) {
226                     av_log(avctx, AV_LOG_ERROR, "Unknown color format\n");
227                     return -1;
228                 }
229
230                 if (channel_index >= 0) {
231                     if (s->bits_per_color_id != -1 && s->bits_per_color_id != current_bits_per_color_id) {
232                         av_log(avctx, AV_LOG_ERROR, "RGB channels not of the same depth\n");
233                         return -1;
234                     }
235                     s->bits_per_color_id  = current_bits_per_color_id;
236                     s->channel_offsets[channel_index] = current_channel_offset;
237                 }
238
239                 current_channel_offset += 1 << current_bits_per_color_id;
240                 buf += 12;
241             }
242
243             /* Check if all channels are set with an offset or if the channels
244              * are causing an overflow  */
245
246             if (FFMIN3(s->channel_offsets[0],
247                        s->channel_offsets[1],
248                        s->channel_offsets[2]) < 0) {
249                 if (s->channel_offsets[0] < 0)
250                     av_log(avctx, AV_LOG_ERROR, "Missing red channel\n");
251                 if (s->channel_offsets[1] < 0)
252                     av_log(avctx, AV_LOG_ERROR, "Missing green channel\n");
253                 if (s->channel_offsets[2] < 0)
254                     av_log(avctx, AV_LOG_ERROR, "Missing blue channel\n");
255                 return -1;
256             }
257
258             buf = channel_list_end;
259             continue;
260         }
261
262         // Process the dataWindow variable
263         if (check_header_variable(avctx, &buf, buf_end, "dataWindow", "box2i", 31, &variable_buffer_data_size) >= 0) {
264             if (!variable_buffer_data_size)
265                 return -1;
266
267             xmin = AV_RL32(buf);
268             ymin = AV_RL32(buf + 4);
269             xmax = AV_RL32(buf + 8);
270             ymax = AV_RL32(buf + 12);
271             xdelta = (xmax-xmin) + 1;
272
273             buf += variable_buffer_data_size;
274             continue;
275         }
276
277         // Process the displayWindow variable
278         if (check_header_variable(avctx, &buf, buf_end, "displayWindow", "box2i", 34, &variable_buffer_data_size) >= 0) {
279             if (!variable_buffer_data_size)
280                 return -1;
281
282             w = AV_RL32(buf + 8) + 1;
283             h = AV_RL32(buf + 12) + 1;
284
285             buf += variable_buffer_data_size;
286             continue;
287         }
288
289         // Process the lineOrder variable
290         if (check_header_variable(avctx, &buf, buf_end, "lineOrder", "lineOrder", 25, &variable_buffer_data_size) >= 0) {
291             if (!variable_buffer_data_size)
292                 return -1;
293
294             if (*buf) {
295                 av_log(avctx, AV_LOG_ERROR, "Doesn't support this line order : %d\n", *buf);
296                 return -1;
297             }
298
299             buf += variable_buffer_data_size;
300             continue;
301         }
302
303         // Process the pixelAspectRatio variable
304         if (check_header_variable(avctx, &buf, buf_end, "pixelAspectRatio", "float", 31, &variable_buffer_data_size) >= 0) {
305             if (!variable_buffer_data_size)
306                 return -1;
307
308             avctx->sample_aspect_ratio = av_d2q(av_int2float(AV_RL32(buf)), 255);
309
310             buf += variable_buffer_data_size;
311             continue;
312         }
313
314         // Process the compression variable
315         if (check_header_variable(avctx, &buf, buf_end, "compression", "compression", 29, &variable_buffer_data_size) >= 0) {
316             if (!variable_buffer_data_size)
317                 return -1;
318
319             s->compr = *buf;
320             switch (s->compr) {
321             case EXR_RAW:
322                 break;
323             case EXR_RLE:
324             case EXR_ZIP1:
325             case EXR_ZIP16:
326             case EXR_PIZ:
327             case EXR_B44:
328             default:
329                 av_log(avctx, AV_LOG_ERROR, "Compression type %d is not supported\n", s->compr);
330                 return -1;
331             }
332
333             buf += variable_buffer_data_size;
334             continue;
335         }
336
337         // Check if there is enough bytes for a header
338         if (buf_end - buf <= 9) {
339             av_log(avctx, AV_LOG_ERROR, "Incomplete header\n");
340             return -1;
341         }
342
343         // Process unknown variables
344         for (i = 0; i < 2; i++) {
345             // Skip variable name/type
346             while (++buf < buf_end)
347                 if (buf[0] == 0x0)
348                     break;
349         }
350         buf++;
351         // Skip variable length
352         if (buf_end - buf >= 5) {
353             variable_buffer_data_size = get_header_variable_length(&buf, buf_end);
354             if (!variable_buffer_data_size) {
355                 av_log(avctx, AV_LOG_ERROR, "Incomplete header\n");
356                 return -1;
357             }
358             buf += variable_buffer_data_size;
359         }
360     }
361
362     if (buf >= buf_end) {
363         av_log(avctx, AV_LOG_ERROR, "Incomplete frame\n");
364         return -1;
365     }
366     buf++;
367
368     switch (s->bits_per_color_id) {
369     case 2: // 32-bit
370     case 1: // 16-bit
371         if (s->channel_offsets[3] >= 0)
372             avctx->pix_fmt = PIX_FMT_RGBA64;
373         else
374             avctx->pix_fmt = PIX_FMT_RGB48;
375         break;
376     // 8-bit
377     case 0:
378         av_log_missing_feature(avctx, "8-bit OpenEXR", 1);
379         return -1;
380     default:
381         av_log(avctx, AV_LOG_ERROR, "Unknown color format : %d\n", s->bits_per_color_id);
382         return -1;
383     }
384
385     if (s->picture.data[0])
386         avctx->release_buffer(avctx, &s->picture);
387     if (av_image_check_size(w, h, 0, avctx))
388         return -1;
389
390     // Verify the xmin, xmax, ymin, ymax and xdelta before setting the actual image size
391     if (xmin > xmax || ymin > ymax || xdelta != xmax - xmin + 1 || xmax >= w || ymax >= h) {
392         av_log(avctx, AV_LOG_ERROR, "Wrong sizing or missing size information\n");
393         return -1;
394     }
395
396     if (w != avctx->width || h != avctx->height) {
397         avcodec_set_dimensions(avctx, w, h);
398     }
399
400     if (avctx->get_buffer(avctx, p) < 0) {
401         av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
402         return -1;
403     }
404
405     ptr    = p->data[0];
406     stride = p->linesize[0];
407
408     // Zero out the start if ymin is not 0
409     for (y = 0; y < ymin; y++) {
410         memset(ptr, 0, avctx->width * 2 * av_pix_fmt_descriptors[avctx->pix_fmt].nb_components);
411         ptr += stride;
412     }
413
414     // Process the actual lines
415     for (y = ymin; y <= ymax; y++) {
416         uint16_t *ptr_x = (uint16_t *)ptr;
417         if (buf_end - buf > 8) {
418             /* Read the lineoffset from the line offset table and add 8 bytes
419                to skip the coordinates and data size fields */
420             const uint64_t line_offset = bytestream_get_le64(&buf) + 8;
421             // Check if the buffer has the required bytes needed from the offset
422             if (line_offset > avpkt->size - xdelta * current_channel_offset) {
423                 // Line offset is probably wrong and not inside the buffer
424                 av_log(avctx, AV_LOG_WARNING, "Line offset for line %d is out of reach setting it to black\n", y);
425                 memset(ptr_x, 0, avctx->width * 2 * av_pix_fmt_descriptors[avctx->pix_fmt].nb_components);
426             } else {
427                 const uint8_t *red_channel_buffer   = avpkt->data + line_offset + xdelta * s->channel_offsets[0];
428                 const uint8_t *green_channel_buffer = avpkt->data + line_offset + xdelta * s->channel_offsets[1];
429                 const uint8_t *blue_channel_buffer  = avpkt->data + line_offset + xdelta * s->channel_offsets[2];
430                 const uint8_t *alpha_channel_buffer = 0;
431
432                 if (s->channel_offsets[3] >= 0)
433                     alpha_channel_buffer = avpkt->data + line_offset + xdelta * s->channel_offsets[3];
434
435                 // Zero out the start if xmin is not 0
436                 memset(ptr_x, 0, xmin * 2 * av_pix_fmt_descriptors[avctx->pix_fmt].nb_components);
437                 ptr_x += xmin * av_pix_fmt_descriptors[avctx->pix_fmt].nb_components;
438                 if (s->bits_per_color_id == 2) {
439                     // 32-bit
440                     for (x = 0; x < xdelta; x++) {
441                         *ptr_x++ = exr_flt2uint(bytestream_get_le32(&red_channel_buffer));
442                         *ptr_x++ = exr_flt2uint(bytestream_get_le32(&green_channel_buffer));
443                         *ptr_x++ = exr_flt2uint(bytestream_get_le32(&blue_channel_buffer));
444                         if (alpha_channel_buffer)
445                             *ptr_x++ = exr_flt2uint(bytestream_get_le32(&alpha_channel_buffer));
446                     }
447                 } else {
448                     // 16-bit
449                     for (x = 0; x < xdelta; x++) {
450                         *ptr_x++ = exr_halflt2uint(bytestream_get_le16(&red_channel_buffer));
451                         *ptr_x++ = exr_halflt2uint(bytestream_get_le16(&green_channel_buffer));
452                         *ptr_x++ = exr_halflt2uint(bytestream_get_le16(&blue_channel_buffer));
453                         if (alpha_channel_buffer)
454                             *ptr_x++ = exr_halflt2uint(bytestream_get_le16(&alpha_channel_buffer));
455                     }
456                 }
457
458                 // Zero out the end if xmax+1 is not w
459                 memset(ptr_x, 0, (avctx->width - (xmax + 1)) * 2 * av_pix_fmt_descriptors[avctx->pix_fmt].nb_components);
460                 ptr_x += (avctx->width - (xmax + 1)) * av_pix_fmt_descriptors[avctx->pix_fmt].nb_components;
461
462             }
463             // Move to next line
464             ptr += stride;
465         }
466     }
467
468     // Zero out the end if ymax+1 is not h
469     for (y = ymax + 1; y < avctx->height; y++) {
470         memset(ptr, 0, avctx->width * 2 * av_pix_fmt_descriptors[avctx->pix_fmt].nb_components);
471         ptr += stride;
472     }
473
474     *picture   = s->picture;
475     *data_size = sizeof(AVPicture);
476
477     return buf_size;
478 }
479
480 static av_cold int decode_init(AVCodecContext *avctx)
481 {
482     EXRContext *s = avctx->priv_data;
483     avcodec_get_frame_defaults(&s->picture);
484     avctx->coded_frame = &s->picture;
485     return 0;
486 }
487
488 static av_cold int decode_end(AVCodecContext *avctx)
489 {
490     EXRContext *s = avctx->priv_data;
491     if (s->picture.data[0])
492         avctx->release_buffer(avctx, &s->picture);
493
494     return 0;
495 }
496
497 AVCodec ff_exr_decoder = {
498     .name               = "exr",
499     .type               = AVMEDIA_TYPE_VIDEO,
500     .id                 = CODEC_ID_EXR,
501     .priv_data_size     = sizeof(EXRContext),
502     .init               = decode_init,
503     .close              = decode_end,
504     .decode             = decode_frame,
505     .capabilities       = CODEC_CAP_DR1,
506     .long_name          = NULL_IF_CONFIG_SMALL("OpenEXR image"),
507 };