Merge branch 'master' of ssh://houllier/home/carl/git/dvdomatic
[dcpomatic.git] / src / lib / image.cc
1 /*
2     Copyright (C) 2012 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 set of classes to describe video images.
22  */
23
24 #include <sstream>
25 #include <iomanip>
26 #include <iostream>
27 #include <sys/time.h>
28 #include <boost/algorithm/string.hpp>
29 #include <boost/bind.hpp>
30 #include <openjpeg.h>
31 extern "C" {
32 #include <libavcodec/avcodec.h>
33 #include <libavformat/avformat.h>
34 #include <libswscale/swscale.h>
35 #include <libavfilter/avfiltergraph.h>
36 #include <libpostproc/postprocess.h>
37 #include <libavutil/pixfmt.h>
38 #include <libavutil/pixdesc.h>
39 }
40 #include "image.h"
41 #include "exceptions.h"
42 #include "scaler.h"
43
44 #include "i18n.h"
45
46 using namespace std;
47 using namespace boost;
48 using libdcp::Size;
49
50 void
51 Image::swap (Image& other)
52 {
53         std::swap (_pixel_format, other._pixel_format);
54 }
55
56 /** @param n Component index.
57  *  @return Number of lines in the image for the given component.
58  */
59 int
60 Image::lines (int n) const
61 {
62         if (n == 0) {
63                 return size().height;
64         }
65         
66         AVPixFmtDescriptor const * d = av_pix_fmt_desc_get(_pixel_format);
67         if (!d) {
68                 throw PixelFormatError (N_("lines()"), _pixel_format);
69         }
70         
71         return size().height / pow(2.0f, d->log2_chroma_h);
72 }
73
74 /** @return Number of components */
75 int
76 Image::components () const
77 {
78         AVPixFmtDescriptor const * d = av_pix_fmt_desc_get(_pixel_format);
79         if (!d) {
80                 throw PixelFormatError (N_("components()"), _pixel_format);
81         }
82
83         if ((d->flags & PIX_FMT_PLANAR) == 0) {
84                 return 1;
85         }
86         
87         return d->nb_components;
88 }
89
90 shared_ptr<Image>
91 Image::scale (libdcp::Size out_size, Scaler const * scaler, bool result_aligned) const
92 {
93         assert (scaler);
94         /* Empirical testing suggests that sws_scale() will crash if
95            the input image is not aligned.
96         */
97         assert (aligned ());
98
99         shared_ptr<Image> scaled (new SimpleImage (pixel_format(), out_size, result_aligned));
100
101         struct SwsContext* scale_context = sws_getContext (
102                 size().width, size().height, pixel_format(),
103                 out_size.width, out_size.height, pixel_format(),
104                 scaler->ffmpeg_id (), 0, 0, 0
105                 );
106
107         sws_scale (
108                 scale_context,
109                 data(), stride(),
110                 0, size().height,
111                 scaled->data(), scaled->stride()
112                 );
113
114         sws_freeContext (scale_context);
115
116         return scaled;
117 }
118
119 /** Scale this image to a given size and convert it to RGB.
120  *  @param out_size Output image size in pixels.
121  *  @param scaler Scaler to use.
122  */
123 shared_ptr<Image>
124 Image::scale_and_convert_to_rgb (libdcp::Size out_size, int padding, Scaler const * scaler, bool result_aligned) const
125 {
126         assert (scaler);
127         /* Empirical testing suggests that sws_scale() will crash if
128            the input image is not aligned.
129         */
130         assert (aligned ());
131
132         libdcp::Size content_size = out_size;
133         content_size.width -= (padding * 2);
134
135         shared_ptr<Image> rgb (new SimpleImage (PIX_FMT_RGB24, content_size, result_aligned));
136
137         struct SwsContext* scale_context = sws_getContext (
138                 size().width, size().height, pixel_format(),
139                 content_size.width, content_size.height, PIX_FMT_RGB24,
140                 scaler->ffmpeg_id (), 0, 0, 0
141                 );
142
143         /* Scale and convert to RGB from whatever its currently in (which may be RGB) */
144         sws_scale (
145                 scale_context,
146                 data(), stride(),
147                 0, size().height,
148                 rgb->data(), rgb->stride()
149                 );
150
151         /* Put the image in the right place in a black frame if are padding; this is
152            a bit grubby and expensive, but probably inconsequential in the great
153            scheme of things.
154         */
155         if (padding > 0) {
156                 shared_ptr<Image> padded_rgb (new SimpleImage (PIX_FMT_RGB24, out_size, result_aligned));
157                 padded_rgb->make_black ();
158
159                 /* XXX: we are cheating a bit here; we know the frame is RGB so we can
160                    make assumptions about its composition.
161                 */
162                 uint8_t* p = padded_rgb->data()[0] + padding * 3;
163                 uint8_t* q = rgb->data()[0];
164                 for (int j = 0; j < rgb->lines(0); ++j) {
165                         memcpy (p, q, rgb->line_size()[0]);
166                         p += padded_rgb->stride()[0];
167                         q += rgb->stride()[0];
168                 }
169
170                 rgb = padded_rgb;
171         }
172
173         sws_freeContext (scale_context);
174
175         return rgb;
176 }
177
178 /** Run a FFmpeg post-process on this image and return the processed version.
179  *  @param pp Flags for the required set of post processes.
180  *  @return Post-processed image.
181  */
182 shared_ptr<Image>
183 Image::post_process (string pp, bool aligned) const
184 {
185         shared_ptr<Image> out (new SimpleImage (pixel_format(), size (), aligned));
186
187         int pp_format = 0;
188         switch (pixel_format()) {
189         case PIX_FMT_YUV420P:
190                 pp_format = PP_FORMAT_420;
191                 break;
192         case PIX_FMT_YUV422P10LE:
193         case PIX_FMT_YUV422P:
194         case PIX_FMT_UYVY422:
195                 pp_format = PP_FORMAT_422;
196                 break;
197         case PIX_FMT_YUV444P:
198         case PIX_FMT_YUV444P9BE:
199         case PIX_FMT_YUV444P9LE:
200         case PIX_FMT_YUV444P10BE:
201         case PIX_FMT_YUV444P10LE:
202                 pp_format = PP_FORMAT_444;
203         default:
204                 throw PixelFormatError (N_("post_process"), pixel_format());
205         }
206                 
207         pp_mode* mode = pp_get_mode_by_name_and_quality (pp.c_str (), PP_QUALITY_MAX);
208         pp_context* context = pp_get_context (size().width, size().height, pp_format | PP_CPU_CAPS_MMX2);
209
210         pp_postprocess (
211                 (const uint8_t **) data(), stride(),
212                 out->data(), out->stride(),
213                 size().width, size().height,
214                 0, 0, mode, context, 0
215                 );
216                 
217         pp_free_mode (mode);
218         pp_free_context (context);
219
220         return out;
221 }
222
223 shared_ptr<Image>
224 Image::crop (Crop crop, bool aligned) const
225 {
226         libdcp::Size cropped_size = size ();
227         cropped_size.width -= crop.left + crop.right;
228         cropped_size.height -= crop.top + crop.bottom;
229
230         shared_ptr<Image> out (new SimpleImage (pixel_format(), cropped_size, aligned));
231
232         for (int c = 0; c < components(); ++c) {
233                 int const crop_left_in_bytes = bytes_per_pixel(c) * crop.left;
234                 int const cropped_width_in_bytes = bytes_per_pixel(c) * cropped_size.width;
235                         
236                 /* Start of the source line, cropped from the top but not the left */
237                 uint8_t* in_p = data()[c] + crop.top * stride()[c];
238                 uint8_t* out_p = out->data()[c];
239                 
240                 for (int y = 0; y < cropped_size.height; ++y) {
241                         memcpy (out_p, in_p + crop_left_in_bytes, cropped_width_in_bytes);
242                         in_p += stride()[c];
243                         out_p += out->stride()[c];
244                 }
245         }
246
247         return out;
248 }
249
250 /** Blacken a YUV image whose bits per pixel is rounded up to 16 */
251 void
252 Image::yuv_16_black (uint16_t v)
253 {
254         memset (data()[0], 0, lines(0) * stride()[0]);
255         for (int i = 1; i < 3; ++i) {
256                 int16_t* p = reinterpret_cast<int16_t*> (data()[i]);
257                 for (int y = 0; y < size().height; ++y) {
258                         for (int x = 0; x < line_size()[i] / 2; ++x) {
259                                 p[x] = v;
260                         }
261                         p += stride()[i] / 2;
262                 }
263         }
264 }
265
266 uint16_t
267 Image::swap_16 (uint16_t v)
268 {
269         return ((v >> 8) & 0xff) | ((v & 0xff) << 8);
270 }
271
272 void
273 Image::make_black ()
274 {
275         /* U/V black value for 8-bit colour */
276         static uint8_t const eight_bit_uv =     (1 << 7) - 1;
277         /* U/V black value for 9-bit colour */
278         static uint16_t const nine_bit_uv =     (1 << 8) - 1;
279         /* U/V black value for 10-bit colour */
280         static uint16_t const ten_bit_uv =      (1 << 9) - 1;
281         /* U/V black value for 16-bit colour */
282         static uint16_t const sixteen_bit_uv =  (1 << 15) - 1;
283         
284         switch (_pixel_format) {
285         case PIX_FMT_YUV420P:
286         case PIX_FMT_YUV422P:
287         case PIX_FMT_YUV444P:
288                 memset (data()[0], 0, lines(0) * stride()[0]);
289                 memset (data()[1], eight_bit_uv, lines(1) * stride()[1]);
290                 memset (data()[2], eight_bit_uv, lines(2) * stride()[2]);
291                 break;
292
293         case PIX_FMT_YUVJ420P:
294         case PIX_FMT_YUVJ422P:
295         case PIX_FMT_YUVJ444P:
296                 memset (data()[0], 0, lines(0) * stride()[0]);
297                 memset (data()[1], eight_bit_uv + 1, lines(1) * stride()[1]);
298                 memset (data()[2], eight_bit_uv + 1, lines(2) * stride()[2]);
299                 break;
300
301         case PIX_FMT_YUV422P9LE:
302         case PIX_FMT_YUV444P9LE:
303                 yuv_16_black (nine_bit_uv);
304                 break;
305
306         case PIX_FMT_YUV422P9BE:
307         case PIX_FMT_YUV444P9BE:
308                 yuv_16_black (swap_16 (nine_bit_uv));
309                 break;
310                 
311         case PIX_FMT_YUV422P10LE:
312         case PIX_FMT_YUV444P10LE:
313                 yuv_16_black (ten_bit_uv);
314                 break;
315
316         case PIX_FMT_YUV422P16LE:
317         case PIX_FMT_YUV444P16LE:
318                 yuv_16_black (sixteen_bit_uv);
319                 break;
320                 
321         case PIX_FMT_YUV444P10BE:
322         case PIX_FMT_YUV422P10BE:
323                 yuv_16_black (swap_16 (ten_bit_uv));
324                 break;
325
326         case PIX_FMT_RGB24:             
327                 memset (data()[0], 0, lines(0) * stride()[0]);
328                 break;
329
330         case PIX_FMT_UYVY422:
331         {
332                 int const Y = lines(0);
333                 int const X = line_size()[0];
334                 uint8_t* p = data()[0];
335                 for (int y = 0; y < Y; ++y) {
336                         for (int x = 0; x < X / 4; ++x) {
337                                 *p++ = eight_bit_uv; // Cb
338                                 *p++ = 0;            // Y0
339                                 *p++ = eight_bit_uv; // Cr
340                                 *p++ = 0;            // Y1
341                         }
342                 }
343                 break;
344         }
345
346         default:
347                 throw PixelFormatError (N_("make_black()"), _pixel_format);
348         }
349 }
350
351 void
352 Image::alpha_blend (shared_ptr<const Image> other, Position position)
353 {
354         /* Only implemented for RGBA onto RGB24 so far */
355         assert (_pixel_format == PIX_FMT_RGB24 && other->pixel_format() == PIX_FMT_RGBA);
356
357         int start_tx = position.x;
358         int start_ox = 0;
359
360         if (start_tx < 0) {
361                 start_ox = -start_tx;
362                 start_tx = 0;
363         }
364
365         int start_ty = position.y;
366         int start_oy = 0;
367
368         if (start_ty < 0) {
369                 start_oy = -start_ty;
370                 start_ty = 0;
371         }
372
373         for (int ty = start_ty, oy = start_oy; ty < size().height && oy < other->size().height; ++ty, ++oy) {
374                 uint8_t* tp = data()[0] + ty * stride()[0] + position.x * 3;
375                 uint8_t* op = other->data()[0] + oy * other->stride()[0];
376                 for (int tx = start_tx, ox = start_ox; tx < size().width && ox < other->size().width; ++tx, ++ox) {
377                         float const alpha = float (op[3]) / 255;
378                         tp[0] = (tp[0] * (1 - alpha)) + op[0] * alpha;
379                         tp[1] = (tp[1] * (1 - alpha)) + op[1] * alpha;
380                         tp[2] = (tp[2] * (1 - alpha)) + op[2] * alpha;
381                         tp += 3;
382                         op += 4;
383                 }
384         }
385 }
386
387 void
388 Image::read_from_socket (shared_ptr<Socket> socket)
389 {
390         for (int i = 0; i < components(); ++i) {
391                 uint8_t* p = data()[i];
392                 for (int y = 0; y < lines(i); ++y) {
393                         socket->read (p, line_size()[i]);
394                         p += stride()[i];
395                 }
396         }
397 }
398
399 void
400 Image::write_to_socket (shared_ptr<Socket> socket) const
401 {
402         for (int i = 0; i < components(); ++i) {
403                 uint8_t* p = data()[i];
404                 for (int y = 0; y < lines(i); ++y) {
405                         socket->write (p, line_size()[i]);
406                         p += stride()[i];
407                 }
408         }
409 }
410
411
412 float
413 Image::bytes_per_pixel (int c) const
414 {
415         AVPixFmtDescriptor const * d = av_pix_fmt_desc_get(_pixel_format);
416         if (!d) {
417                 throw PixelFormatError (N_("lines()"), _pixel_format);
418         }
419
420         if (c >= components()) {
421                 return 0;
422         }
423
424         float bpp[4] = { 0, 0, 0, 0 };
425
426         bpp[0] = floor ((d->comp[0].depth_minus1 + 1 + 7) / 8);
427         if (d->nb_components > 1) {
428                 bpp[1] = floor ((d->comp[1].depth_minus1 + 1 + 7) / 8) / pow (2.0f, d->log2_chroma_w);
429         }
430         if (d->nb_components > 2) {
431                 bpp[2] = floor ((d->comp[2].depth_minus1 + 1 + 7) / 8) / pow (2.0f, d->log2_chroma_w);
432         }
433         if (d->nb_components > 3) {
434                 bpp[3] = floor ((d->comp[3].depth_minus1 + 1 + 7) / 8) / pow (2.0f, d->log2_chroma_w);
435         }
436         
437         if ((d->flags & PIX_FMT_PLANAR) == 0) {
438                 /* Not planar; sum them up */
439                 return bpp[0] + bpp[1] + bpp[2] + bpp[3];
440         }
441
442         return bpp[c];
443 }
444
445 /** Construct a SimpleImage of a given size and format, allocating memory
446  *  as required.
447  *
448  *  @param p Pixel format.
449  *  @param s Size in pixels.
450  */
451 SimpleImage::SimpleImage (AVPixelFormat p, libdcp::Size s, bool aligned)
452         : Image (p)
453         , _size (s)
454         , _aligned (aligned)
455 {
456         allocate ();
457 }
458
459 void
460 SimpleImage::allocate ()
461 {
462         _data = (uint8_t **) av_malloc (4 * sizeof (uint8_t *));
463         _data[0] = _data[1] = _data[2] = _data[3] = 0;
464         
465         _line_size = (int *) av_malloc (4 * sizeof (int));
466         _line_size[0] = _line_size[1] = _line_size[2] = _line_size[3] = 0;
467         
468         _stride = (int *) av_malloc (4 * sizeof (int));
469         _stride[0] = _stride[1] = _stride[2] = _stride[3] = 0;
470
471         for (int i = 0; i < components(); ++i) {
472                 _line_size[i] = _size.width * bytes_per_pixel(i);
473                 _stride[i] = stride_round_up (i, _line_size, _aligned ? 32 : 1);
474                 _data[i] = (uint8_t *) av_malloc (_stride[i] * lines (i));
475         }
476 }
477
478 SimpleImage::SimpleImage (SimpleImage const & other)
479         : Image (other)
480         , _size (other._size)
481         , _aligned (other._aligned)
482 {
483         allocate ();
484
485         for (int i = 0; i < components(); ++i) {
486                 uint8_t* p = _data[i];
487                 uint8_t* q = other._data[i];
488                 for (int j = 0; j < lines(i); ++j) {
489                         memcpy (p, q, _line_size[i]);
490                         p += stride()[i];
491                         q += other.stride()[i];
492                 }
493         }
494 }
495
496 SimpleImage::SimpleImage (AVFrame* frame)
497         : Image (static_cast<AVPixelFormat> (frame->format))
498         , _size (frame->width, frame->height)
499         , _aligned (true)
500 {
501         allocate ();
502
503         for (int i = 0; i < components(); ++i) {
504                 uint8_t* p = _data[i];
505                 uint8_t* q = frame->data[i];
506                 for (int j = 0; j < lines(i); ++j) {
507                         memcpy (p, q, _line_size[i]);
508                         p += stride()[i];
509                         /* AVFrame's linesize is what we call `stride' */
510                         q += frame->linesize[i];
511                 }
512         }
513 }
514
515 SimpleImage::SimpleImage (shared_ptr<const Image> other)
516         : Image (*other.get())
517 {
518         _size = other->size ();
519         _aligned = true;
520
521         allocate ();
522
523         for (int i = 0; i < components(); ++i) {
524                 assert(line_size()[i] == other->line_size()[i]);
525                 uint8_t* p = _data[i];
526                 uint8_t* q = other->data()[i];
527                 for (int j = 0; j < lines(i); ++j) {
528                         memcpy (p, q, line_size()[i]);
529                         p += stride()[i];
530                         q += other->stride()[i];
531                 }
532         }
533 }
534
535 SimpleImage&
536 SimpleImage::operator= (SimpleImage const & other)
537 {
538         if (this == &other) {
539                 return *this;
540         }
541
542         SimpleImage tmp (other);
543         swap (tmp);
544         return *this;
545 }
546
547 void
548 SimpleImage::swap (SimpleImage & other)
549 {
550         Image::swap (other);
551         
552         std::swap (_size, other._size);
553
554         for (int i = 0; i < 4; ++i) {
555                 std::swap (_data[i], other._data[i]);
556                 std::swap (_line_size[i], other._line_size[i]);
557                 std::swap (_stride[i], other._stride[i]);
558         }
559
560         std::swap (_aligned, other._aligned);
561 }
562
563 /** Destroy a SimpleImage */
564 SimpleImage::~SimpleImage ()
565 {
566         for (int i = 0; i < components(); ++i) {
567                 av_free (_data[i]);
568         }
569
570         av_free (_data);
571         av_free (_line_size);
572         av_free (_stride);
573 }
574
575 uint8_t **
576 SimpleImage::data () const
577 {
578         return _data;
579 }
580
581 int *
582 SimpleImage::line_size () const
583 {
584         return _line_size;
585 }
586
587 int *
588 SimpleImage::stride () const
589 {
590         return _stride;
591 }
592
593 libdcp::Size
594 SimpleImage::size () const
595 {
596         return _size;
597 }
598
599 bool
600 SimpleImage::aligned () const
601 {
602         return _aligned;
603 }
604
605 RGBPlusAlphaImage::RGBPlusAlphaImage (shared_ptr<const Image> im)
606         : SimpleImage (im->pixel_format(), im->size(), false)
607 {
608         assert (im->pixel_format() == PIX_FMT_RGBA);
609
610         _alpha = (uint8_t *) av_malloc (im->size().width * im->size().height);
611
612         uint8_t* in = im->data()[0];
613         uint8_t* out = data()[0];
614         uint8_t* out_alpha = _alpha;
615         for (int y = 0; y < im->size().height; ++y) {
616                 uint8_t* in_r = in;
617                 for (int x = 0; x < im->size().width; ++x) {
618                         *out++ = *in_r++;
619                         *out++ = *in_r++;
620                         *out++ = *in_r++;
621                         *out_alpha++ = *in_r++;
622                 }
623
624                 in += im->stride()[0];
625         }
626 }
627
628 RGBPlusAlphaImage::~RGBPlusAlphaImage ()
629 {
630         av_free (_alpha);
631 }
632