Fix crop of some YUV content.
[dcpomatic.git] / src / lib / image.cc
1 /*
2     Copyright (C) 2012-2015 Carl Hetherington <cth@carlh.net>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 /** @file src/image.cc
21  *  @brief A class to describe a video image.
22  */
23
24 #include "image.h"
25 #include "exceptions.h"
26 #include "timer.h"
27 #include "rect.h"
28 #include "util.h"
29 #include "md5_digester.h"
30 #include "dcpomatic_socket.h"
31 extern "C" {
32 #include <libswscale/swscale.h>
33 #include <libavutil/pixfmt.h>
34 #include <libavutil/pixdesc.h>
35 }
36 #include <iostream>
37
38 #include "i18n.h"
39
40 using std::string;
41 using std::min;
42 using std::cout;
43 using std::cerr;
44 using std::list;
45 using boost::shared_ptr;
46 using dcp::Size;
47
48 int
49 Image::line_factor (int n) const
50 {
51         if (n == 0) {
52                 return 1;
53         }
54
55         AVPixFmtDescriptor const * d = av_pix_fmt_desc_get(_pixel_format);
56         if (!d) {
57                 throw PixelFormatError ("line_factor()", _pixel_format);
58         }
59
60         return pow (2.0f, d->log2_chroma_h);
61 }
62
63 /** @param n Component index.
64  *  @return Number of lines in the image for the given component.
65  */
66 int
67 Image::lines (int n) const
68 {
69         return rint (ceil (static_cast<double>(size().height) / line_factor (n)));
70 }
71
72 /** @return Number of components */
73 int
74 Image::components () const
75 {
76         AVPixFmtDescriptor const * d = av_pix_fmt_desc_get(_pixel_format);
77         if (!d) {
78                 throw PixelFormatError ("components()", _pixel_format);
79         }
80
81         if ((d->flags & PIX_FMT_PLANAR) == 0) {
82                 return 1;
83         }
84
85         return d->nb_components;
86 }
87
88 /** Crop this image, scale it to `inter_size' and then place it in a black frame of `out_size' */
89 shared_ptr<Image>
90 Image::crop_scale_window (
91         Crop crop, dcp::Size inter_size, dcp::Size out_size, dcp::YUVToRGB yuv_to_rgb, AVPixelFormat out_format, bool out_aligned
92         ) const
93 {
94         /* Empirical testing suggests that sws_scale() will crash if
95            the input image is not aligned.
96         */
97         DCPOMATIC_ASSERT (aligned ());
98
99         DCPOMATIC_ASSERT (out_size.width >= inter_size.width);
100         DCPOMATIC_ASSERT (out_size.height >= inter_size.height);
101
102         /* Here's an image of out_size */
103         shared_ptr<Image> out (new Image (out_format, out_size, out_aligned));
104         out->make_black ();
105
106         /* Size of the image after any crop */
107         dcp::Size const cropped_size = crop.apply (size ());
108
109         /* Scale context for a scale from cropped_size to inter_size */
110         struct SwsContext* scale_context = sws_getContext (
111                         cropped_size.width, cropped_size.height, pixel_format(),
112                         inter_size.width, inter_size.height, out_format,
113                         SWS_BICUBIC, 0, 0, 0
114                 );
115
116         if (!scale_context) {
117                 throw StringError (N_("Could not allocate SwsContext"));
118         }
119
120         DCPOMATIC_ASSERT (yuv_to_rgb < dcp::YUV_TO_RGB_COUNT);
121         int const lut[dcp::YUV_TO_RGB_COUNT] = {
122                 SWS_CS_ITU601,
123                 SWS_CS_ITU709
124         };
125
126         sws_setColorspaceDetails (
127                 scale_context,
128                 sws_getCoefficients (lut[yuv_to_rgb]), 0,
129                 sws_getCoefficients (lut[yuv_to_rgb]), 0,
130                 0, 1 << 16, 1 << 16
131                 );
132
133         AVPixFmtDescriptor const * desc = av_pix_fmt_desc_get (_pixel_format);
134         if (!desc) {
135                 throw PixelFormatError ("crop_scale_window()", _pixel_format);
136         }
137
138         /* Prepare input data pointers with crop */
139         uint8_t* scale_in_data[components()];
140         for (int c = 0; c < components(); ++c) {
141                 /* To work out the crop in bytes, start by multiplying
142                    the crop by the (average) bytes per pixel.  Then
143                    round down so that we don't crop a subsampled pixel until
144                    we've cropped all of its Y-channel pixels.
145                 */
146                 int const x = int (rint (bytes_per_pixel(c) * crop.left)) & ~ ((int) desc->log2_chroma_w);
147                 scale_in_data[c] = data()[c] + x + stride()[c] * (crop.top / line_factor(c));
148         }
149
150         /* Corner of the image within out_size */
151         Position<int> const corner ((out_size.width - inter_size.width) / 2, (out_size.height - inter_size.height) / 2);
152
153         uint8_t* scale_out_data[out->components()];
154         for (int c = 0; c < out->components(); ++c) {
155                 scale_out_data[c] = out->data()[c] + int (rint (out->bytes_per_pixel(c) * corner.x)) + out->stride()[c] * corner.y;
156         }
157
158         sws_scale (
159                 scale_context,
160                 scale_in_data, stride(),
161                 0, cropped_size.height,
162                 scale_out_data, out->stride()
163                 );
164
165         sws_freeContext (scale_context);
166
167         return out;
168 }
169
170 shared_ptr<Image>
171 Image::scale (dcp::Size out_size, dcp::YUVToRGB yuv_to_rgb, AVPixelFormat out_format, bool out_aligned) const
172 {
173         /* Empirical testing suggests that sws_scale() will crash if
174            the input image is not aligned.
175         */
176         DCPOMATIC_ASSERT (aligned ());
177
178         shared_ptr<Image> scaled (new Image (out_format, out_size, out_aligned));
179
180         struct SwsContext* scale_context = sws_getContext (
181                 size().width, size().height, pixel_format(),
182                 out_size.width, out_size.height, out_format,
183                 SWS_BICUBIC, 0, 0, 0
184                 );
185
186         DCPOMATIC_ASSERT (yuv_to_rgb < dcp::YUV_TO_RGB_COUNT);
187         int const lut[dcp::YUV_TO_RGB_COUNT] = {
188                 SWS_CS_ITU601,
189                 SWS_CS_ITU709
190         };
191
192         sws_setColorspaceDetails (
193                 scale_context,
194                 sws_getCoefficients (lut[yuv_to_rgb]), 0,
195                 sws_getCoefficients (lut[yuv_to_rgb]), 0,
196                 0, 1 << 16, 1 << 16
197                 );
198
199         sws_scale (
200                 scale_context,
201                 data(), stride(),
202                 0, size().height,
203                 scaled->data(), scaled->stride()
204                 );
205
206         sws_freeContext (scale_context);
207
208         return scaled;
209 }
210
211 shared_ptr<Image>
212 Image::crop (Crop crop, bool aligned) const
213 {
214         dcp::Size cropped_size = crop.apply (size ());
215         shared_ptr<Image> out (new Image (pixel_format(), cropped_size, aligned));
216
217         for (int c = 0; c < components(); ++c) {
218                 int const crop_left_in_bytes = bytes_per_pixel(c) * crop.left;
219                 /* bytes_per_pixel() could be a fraction; in this case the stride will be rounded
220                    up, and we need to make sure that we copy over the width (up to the stride)
221                    rather than short of the width; hence the ceil() here.
222                 */
223                 int const cropped_width_in_bytes = ceil (bytes_per_pixel(c) * cropped_size.width);
224
225                 /* Start of the source line, cropped from the top but not the left */
226                 uint8_t* in_p = data()[c] + (crop.top / out->line_factor(c)) * stride()[c];
227                 uint8_t* out_p = out->data()[c];
228
229                 for (int y = 0; y < out->lines(c); ++y) {
230                         memcpy (out_p, in_p + crop_left_in_bytes, cropped_width_in_bytes);
231                         in_p += stride()[c];
232                         out_p += out->stride()[c];
233                 }
234         }
235
236         return out;
237 }
238
239 /** Blacken a YUV image whose bits per pixel is rounded up to 16 */
240 void
241 Image::yuv_16_black (uint16_t v, bool alpha)
242 {
243         memset (data()[0], 0, lines(0) * stride()[0]);
244         for (int i = 1; i < 3; ++i) {
245                 int16_t* p = reinterpret_cast<int16_t*> (data()[i]);
246                 for (int y = 0; y < lines(i); ++y) {
247                         /* We divide by 2 here because we are writing 2 bytes at a time */
248                         for (int x = 0; x < line_size()[i] / 2; ++x) {
249                                 p[x] = v;
250                         }
251                         p += stride()[i] / 2;
252                 }
253         }
254
255         if (alpha) {
256                 memset (data()[3], 0, lines(3) * stride()[3]);
257         }
258 }
259
260 uint16_t
261 Image::swap_16 (uint16_t v)
262 {
263         return ((v >> 8) & 0xff) | ((v & 0xff) << 8);
264 }
265
266 void
267 Image::make_black ()
268 {
269         /* U/V black value for 8-bit colour */
270         static uint8_t const eight_bit_uv =     (1 << 7) - 1;
271         /* U/V black value for 9-bit colour */
272         static uint16_t const nine_bit_uv =     (1 << 8) - 1;
273         /* U/V black value for 10-bit colour */
274         static uint16_t const ten_bit_uv =      (1 << 9) - 1;
275         /* U/V black value for 16-bit colour */
276         static uint16_t const sixteen_bit_uv =  (1 << 15) - 1;
277
278         switch (_pixel_format) {
279         case PIX_FMT_YUV420P:
280         case PIX_FMT_YUV422P:
281         case PIX_FMT_YUV444P:
282         case PIX_FMT_YUV411P:
283                 memset (data()[0], 0, lines(0) * stride()[0]);
284                 memset (data()[1], eight_bit_uv, lines(1) * stride()[1]);
285                 memset (data()[2], eight_bit_uv, lines(2) * stride()[2]);
286                 break;
287
288         case PIX_FMT_YUVJ420P:
289         case PIX_FMT_YUVJ422P:
290         case PIX_FMT_YUVJ444P:
291                 memset (data()[0], 0, lines(0) * stride()[0]);
292                 memset (data()[1], eight_bit_uv + 1, lines(1) * stride()[1]);
293                 memset (data()[2], eight_bit_uv + 1, lines(2) * stride()[2]);
294                 break;
295
296         case PIX_FMT_YUV422P9LE:
297         case PIX_FMT_YUV444P9LE:
298                 yuv_16_black (nine_bit_uv, false);
299                 break;
300
301         case PIX_FMT_YUV422P9BE:
302         case PIX_FMT_YUV444P9BE:
303                 yuv_16_black (swap_16 (nine_bit_uv), false);
304                 break;
305
306         case PIX_FMT_YUV422P10LE:
307         case PIX_FMT_YUV444P10LE:
308                 yuv_16_black (ten_bit_uv, false);
309                 break;
310
311         case PIX_FMT_YUV422P16LE:
312         case PIX_FMT_YUV444P16LE:
313                 yuv_16_black (sixteen_bit_uv, false);
314                 break;
315
316         case PIX_FMT_YUV444P10BE:
317         case PIX_FMT_YUV422P10BE:
318                 yuv_16_black (swap_16 (ten_bit_uv), false);
319                 break;
320
321         case AV_PIX_FMT_YUVA420P9BE:
322         case AV_PIX_FMT_YUVA422P9BE:
323         case AV_PIX_FMT_YUVA444P9BE:
324                 yuv_16_black (swap_16 (nine_bit_uv), true);
325                 break;
326
327         case AV_PIX_FMT_YUVA420P9LE:
328         case AV_PIX_FMT_YUVA422P9LE:
329         case AV_PIX_FMT_YUVA444P9LE:
330                 yuv_16_black (nine_bit_uv, true);
331                 break;
332
333         case AV_PIX_FMT_YUVA420P10BE:
334         case AV_PIX_FMT_YUVA422P10BE:
335         case AV_PIX_FMT_YUVA444P10BE:
336                 yuv_16_black (swap_16 (ten_bit_uv), true);
337                 break;
338
339         case AV_PIX_FMT_YUVA420P10LE:
340         case AV_PIX_FMT_YUVA422P10LE:
341         case AV_PIX_FMT_YUVA444P10LE:
342                 yuv_16_black (ten_bit_uv, true);
343                 break;
344
345         case AV_PIX_FMT_YUVA420P16BE:
346         case AV_PIX_FMT_YUVA422P16BE:
347         case AV_PIX_FMT_YUVA444P16BE:
348                 yuv_16_black (swap_16 (sixteen_bit_uv), true);
349                 break;
350
351         case AV_PIX_FMT_YUVA420P16LE:
352         case AV_PIX_FMT_YUVA422P16LE:
353         case AV_PIX_FMT_YUVA444P16LE:
354                 yuv_16_black (sixteen_bit_uv, true);
355                 break;
356
357         case PIX_FMT_RGB24:
358         case PIX_FMT_ARGB:
359         case PIX_FMT_RGBA:
360         case PIX_FMT_ABGR:
361         case PIX_FMT_BGRA:
362         case PIX_FMT_RGB555LE:
363         case PIX_FMT_RGB48LE:
364         case PIX_FMT_RGB48BE:
365                 memset (data()[0], 0, lines(0) * stride()[0]);
366                 break;
367
368         case PIX_FMT_UYVY422:
369         {
370                 int const Y = lines(0);
371                 int const X = line_size()[0];
372                 uint8_t* p = data()[0];
373                 for (int y = 0; y < Y; ++y) {
374                         for (int x = 0; x < X / 4; ++x) {
375                                 *p++ = eight_bit_uv; // Cb
376                                 *p++ = 0;            // Y0
377                                 *p++ = eight_bit_uv; // Cr
378                                 *p++ = 0;            // Y1
379                         }
380                 }
381                 break;
382         }
383
384         default:
385                 throw PixelFormatError ("make_black()", _pixel_format);
386         }
387 }
388
389 void
390 Image::make_transparent ()
391 {
392         if (_pixel_format != PIX_FMT_RGBA) {
393                 throw PixelFormatError ("make_transparent()", _pixel_format);
394         }
395
396         memset (data()[0], 0, lines(0) * stride()[0]);
397 }
398
399 void
400 Image::alpha_blend (shared_ptr<const Image> other, Position<int> position)
401 {
402         DCPOMATIC_ASSERT (other->pixel_format() == PIX_FMT_RGBA);
403         int const other_bpp = 4;
404
405         int start_tx = position.x;
406         int start_ox = 0;
407
408         if (start_tx < 0) {
409                 start_ox = -start_tx;
410                 start_tx = 0;
411         }
412
413         int start_ty = position.y;
414         int start_oy = 0;
415
416         if (start_ty < 0) {
417                 start_oy = -start_ty;
418                 start_ty = 0;
419         }
420
421         switch (_pixel_format) {
422         case PIX_FMT_RGB24:
423         {
424                 int const this_bpp = 3;
425                 for (int ty = start_ty, oy = start_oy; ty < size().height && oy < other->size().height; ++ty, ++oy) {
426                         uint8_t* tp = data()[0] + ty * stride()[0] + start_tx * this_bpp;
427                         uint8_t* op = other->data()[0] + oy * other->stride()[0];
428                         for (int tx = start_tx, ox = start_ox; tx < size().width && ox < other->size().width; ++tx, ++ox) {
429                                 float const alpha = float (op[3]) / 255;
430                                 tp[0] = op[0] * alpha + tp[0] * (1 - alpha);
431                                 tp[1] = op[1] * alpha + tp[1] * (1 - alpha);
432                                 tp[2] = op[2] * alpha + tp[2] * (1 - alpha);
433
434                                 tp += this_bpp;
435                                 op += other_bpp;
436                         }
437                 }
438                 break;
439         }
440         case PIX_FMT_BGRA:
441         case PIX_FMT_RGBA:
442         {
443                 int const this_bpp = 4;
444                 for (int ty = start_ty, oy = start_oy; ty < size().height && oy < other->size().height; ++ty, ++oy) {
445                         uint8_t* tp = data()[0] + ty * stride()[0] + start_tx * this_bpp;
446                         uint8_t* op = other->data()[0] + oy * other->stride()[0];
447                         for (int tx = start_tx, ox = start_ox; tx < size().width && ox < other->size().width; ++tx, ++ox) {
448                                 float const alpha = float (op[3]) / 255;
449                                 tp[0] = op[0] * alpha + tp[0] * (1 - alpha);
450                                 tp[1] = op[1] * alpha + tp[1] * (1 - alpha);
451                                 tp[2] = op[2] * alpha + tp[2] * (1 - alpha);
452                                 tp[3] = op[3] * alpha + tp[3] * (1 - alpha);
453
454                                 tp += this_bpp;
455                                 op += other_bpp;
456                         }
457                 }
458                 break;
459         }
460         case PIX_FMT_RGB48LE:
461         {
462                 int const this_bpp = 6;
463                 for (int ty = start_ty, oy = start_oy; ty < size().height && oy < other->size().height; ++ty, ++oy) {
464                         uint8_t* tp = data()[0] + ty * stride()[0] + start_tx * this_bpp;
465                         uint8_t* op = other->data()[0] + oy * other->stride()[0];
466                         for (int tx = start_tx, ox = start_ox; tx < size().width && ox < other->size().width; ++tx, ++ox) {
467                                 float const alpha = float (op[3]) / 255;
468                                 /* Blend high bytes */
469                                 tp[1] = op[0] * alpha + tp[1] * (1 - alpha);
470                                 tp[3] = op[1] * alpha + tp[3] * (1 - alpha);
471                                 tp[5] = op[2] * alpha + tp[5] * (1 - alpha);
472
473                                 tp += this_bpp;
474                                 op += other_bpp;
475                         }
476                 }
477                 break;
478         }
479         default:
480                 DCPOMATIC_ASSERT (false);
481         }
482 }
483
484 void
485 Image::copy (shared_ptr<const Image> other, Position<int> position)
486 {
487         /* Only implemented for RGB24 onto RGB24 so far */
488         DCPOMATIC_ASSERT (_pixel_format == PIX_FMT_RGB24 && other->pixel_format() == PIX_FMT_RGB24);
489         DCPOMATIC_ASSERT (position.x >= 0 && position.y >= 0);
490
491         int const N = min (position.x + other->size().width, size().width) - position.x;
492         for (int ty = position.y, oy = 0; ty < size().height && oy < other->size().height; ++ty, ++oy) {
493                 uint8_t * const tp = data()[0] + ty * stride()[0] + position.x * 3;
494                 uint8_t * const op = other->data()[0] + oy * other->stride()[0];
495                 memcpy (tp, op, N * 3);
496         }
497 }
498
499 void
500 Image::read_from_socket (shared_ptr<Socket> socket)
501 {
502         for (int i = 0; i < components(); ++i) {
503                 uint8_t* p = data()[i];
504                 for (int y = 0; y < lines(i); ++y) {
505                         socket->read (p, line_size()[i]);
506                         p += stride()[i];
507                 }
508         }
509 }
510
511 void
512 Image::write_to_socket (shared_ptr<Socket> socket) const
513 {
514         for (int i = 0; i < components(); ++i) {
515                 uint8_t* p = data()[i];
516                 for (int y = 0; y < lines(i); ++y) {
517                         socket->write (p, line_size()[i]);
518                         p += stride()[i];
519                 }
520         }
521 }
522
523
524 float
525 Image::bytes_per_pixel (int c) const
526 {
527         AVPixFmtDescriptor const * d = av_pix_fmt_desc_get(_pixel_format);
528         if (!d) {
529                 throw PixelFormatError ("bytes_per_pixel()", _pixel_format);
530         }
531
532         if (c >= components()) {
533                 return 0;
534         }
535
536         float bpp[4] = { 0, 0, 0, 0 };
537
538         bpp[0] = floor ((d->comp[0].depth_minus1 + 1 + 7) / 8);
539         if (d->nb_components > 1) {
540                 bpp[1] = floor ((d->comp[1].depth_minus1 + 1 + 7) / 8) / pow (2.0f, d->log2_chroma_w);
541         }
542         if (d->nb_components > 2) {
543                 bpp[2] = floor ((d->comp[2].depth_minus1 + 1 + 7) / 8) / pow (2.0f, d->log2_chroma_w);
544         }
545         if (d->nb_components > 3) {
546                 bpp[3] = floor ((d->comp[3].depth_minus1 + 1 + 7) / 8) / pow (2.0f, d->log2_chroma_w);
547         }
548
549         if ((d->flags & PIX_FMT_PLANAR) == 0) {
550                 /* Not planar; sum them up */
551                 return bpp[0] + bpp[1] + bpp[2] + bpp[3];
552         }
553
554         return bpp[c];
555 }
556
557 /** Construct a Image of a given size and format, allocating memory
558  *  as required.
559  *
560  *  @param p Pixel format.
561  *  @param s Size in pixels.
562  */
563 Image::Image (AVPixelFormat p, dcp::Size s, bool aligned)
564         : _size (s)
565         , _pixel_format (p)
566         , _aligned (aligned)
567 {
568         allocate ();
569 }
570
571 void
572 Image::allocate ()
573 {
574         _data = (uint8_t **) wrapped_av_malloc (4 * sizeof (uint8_t *));
575         _data[0] = _data[1] = _data[2] = _data[3] = 0;
576
577         _line_size = (int *) wrapped_av_malloc (4 * sizeof (int));
578         _line_size[0] = _line_size[1] = _line_size[2] = _line_size[3] = 0;
579
580         _stride = (int *) wrapped_av_malloc (4 * sizeof (int));
581         _stride[0] = _stride[1] = _stride[2] = _stride[3] = 0;
582
583         for (int i = 0; i < components(); ++i) {
584                 _line_size[i] = ceil (_size.width * bytes_per_pixel(i));
585                 _stride[i] = stride_round_up (i, _line_size, _aligned ? 32 : 1);
586
587                 /* The assembler function ff_rgb24ToY_avx (in libswscale/x86/input.asm)
588                    uses a 16-byte fetch to read three bytes (R/G/B) of image data.
589                    Hence on the last pixel of the last line it reads over the end of
590                    the actual data by 1 byte.  If the width of an image is a multiple
591                    of the stride alignment there will be no padding at the end of image lines.
592                    OS X crashes on this illegal read, though other operating systems don't
593                    seem to mind.  The nasty + 1 in this malloc makes sure there is always a byte
594                    for that instruction to read safely.
595
596                    Further to the above, valgrind is now telling me that ff_rgb24ToY_ssse3
597                    over-reads by more then _avx.  I can't follow the code to work out how much,
598                    so I'll just over-allocate by 32 bytes and have done with it.  Empirical
599                    testing suggests that it works.
600                 */
601                 _data[i] = (uint8_t *) wrapped_av_malloc (_stride[i] * lines (i) + 32);
602         }
603 }
604
605 Image::Image (Image const & other)
606         : _size (other._size)
607         , _pixel_format (other._pixel_format)
608         , _aligned (other._aligned)
609 {
610         allocate ();
611
612         for (int i = 0; i < components(); ++i) {
613                 uint8_t* p = _data[i];
614                 uint8_t* q = other._data[i];
615                 for (int j = 0; j < lines(i); ++j) {
616                         memcpy (p, q, _line_size[i]);
617                         p += stride()[i];
618                         q += other.stride()[i];
619                 }
620         }
621 }
622
623 Image::Image (AVFrame* frame)
624         : _size (frame->width, frame->height)
625         , _pixel_format (static_cast<AVPixelFormat> (frame->format))
626         , _aligned (true)
627 {
628         allocate ();
629
630         for (int i = 0; i < components(); ++i) {
631                 uint8_t* p = _data[i];
632                 uint8_t* q = frame->data[i];
633                 for (int j = 0; j < lines(i); ++j) {
634                         memcpy (p, q, _line_size[i]);
635                         p += stride()[i];
636                         /* AVFrame's linesize is what we call `stride' */
637                         q += frame->linesize[i];
638                 }
639         }
640 }
641
642 Image::Image (shared_ptr<const Image> other, bool aligned)
643         : _size (other->_size)
644         , _pixel_format (other->_pixel_format)
645         , _aligned (aligned)
646 {
647         allocate ();
648
649         for (int i = 0; i < components(); ++i) {
650                 DCPOMATIC_ASSERT (line_size()[i] == other->line_size()[i]);
651                 uint8_t* p = _data[i];
652                 uint8_t* q = other->data()[i];
653                 for (int j = 0; j < lines(i); ++j) {
654                         memcpy (p, q, line_size()[i]);
655                         p += stride()[i];
656                         q += other->stride()[i];
657                 }
658         }
659 }
660
661 Image&
662 Image::operator= (Image const & other)
663 {
664         if (this == &other) {
665                 return *this;
666         }
667
668         Image tmp (other);
669         swap (tmp);
670         return *this;
671 }
672
673 void
674 Image::swap (Image & other)
675 {
676         std::swap (_size, other._size);
677         std::swap (_pixel_format, other._pixel_format);
678
679         for (int i = 0; i < 4; ++i) {
680                 std::swap (_data[i], other._data[i]);
681                 std::swap (_line_size[i], other._line_size[i]);
682                 std::swap (_stride[i], other._stride[i]);
683         }
684
685         std::swap (_aligned, other._aligned);
686 }
687
688 /** Destroy a Image */
689 Image::~Image ()
690 {
691         for (int i = 0; i < components(); ++i) {
692                 av_free (_data[i]);
693         }
694
695         av_free (_data);
696         av_free (_line_size);
697         av_free (_stride);
698 }
699
700 uint8_t * const *
701 Image::data () const
702 {
703         return _data;
704 }
705
706 int *
707 Image::line_size () const
708 {
709         return _line_size;
710 }
711
712 int const *
713 Image::stride () const
714 {
715         return _stride;
716 }
717
718 dcp::Size
719 Image::size () const
720 {
721         return _size;
722 }
723
724 bool
725 Image::aligned () const
726 {
727         return _aligned;
728 }
729
730 PositionImage
731 merge (list<PositionImage> images)
732 {
733         if (images.empty ()) {
734                 return PositionImage ();
735         }
736
737         if (images.size() == 1) {
738                 return images.front ();
739         }
740
741         dcpomatic::Rect<int> all (images.front().position, images.front().image->size().width, images.front().image->size().height);
742         for (list<PositionImage>::const_iterator i = images.begin(); i != images.end(); ++i) {
743                 all.extend (dcpomatic::Rect<int> (i->position, i->image->size().width, i->image->size().height));
744         }
745
746         shared_ptr<Image> merged (new Image (images.front().image->pixel_format (), dcp::Size (all.width, all.height), true));
747         merged->make_transparent ();
748         for (list<PositionImage>::const_iterator i = images.begin(); i != images.end(); ++i) {
749                 merged->alpha_blend (i->image, i->position - all.position());
750         }
751
752         return PositionImage (merged, all.position ());
753 }
754
755 bool
756 operator== (Image const & a, Image const & b)
757 {
758         if (a.components() != b.components() || a.pixel_format() != b.pixel_format() || a.aligned() != b.aligned()) {
759                 return false;
760         }
761
762         for (int c = 0; c < a.components(); ++c) {
763                 if (a.lines(c) != b.lines(c) || a.line_size()[c] != b.line_size()[c] || a.stride()[c] != b.stride()[c]) {
764                         return false;
765                 }
766
767                 uint8_t* p = a.data()[c];
768                 uint8_t* q = b.data()[c];
769                 for (int y = 0; y < a.lines(c); ++y) {
770                         if (memcmp (p, q, a.line_size()[c]) != 0) {
771                                 return false;
772                         }
773
774                         p += a.stride()[c];
775                         q += b.stride()[c];
776                 }
777         }
778
779         return true;
780 }
781
782 /** Fade the image.
783  *  @param f Amount to fade by; 0 is black, 1 is no fade.
784  */
785 void
786 Image::fade (float f)
787 {
788         switch (_pixel_format) {
789         case PIX_FMT_YUV420P:
790         case PIX_FMT_YUV422P:
791         case PIX_FMT_YUV444P:
792         case PIX_FMT_YUV411P:
793         case PIX_FMT_YUVJ420P:
794         case PIX_FMT_YUVJ422P:
795         case PIX_FMT_YUVJ444P:
796         case PIX_FMT_RGB24:
797         case PIX_FMT_ARGB:
798         case PIX_FMT_RGBA:
799         case PIX_FMT_ABGR:
800         case PIX_FMT_BGRA:
801         case PIX_FMT_RGB555LE:
802                 /* 8-bit */
803                 for (int c = 0; c < 3; ++c) {
804                         uint8_t* p = data()[c];
805                         for (int y = 0; y < lines(c); ++y) {
806                                 uint8_t* q = p;
807                                 for (int x = 0; x < line_size()[c]; ++x) {
808                                         *q = int (float (*q) * f);
809                                         ++q;
810                                 }
811                                 p += stride()[c];
812                         }
813                 }
814                 break;
815
816         case PIX_FMT_YUV422P9LE:
817         case PIX_FMT_YUV444P9LE:
818         case PIX_FMT_YUV422P10LE:
819         case PIX_FMT_YUV444P10LE:
820         case PIX_FMT_YUV422P16LE:
821         case PIX_FMT_YUV444P16LE:
822         case AV_PIX_FMT_YUVA420P9LE:
823         case AV_PIX_FMT_YUVA422P9LE:
824         case AV_PIX_FMT_YUVA444P9LE:
825         case AV_PIX_FMT_YUVA420P10LE:
826         case AV_PIX_FMT_YUVA422P10LE:
827         case AV_PIX_FMT_YUVA444P10LE:
828         case AV_PIX_FMT_RGB48LE:
829                 /* 16-bit little-endian */
830                 for (int c = 0; c < 3; ++c) {
831                         int const stride_pixels = stride()[c] / 2;
832                         int const line_size_pixels = line_size()[c] / 2;
833                         uint16_t* p = reinterpret_cast<uint16_t*> (data()[c]);
834                         for (int y = 0; y < lines(c); ++y) {
835                                 uint16_t* q = p;
836                                 for (int x = 0; x < line_size_pixels; ++x) {
837                                         *q = int (float (*q) * f);
838                                         ++q;
839                                 }
840                                 p += stride_pixels;
841                         }
842                 }
843                 break;
844
845         case PIX_FMT_YUV422P9BE:
846         case PIX_FMT_YUV444P9BE:
847         case PIX_FMT_YUV444P10BE:
848         case PIX_FMT_YUV422P10BE:
849         case AV_PIX_FMT_YUVA420P9BE:
850         case AV_PIX_FMT_YUVA422P9BE:
851         case AV_PIX_FMT_YUVA444P9BE:
852         case AV_PIX_FMT_YUVA420P10BE:
853         case AV_PIX_FMT_YUVA422P10BE:
854         case AV_PIX_FMT_YUVA444P10BE:
855         case AV_PIX_FMT_YUVA420P16BE:
856         case AV_PIX_FMT_YUVA422P16BE:
857         case AV_PIX_FMT_YUVA444P16BE:
858         case AV_PIX_FMT_RGB48BE:
859                 /* 16-bit big-endian */
860                 for (int c = 0; c < 3; ++c) {
861                         int const stride_pixels = stride()[c] / 2;
862                         int const line_size_pixels = line_size()[c] / 2;
863                         uint16_t* p = reinterpret_cast<uint16_t*> (data()[c]);
864                         for (int y = 0; y < lines(c); ++y) {
865                                 uint16_t* q = p;
866                                 for (int x = 0; x < line_size_pixels; ++x) {
867                                         *q = swap_16 (int (float (swap_16 (*q)) * f));
868                                         ++q;
869                                 }
870                                 p += stride_pixels;
871                         }
872                 }
873                 break;
874
875         case PIX_FMT_UYVY422:
876         {
877                 int const Y = lines(0);
878                 int const X = line_size()[0];
879                 uint8_t* p = data()[0];
880                 for (int y = 0; y < Y; ++y) {
881                         for (int x = 0; x < X; ++x) {
882                                 *p = int (float (*p) * f);
883                                 ++p;
884                         }
885                 }
886                 break;
887         }
888
889         default:
890                 throw PixelFormatError ("fade()", _pixel_format);
891         }
892 }