Add video waveform viewer.
[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 samples (i.e. pixels, unless sub-sampled) in each direction for this component.
65  */
66 dcp::Size
67 Image::sample_size (int n) const
68 {
69         int horizontal_factor = 1;
70         if (n > 0) {
71                 AVPixFmtDescriptor const * d = av_pix_fmt_desc_get (_pixel_format);
72                 if (!d) {
73                         throw PixelFormatError ("sample_size()", _pixel_format);
74                 }
75                 horizontal_factor = pow (2.0f, d->log2_chroma_w);
76         }
77
78         return dcp::Size (
79                 rint (ceil (static_cast<double>(size().width) / horizontal_factor)),
80                 rint (ceil (static_cast<double>(size().height) / line_factor (n)))
81                 );
82 }
83
84 int
85 Image::components () const
86 {
87         AVPixFmtDescriptor const * d = av_pix_fmt_desc_get(_pixel_format);
88         if (!d) {
89                 throw PixelFormatError ("components()", _pixel_format);
90         }
91
92         return d->nb_components;
93 }
94
95 /** @return Number of planes */
96 int
97 Image::planes () const
98 {
99         AVPixFmtDescriptor const * d = av_pix_fmt_desc_get(_pixel_format);
100         if (!d) {
101                 throw PixelFormatError ("planes()", _pixel_format);
102         }
103
104         if ((d->flags & PIX_FMT_PLANAR) == 0) {
105                 return 1;
106         }
107
108         return d->nb_components;
109 }
110
111 /** Crop this image, scale it to `inter_size' and then place it in a black frame of `out_size' */
112 shared_ptr<Image>
113 Image::crop_scale_window (
114         Crop crop, dcp::Size inter_size, dcp::Size out_size, dcp::YUVToRGB yuv_to_rgb, AVPixelFormat out_format, bool out_aligned
115         ) const
116 {
117         /* Empirical testing suggests that sws_scale() will crash if
118            the input image is not aligned.
119         */
120         DCPOMATIC_ASSERT (aligned ());
121
122         DCPOMATIC_ASSERT (out_size.width >= inter_size.width);
123         DCPOMATIC_ASSERT (out_size.height >= inter_size.height);
124
125         /* Here's an image of out_size */
126         shared_ptr<Image> out (new Image (out_format, out_size, out_aligned));
127         out->make_black ();
128
129         /* Size of the image after any crop */
130         dcp::Size const cropped_size = crop.apply (size ());
131
132         /* Scale context for a scale from cropped_size to inter_size */
133         struct SwsContext* scale_context = sws_getContext (
134                         cropped_size.width, cropped_size.height, pixel_format(),
135                         inter_size.width, inter_size.height, out_format,
136                         SWS_BICUBIC, 0, 0, 0
137                 );
138
139         if (!scale_context) {
140                 throw StringError (N_("Could not allocate SwsContext"));
141         }
142
143         DCPOMATIC_ASSERT (yuv_to_rgb < dcp::YUV_TO_RGB_COUNT);
144         int const lut[dcp::YUV_TO_RGB_COUNT] = {
145                 SWS_CS_ITU601,
146                 SWS_CS_ITU709
147         };
148
149         sws_setColorspaceDetails (
150                 scale_context,
151                 sws_getCoefficients (lut[yuv_to_rgb]), 0,
152                 sws_getCoefficients (lut[yuv_to_rgb]), 0,
153                 0, 1 << 16, 1 << 16
154                 );
155
156         AVPixFmtDescriptor const * desc = av_pix_fmt_desc_get (_pixel_format);
157         if (!desc) {
158                 throw PixelFormatError ("crop_scale_window()", _pixel_format);
159         }
160
161         /* Prepare input data pointers with crop */
162         uint8_t* scale_in_data[planes()];
163         for (int c = 0; c < planes(); ++c) {
164                 /* To work out the crop in bytes, start by multiplying
165                    the crop by the (average) bytes per pixel.  Then
166                    round down so that we don't crop a subsampled pixel until
167                    we've cropped all of its Y-channel pixels.
168                 */
169                 int const x = int (rint (bytes_per_pixel(c) * crop.left)) & ~ ((int) desc->log2_chroma_w);
170                 scale_in_data[c] = data()[c] + x + stride()[c] * (crop.top / line_factor(c));
171         }
172
173         /* Corner of the image within out_size */
174         Position<int> const corner ((out_size.width - inter_size.width) / 2, (out_size.height - inter_size.height) / 2);
175
176         uint8_t* scale_out_data[out->planes()];
177         for (int c = 0; c < out->planes(); ++c) {
178                 scale_out_data[c] = out->data()[c] + int (rint (out->bytes_per_pixel(c) * corner.x)) + out->stride()[c] * corner.y;
179         }
180
181         sws_scale (
182                 scale_context,
183                 scale_in_data, stride(),
184                 0, cropped_size.height,
185                 scale_out_data, out->stride()
186                 );
187
188         sws_freeContext (scale_context);
189
190         return out;
191 }
192
193 shared_ptr<Image>
194 Image::scale (dcp::Size out_size, dcp::YUVToRGB yuv_to_rgb, AVPixelFormat out_format, bool out_aligned) const
195 {
196         /* Empirical testing suggests that sws_scale() will crash if
197            the input image is not aligned.
198         */
199         DCPOMATIC_ASSERT (aligned ());
200
201         shared_ptr<Image> scaled (new Image (out_format, out_size, out_aligned));
202
203         struct SwsContext* scale_context = sws_getContext (
204                 size().width, size().height, pixel_format(),
205                 out_size.width, out_size.height, out_format,
206                 SWS_BICUBIC, 0, 0, 0
207                 );
208
209         DCPOMATIC_ASSERT (yuv_to_rgb < dcp::YUV_TO_RGB_COUNT);
210         int const lut[dcp::YUV_TO_RGB_COUNT] = {
211                 SWS_CS_ITU601,
212                 SWS_CS_ITU709
213         };
214
215         sws_setColorspaceDetails (
216                 scale_context,
217                 sws_getCoefficients (lut[yuv_to_rgb]), 0,
218                 sws_getCoefficients (lut[yuv_to_rgb]), 0,
219                 0, 1 << 16, 1 << 16
220                 );
221
222         sws_scale (
223                 scale_context,
224                 data(), stride(),
225                 0, size().height,
226                 scaled->data(), scaled->stride()
227                 );
228
229         sws_freeContext (scale_context);
230
231         return scaled;
232 }
233
234 /** Blacken a YUV image whose bits per pixel is rounded up to 16 */
235 void
236 Image::yuv_16_black (uint16_t v, bool alpha)
237 {
238         memset (data()[0], 0, sample_size(0).height * stride()[0]);
239         for (int i = 1; i < 3; ++i) {
240                 int16_t* p = reinterpret_cast<int16_t*> (data()[i]);
241                 int const lines = sample_size(i).height;
242                 for (int y = 0; y < lines; ++y) {
243                         /* We divide by 2 here because we are writing 2 bytes at a time */
244                         for (int x = 0; x < line_size()[i] / 2; ++x) {
245                                 p[x] = v;
246                         }
247                         p += stride()[i] / 2;
248                 }
249         }
250
251         if (alpha) {
252                 memset (data()[3], 0, sample_size(3).height * stride()[3]);
253         }
254 }
255
256 uint16_t
257 Image::swap_16 (uint16_t v)
258 {
259         return ((v >> 8) & 0xff) | ((v & 0xff) << 8);
260 }
261
262 void
263 Image::make_black ()
264 {
265         /* U/V black value for 8-bit colour */
266         static uint8_t const eight_bit_uv =     (1 << 7) - 1;
267         /* U/V black value for 9-bit colour */
268         static uint16_t const nine_bit_uv =     (1 << 8) - 1;
269         /* U/V black value for 10-bit colour */
270         static uint16_t const ten_bit_uv =      (1 << 9) - 1;
271         /* U/V black value for 16-bit colour */
272         static uint16_t const sixteen_bit_uv =  (1 << 15) - 1;
273
274         switch (_pixel_format) {
275         case PIX_FMT_YUV420P:
276         case PIX_FMT_YUV422P:
277         case PIX_FMT_YUV444P:
278         case PIX_FMT_YUV411P:
279                 memset (data()[0], 0, sample_size(0).height * stride()[0]);
280                 memset (data()[1], eight_bit_uv, sample_size(1).height * stride()[1]);
281                 memset (data()[2], eight_bit_uv, sample_size(2).height * stride()[2]);
282                 break;
283
284         case PIX_FMT_YUVJ420P:
285         case PIX_FMT_YUVJ422P:
286         case PIX_FMT_YUVJ444P:
287                 memset (data()[0], 0, sample_size(0).height * stride()[0]);
288                 memset (data()[1], eight_bit_uv + 1, sample_size(1).height * stride()[1]);
289                 memset (data()[2], eight_bit_uv + 1, sample_size(2).height * stride()[2]);
290                 break;
291
292         case PIX_FMT_YUV422P9LE:
293         case PIX_FMT_YUV444P9LE:
294                 yuv_16_black (nine_bit_uv, false);
295                 break;
296
297         case PIX_FMT_YUV422P9BE:
298         case PIX_FMT_YUV444P9BE:
299                 yuv_16_black (swap_16 (nine_bit_uv), false);
300                 break;
301
302         case PIX_FMT_YUV422P10LE:
303         case PIX_FMT_YUV444P10LE:
304                 yuv_16_black (ten_bit_uv, false);
305                 break;
306
307         case PIX_FMT_YUV422P16LE:
308         case PIX_FMT_YUV444P16LE:
309                 yuv_16_black (sixteen_bit_uv, false);
310                 break;
311
312         case PIX_FMT_YUV444P10BE:
313         case PIX_FMT_YUV422P10BE:
314                 yuv_16_black (swap_16 (ten_bit_uv), false);
315                 break;
316
317         case AV_PIX_FMT_YUVA420P9BE:
318         case AV_PIX_FMT_YUVA422P9BE:
319         case AV_PIX_FMT_YUVA444P9BE:
320                 yuv_16_black (swap_16 (nine_bit_uv), true);
321                 break;
322
323         case AV_PIX_FMT_YUVA420P9LE:
324         case AV_PIX_FMT_YUVA422P9LE:
325         case AV_PIX_FMT_YUVA444P9LE:
326                 yuv_16_black (nine_bit_uv, true);
327                 break;
328
329         case AV_PIX_FMT_YUVA420P10BE:
330         case AV_PIX_FMT_YUVA422P10BE:
331         case AV_PIX_FMT_YUVA444P10BE:
332                 yuv_16_black (swap_16 (ten_bit_uv), true);
333                 break;
334
335         case AV_PIX_FMT_YUVA420P10LE:
336         case AV_PIX_FMT_YUVA422P10LE:
337         case AV_PIX_FMT_YUVA444P10LE:
338                 yuv_16_black (ten_bit_uv, true);
339                 break;
340
341         case AV_PIX_FMT_YUVA420P16BE:
342         case AV_PIX_FMT_YUVA422P16BE:
343         case AV_PIX_FMT_YUVA444P16BE:
344                 yuv_16_black (swap_16 (sixteen_bit_uv), true);
345                 break;
346
347         case AV_PIX_FMT_YUVA420P16LE:
348         case AV_PIX_FMT_YUVA422P16LE:
349         case AV_PIX_FMT_YUVA444P16LE:
350                 yuv_16_black (sixteen_bit_uv, true);
351                 break;
352
353         case PIX_FMT_RGB24:
354         case PIX_FMT_ARGB:
355         case PIX_FMT_RGBA:
356         case PIX_FMT_ABGR:
357         case PIX_FMT_BGRA:
358         case PIX_FMT_RGB555LE:
359         case PIX_FMT_RGB48LE:
360         case PIX_FMT_RGB48BE:
361                 memset (data()[0], 0, sample_size(0).height * stride()[0]);
362                 break;
363
364         case PIX_FMT_UYVY422:
365         {
366                 int const Y = sample_size(0).height;
367                 int const X = line_size()[0];
368                 uint8_t* p = data()[0];
369                 for (int y = 0; y < Y; ++y) {
370                         for (int x = 0; x < X / 4; ++x) {
371                                 *p++ = eight_bit_uv; // Cb
372                                 *p++ = 0;            // Y0
373                                 *p++ = eight_bit_uv; // Cr
374                                 *p++ = 0;            // Y1
375                         }
376                 }
377                 break;
378         }
379
380         default:
381                 throw PixelFormatError ("make_black()", _pixel_format);
382         }
383 }
384
385 void
386 Image::make_transparent ()
387 {
388         if (_pixel_format != PIX_FMT_RGBA) {
389                 throw PixelFormatError ("make_transparent()", _pixel_format);
390         }
391
392         memset (data()[0], 0, sample_size(0).height * stride()[0]);
393 }
394
395 void
396 Image::alpha_blend (shared_ptr<const Image> other, Position<int> position)
397 {
398         DCPOMATIC_ASSERT (other->pixel_format() == PIX_FMT_RGBA);
399         int const other_bpp = 4;
400
401         int start_tx = position.x;
402         int start_ox = 0;
403
404         if (start_tx < 0) {
405                 start_ox = -start_tx;
406                 start_tx = 0;
407         }
408
409         int start_ty = position.y;
410         int start_oy = 0;
411
412         if (start_ty < 0) {
413                 start_oy = -start_ty;
414                 start_ty = 0;
415         }
416
417         switch (_pixel_format) {
418         case PIX_FMT_RGB24:
419         {
420                 int const this_bpp = 3;
421                 for (int ty = start_ty, oy = start_oy; ty < size().height && oy < other->size().height; ++ty, ++oy) {
422                         uint8_t* tp = data()[0] + ty * stride()[0] + start_tx * this_bpp;
423                         uint8_t* op = other->data()[0] + oy * other->stride()[0];
424                         for (int tx = start_tx, ox = start_ox; tx < size().width && ox < other->size().width; ++tx, ++ox) {
425                                 float const alpha = float (op[3]) / 255;
426                                 tp[0] = op[0] * alpha + tp[0] * (1 - alpha);
427                                 tp[1] = op[1] * alpha + tp[1] * (1 - alpha);
428                                 tp[2] = op[2] * alpha + tp[2] * (1 - alpha);
429
430                                 tp += this_bpp;
431                                 op += other_bpp;
432                         }
433                 }
434                 break;
435         }
436         case PIX_FMT_BGRA:
437         case PIX_FMT_RGBA:
438         {
439                 int const this_bpp = 4;
440                 for (int ty = start_ty, oy = start_oy; ty < size().height && oy < other->size().height; ++ty, ++oy) {
441                         uint8_t* tp = data()[0] + ty * stride()[0] + start_tx * this_bpp;
442                         uint8_t* op = other->data()[0] + oy * other->stride()[0];
443                         for (int tx = start_tx, ox = start_ox; tx < size().width && ox < other->size().width; ++tx, ++ox) {
444                                 float const alpha = float (op[3]) / 255;
445                                 tp[0] = op[0] * alpha + tp[0] * (1 - alpha);
446                                 tp[1] = op[1] * alpha + tp[1] * (1 - alpha);
447                                 tp[2] = op[2] * alpha + tp[2] * (1 - alpha);
448                                 tp[3] = op[3] * alpha + tp[3] * (1 - alpha);
449
450                                 tp += this_bpp;
451                                 op += other_bpp;
452                         }
453                 }
454                 break;
455         }
456         case PIX_FMT_RGB48LE:
457         {
458                 int const this_bpp = 6;
459                 for (int ty = start_ty, oy = start_oy; ty < size().height && oy < other->size().height; ++ty, ++oy) {
460                         uint8_t* tp = data()[0] + ty * stride()[0] + start_tx * this_bpp;
461                         uint8_t* op = other->data()[0] + oy * other->stride()[0];
462                         for (int tx = start_tx, ox = start_ox; tx < size().width && ox < other->size().width; ++tx, ++ox) {
463                                 float const alpha = float (op[3]) / 255;
464                                 /* Blend high bytes */
465                                 tp[1] = op[0] * alpha + tp[1] * (1 - alpha);
466                                 tp[3] = op[1] * alpha + tp[3] * (1 - alpha);
467                                 tp[5] = op[2] * alpha + tp[5] * (1 - alpha);
468
469                                 tp += this_bpp;
470                                 op += other_bpp;
471                         }
472                 }
473                 break;
474         }
475         default:
476                 DCPOMATIC_ASSERT (false);
477         }
478 }
479
480 void
481 Image::copy (shared_ptr<const Image> other, Position<int> position)
482 {
483         /* Only implemented for RGB24 onto RGB24 so far */
484         DCPOMATIC_ASSERT (_pixel_format == PIX_FMT_RGB24 && other->pixel_format() == PIX_FMT_RGB24);
485         DCPOMATIC_ASSERT (position.x >= 0 && position.y >= 0);
486
487         int const N = min (position.x + other->size().width, size().width) - position.x;
488         for (int ty = position.y, oy = 0; ty < size().height && oy < other->size().height; ++ty, ++oy) {
489                 uint8_t * const tp = data()[0] + ty * stride()[0] + position.x * 3;
490                 uint8_t * const op = other->data()[0] + oy * other->stride()[0];
491                 memcpy (tp, op, N * 3);
492         }
493 }
494
495 void
496 Image::read_from_socket (shared_ptr<Socket> socket)
497 {
498         for (int i = 0; i < planes(); ++i) {
499                 uint8_t* p = data()[i];
500                 int const lines = sample_size(i).height;
501                 for (int y = 0; y < lines; ++y) {
502                         socket->read (p, line_size()[i]);
503                         p += stride()[i];
504                 }
505         }
506 }
507
508 void
509 Image::write_to_socket (shared_ptr<Socket> socket) const
510 {
511         for (int i = 0; i < planes(); ++i) {
512                 uint8_t* p = data()[i];
513                 int const lines = sample_size(i).height;
514                 for (int y = 0; y < lines; ++y) {
515                         socket->write (p, line_size()[i]);
516                         p += stride()[i];
517                 }
518         }
519 }
520
521 float
522 Image::bytes_per_pixel (int c) const
523 {
524         AVPixFmtDescriptor const * d = av_pix_fmt_desc_get(_pixel_format);
525         if (!d) {
526                 throw PixelFormatError ("bytes_per_pixel()", _pixel_format);
527         }
528
529         if (c >= planes()) {
530                 return 0;
531         }
532
533         float bpp[4] = { 0, 0, 0, 0 };
534
535         bpp[0] = floor ((d->comp[0].depth_minus1 + 1 + 7) / 8);
536         if (d->nb_components > 1) {
537                 bpp[1] = floor ((d->comp[1].depth_minus1 + 1 + 7) / 8) / pow (2.0f, d->log2_chroma_w);
538         }
539         if (d->nb_components > 2) {
540                 bpp[2] = floor ((d->comp[2].depth_minus1 + 1 + 7) / 8) / pow (2.0f, d->log2_chroma_w);
541         }
542         if (d->nb_components > 3) {
543                 bpp[3] = floor ((d->comp[3].depth_minus1 + 1 + 7) / 8) / pow (2.0f, d->log2_chroma_w);
544         }
545
546         if ((d->flags & PIX_FMT_PLANAR) == 0) {
547                 /* Not planar; sum them up */
548                 return bpp[0] + bpp[1] + bpp[2] + bpp[3];
549         }
550
551         return bpp[c];
552 }
553
554 /** Construct a Image of a given size and format, allocating memory
555  *  as required.
556  *
557  *  @param p Pixel format.
558  *  @param s Size in pixels.
559  */
560 Image::Image (AVPixelFormat p, dcp::Size s, bool aligned)
561         : _size (s)
562         , _pixel_format (p)
563         , _aligned (aligned)
564 {
565         allocate ();
566 }
567
568 void
569 Image::allocate ()
570 {
571         _data = (uint8_t **) wrapped_av_malloc (4 * sizeof (uint8_t *));
572         _data[0] = _data[1] = _data[2] = _data[3] = 0;
573
574         _line_size = (int *) wrapped_av_malloc (4 * sizeof (int));
575         _line_size[0] = _line_size[1] = _line_size[2] = _line_size[3] = 0;
576
577         _stride = (int *) wrapped_av_malloc (4 * sizeof (int));
578         _stride[0] = _stride[1] = _stride[2] = _stride[3] = 0;
579
580         for (int i = 0; i < planes(); ++i) {
581                 _line_size[i] = ceil (_size.width * bytes_per_pixel(i));
582                 _stride[i] = stride_round_up (i, _line_size, _aligned ? 32 : 1);
583
584                 /* The assembler function ff_rgb24ToY_avx (in libswscale/x86/input.asm)
585                    uses a 16-byte fetch to read three bytes (R/G/B) of image data.
586                    Hence on the last pixel of the last line it reads over the end of
587                    the actual data by 1 byte.  If the width of an image is a multiple
588                    of the stride alignment there will be no padding at the end of image lines.
589                    OS X crashes on this illegal read, though other operating systems don't
590                    seem to mind.  The nasty + 1 in this malloc makes sure there is always a byte
591                    for that instruction to read safely.
592
593                    Further to the above, valgrind is now telling me that ff_rgb24ToY_ssse3
594                    over-reads by more then _avx.  I can't follow the code to work out how much,
595                    so I'll just over-allocate by 32 bytes and have done with it.  Empirical
596                    testing suggests that it works.
597                 */
598                 _data[i] = (uint8_t *) wrapped_av_malloc (_stride[i] * sample_size(i).height + 32);
599         }
600 }
601
602 Image::Image (Image const & other)
603         : _size (other._size)
604         , _pixel_format (other._pixel_format)
605         , _aligned (other._aligned)
606 {
607         allocate ();
608
609         for (int i = 0; i < planes(); ++i) {
610                 uint8_t* p = _data[i];
611                 uint8_t* q = other._data[i];
612                 int const lines = sample_size(i).height;
613                 for (int j = 0; j < lines; ++j) {
614                         memcpy (p, q, _line_size[i]);
615                         p += stride()[i];
616                         q += other.stride()[i];
617                 }
618         }
619 }
620
621 Image::Image (AVFrame* frame)
622         : _size (frame->width, frame->height)
623         , _pixel_format (static_cast<AVPixelFormat> (frame->format))
624         , _aligned (true)
625 {
626         allocate ();
627
628         for (int i = 0; i < planes(); ++i) {
629                 uint8_t* p = _data[i];
630                 uint8_t* q = frame->data[i];
631                 int const lines = sample_size(i).height;
632                 for (int j = 0; j < lines; ++j) {
633                         memcpy (p, q, _line_size[i]);
634                         p += stride()[i];
635                         /* AVFrame's linesize is what we call `stride' */
636                         q += frame->linesize[i];
637                 }
638         }
639 }
640
641 Image::Image (shared_ptr<const Image> other, bool aligned)
642         : _size (other->_size)
643         , _pixel_format (other->_pixel_format)
644         , _aligned (aligned)
645 {
646         allocate ();
647
648         for (int i = 0; i < planes(); ++i) {
649                 DCPOMATIC_ASSERT (line_size()[i] == other->line_size()[i]);
650                 uint8_t* p = _data[i];
651                 uint8_t* q = other->data()[i];
652                 int const lines = sample_size(i).height;
653                 for (int j = 0; j < lines; ++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 < planes(); ++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 const *
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.planes() != b.planes() || a.pixel_format() != b.pixel_format() || a.aligned() != b.aligned()) {
759                 return false;
760         }
761
762         for (int c = 0; c < a.planes(); ++c) {
763                 if (a.sample_size(c).height != b.sample_size(c).height || 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                 int const lines = a.sample_size(c).height;
770                 for (int y = 0; y < lines; ++y) {
771                         if (memcmp (p, q, a.line_size()[c]) != 0) {
772                                 return false;
773                         }
774
775                         p += a.stride()[c];
776                         q += b.stride()[c];
777                 }
778         }
779
780         return true;
781 }
782
783 /** Fade the image.
784  *  @param f Amount to fade by; 0 is black, 1 is no fade.
785  */
786 void
787 Image::fade (float f)
788 {
789         switch (_pixel_format) {
790         case PIX_FMT_YUV420P:
791         case PIX_FMT_YUV422P:
792         case PIX_FMT_YUV444P:
793         case PIX_FMT_YUV411P:
794         case PIX_FMT_YUVJ420P:
795         case PIX_FMT_YUVJ422P:
796         case PIX_FMT_YUVJ444P:
797         case PIX_FMT_RGB24:
798         case PIX_FMT_ARGB:
799         case PIX_FMT_RGBA:
800         case PIX_FMT_ABGR:
801         case PIX_FMT_BGRA:
802         case PIX_FMT_RGB555LE:
803                 /* 8-bit */
804                 for (int c = 0; c < 3; ++c) {
805                         uint8_t* p = data()[c];
806                         int const lines = sample_size(c).height;
807                         for (int y = 0; y < lines; ++y) {
808                                 uint8_t* q = p;
809                                 for (int x = 0; x < line_size()[c]; ++x) {
810                                         *q = int (float (*q) * f);
811                                         ++q;
812                                 }
813                                 p += stride()[c];
814                         }
815                 }
816                 break;
817
818         case PIX_FMT_YUV422P9LE:
819         case PIX_FMT_YUV444P9LE:
820         case PIX_FMT_YUV422P10LE:
821         case PIX_FMT_YUV444P10LE:
822         case PIX_FMT_YUV422P16LE:
823         case PIX_FMT_YUV444P16LE:
824         case AV_PIX_FMT_YUVA420P9LE:
825         case AV_PIX_FMT_YUVA422P9LE:
826         case AV_PIX_FMT_YUVA444P9LE:
827         case AV_PIX_FMT_YUVA420P10LE:
828         case AV_PIX_FMT_YUVA422P10LE:
829         case AV_PIX_FMT_YUVA444P10LE:
830         case AV_PIX_FMT_RGB48LE:
831                 /* 16-bit little-endian */
832                 for (int c = 0; c < 3; ++c) {
833                         int const stride_pixels = stride()[c] / 2;
834                         int const line_size_pixels = line_size()[c] / 2;
835                         uint16_t* p = reinterpret_cast<uint16_t*> (data()[c]);
836                         int const lines = sample_size(c).height;
837                         for (int y = 0; y < lines; ++y) {
838                                 uint16_t* q = p;
839                                 for (int x = 0; x < line_size_pixels; ++x) {
840                                         *q = int (float (*q) * f);
841                                         ++q;
842                                 }
843                                 p += stride_pixels;
844                         }
845                 }
846                 break;
847
848         case PIX_FMT_YUV422P9BE:
849         case PIX_FMT_YUV444P9BE:
850         case PIX_FMT_YUV444P10BE:
851         case PIX_FMT_YUV422P10BE:
852         case AV_PIX_FMT_YUVA420P9BE:
853         case AV_PIX_FMT_YUVA422P9BE:
854         case AV_PIX_FMT_YUVA444P9BE:
855         case AV_PIX_FMT_YUVA420P10BE:
856         case AV_PIX_FMT_YUVA422P10BE:
857         case AV_PIX_FMT_YUVA444P10BE:
858         case AV_PIX_FMT_YUVA420P16BE:
859         case AV_PIX_FMT_YUVA422P16BE:
860         case AV_PIX_FMT_YUVA444P16BE:
861         case AV_PIX_FMT_RGB48BE:
862                 /* 16-bit big-endian */
863                 for (int c = 0; c < 3; ++c) {
864                         int const stride_pixels = stride()[c] / 2;
865                         int const line_size_pixels = line_size()[c] / 2;
866                         uint16_t* p = reinterpret_cast<uint16_t*> (data()[c]);
867                         int const lines = sample_size(c).height;
868                         for (int y = 0; y < lines; ++y) {
869                                 uint16_t* q = p;
870                                 for (int x = 0; x < line_size_pixels; ++x) {
871                                         *q = swap_16 (int (float (swap_16 (*q)) * f));
872                                         ++q;
873                                 }
874                                 p += stride_pixels;
875                         }
876                 }
877                 break;
878
879         case PIX_FMT_UYVY422:
880         {
881                 int const Y = sample_size(0).height;
882                 int const X = line_size()[0];
883                 uint8_t* p = data()[0];
884                 for (int y = 0; y < Y; ++y) {
885                         for (int x = 0; x < X; ++x) {
886                                 *p = int (float (*p) * f);
887                                 ++p;
888                         }
889                 }
890                 break;
891         }
892
893         default:
894                 throw PixelFormatError ("fade()", _pixel_format);
895         }
896 }