Merge master.
[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, 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         shared_ptr<Image> rgb (new SimpleImage (PIX_FMT_RGB24, out_size, result_aligned));
133
134         struct SwsContext* scale_context = sws_getContext (
135                 size().width, size().height, pixel_format(),
136                 out_size.width, out_size.height, PIX_FMT_RGB24,
137                 scaler->ffmpeg_id (), 0, 0, 0
138                 );
139
140         /* Scale and convert to RGB from whatever its currently in (which may be RGB) */
141         sws_scale (
142                 scale_context,
143                 data(), stride(),
144                 0, size().height,
145                 rgb->data(), rgb->stride()
146                 );
147
148         sws_freeContext (scale_context);
149
150         return rgb;
151 }
152
153 /** Run a FFmpeg post-process on this image and return the processed version.
154  *  @param pp Flags for the required set of post processes.
155  *  @return Post-processed image.
156  */
157 shared_ptr<Image>
158 Image::post_process (string pp, bool aligned) const
159 {
160         shared_ptr<Image> out (new SimpleImage (pixel_format(), size (), aligned));
161
162         int pp_format = 0;
163         switch (pixel_format()) {
164         case PIX_FMT_YUV420P:
165                 pp_format = PP_FORMAT_420;
166                 break;
167         case PIX_FMT_YUV422P10LE:
168         case PIX_FMT_YUV422P:
169         case PIX_FMT_UYVY422:
170                 pp_format = PP_FORMAT_422;
171                 break;
172         case PIX_FMT_YUV444P:
173         case PIX_FMT_YUV444P9BE:
174         case PIX_FMT_YUV444P9LE:
175         case PIX_FMT_YUV444P10BE:
176         case PIX_FMT_YUV444P10LE:
177                 pp_format = PP_FORMAT_444;
178         default:
179                 throw PixelFormatError (N_("post_process"), pixel_format());
180         }
181                 
182         pp_mode* mode = pp_get_mode_by_name_and_quality (pp.c_str (), PP_QUALITY_MAX);
183         pp_context* context = pp_get_context (size().width, size().height, pp_format | PP_CPU_CAPS_MMX2);
184
185         pp_postprocess (
186                 (const uint8_t **) data(), stride(),
187                 out->data(), out->stride(),
188                 size().width, size().height,
189                 0, 0, mode, context, 0
190                 );
191                 
192         pp_free_mode (mode);
193         pp_free_context (context);
194
195         return out;
196 }
197
198 shared_ptr<Image>
199 Image::crop (Crop crop, bool aligned) const
200 {
201         libdcp::Size cropped_size = size ();
202         cropped_size.width -= crop.left + crop.right;
203         cropped_size.height -= crop.top + crop.bottom;
204
205         shared_ptr<Image> out (new SimpleImage (pixel_format(), cropped_size, aligned));
206
207         for (int c = 0; c < components(); ++c) {
208                 int const crop_left_in_bytes = bytes_per_pixel(c) * crop.left;
209                 int const cropped_width_in_bytes = bytes_per_pixel(c) * cropped_size.width;
210                         
211                 /* Start of the source line, cropped from the top but not the left */
212                 uint8_t* in_p = data()[c] + crop.top * stride()[c];
213                 uint8_t* out_p = out->data()[c];
214
215                 for (int y = 0; y < out->lines(c); ++y) {
216                         memcpy (out_p, in_p + crop_left_in_bytes, cropped_width_in_bytes);
217                         in_p += stride()[c];
218                         out_p += out->stride()[c];
219                 }
220         }
221
222         return out;
223 }
224
225 /** Blacken a YUV image whose bits per pixel is rounded up to 16 */
226 void
227 Image::yuv_16_black (uint16_t v)
228 {
229         memset (data()[0], 0, lines(0) * stride()[0]);
230         for (int i = 1; i < 3; ++i) {
231                 int16_t* p = reinterpret_cast<int16_t*> (data()[i]);
232                 for (int y = 0; y < size().height; ++y) {
233                         for (int x = 0; x < line_size()[i] / 2; ++x) {
234                                 p[x] = v;
235                         }
236                         p += stride()[i] / 2;
237                 }
238         }
239 }
240
241 uint16_t
242 Image::swap_16 (uint16_t v)
243 {
244         return ((v >> 8) & 0xff) | ((v & 0xff) << 8);
245 }
246
247 void
248 Image::make_black ()
249 {
250         /* U/V black value for 8-bit colour */
251         static uint8_t const eight_bit_uv =     (1 << 7) - 1;
252         /* U/V black value for 9-bit colour */
253         static uint16_t const nine_bit_uv =     (1 << 8) - 1;
254         /* U/V black value for 10-bit colour */
255         static uint16_t const ten_bit_uv =      (1 << 9) - 1;
256         /* U/V black value for 16-bit colour */
257         static uint16_t const sixteen_bit_uv =  (1 << 15) - 1;
258         
259         switch (_pixel_format) {
260         case PIX_FMT_YUV420P:
261         case PIX_FMT_YUV422P:
262         case PIX_FMT_YUV444P:
263                 memset (data()[0], 0, lines(0) * stride()[0]);
264                 memset (data()[1], eight_bit_uv, lines(1) * stride()[1]);
265                 memset (data()[2], eight_bit_uv, lines(2) * stride()[2]);
266                 break;
267
268         case PIX_FMT_YUVJ420P:
269         case PIX_FMT_YUVJ422P:
270         case PIX_FMT_YUVJ444P:
271                 memset (data()[0], 0, lines(0) * stride()[0]);
272                 memset (data()[1], eight_bit_uv + 1, lines(1) * stride()[1]);
273                 memset (data()[2], eight_bit_uv + 1, lines(2) * stride()[2]);
274                 break;
275
276         case PIX_FMT_YUV422P9LE:
277         case PIX_FMT_YUV444P9LE:
278                 yuv_16_black (nine_bit_uv);
279                 break;
280
281         case PIX_FMT_YUV422P9BE:
282         case PIX_FMT_YUV444P9BE:
283                 yuv_16_black (swap_16 (nine_bit_uv));
284                 break;
285                 
286         case PIX_FMT_YUV422P10LE:
287         case PIX_FMT_YUV444P10LE:
288                 yuv_16_black (ten_bit_uv);
289                 break;
290
291         case PIX_FMT_YUV422P16LE:
292         case PIX_FMT_YUV444P16LE:
293                 yuv_16_black (sixteen_bit_uv);
294                 break;
295                 
296         case PIX_FMT_YUV444P10BE:
297         case PIX_FMT_YUV422P10BE:
298                 yuv_16_black (swap_16 (ten_bit_uv));
299                 break;
300
301         case PIX_FMT_RGB24:             
302                 memset (data()[0], 0, lines(0) * stride()[0]);
303                 break;
304
305         case PIX_FMT_UYVY422:
306         {
307                 int const Y = lines(0);
308                 int const X = line_size()[0];
309                 uint8_t* p = data()[0];
310                 for (int y = 0; y < Y; ++y) {
311                         for (int x = 0; x < X / 4; ++x) {
312                                 *p++ = eight_bit_uv; // Cb
313                                 *p++ = 0;            // Y0
314                                 *p++ = eight_bit_uv; // Cr
315                                 *p++ = 0;            // Y1
316                         }
317                 }
318                 break;
319         }
320
321         default:
322                 throw PixelFormatError (N_("make_black()"), _pixel_format);
323         }
324 }
325
326 void
327 Image::alpha_blend (shared_ptr<const Image> other, Position position)
328 {
329         /* Only implemented for RGBA onto RGB24 so far */
330         assert (_pixel_format == PIX_FMT_RGB24 && other->pixel_format() == PIX_FMT_RGBA);
331
332         int start_tx = position.x;
333         int start_ox = 0;
334
335         if (start_tx < 0) {
336                 start_ox = -start_tx;
337                 start_tx = 0;
338         }
339
340         int start_ty = position.y;
341         int start_oy = 0;
342
343         if (start_ty < 0) {
344                 start_oy = -start_ty;
345                 start_ty = 0;
346         }
347
348         for (int ty = start_ty, oy = start_oy; ty < size().height && oy < other->size().height; ++ty, ++oy) {
349                 uint8_t* tp = data()[0] + ty * stride()[0] + position.x * 3;
350                 uint8_t* op = other->data()[0] + oy * other->stride()[0];
351                 for (int tx = start_tx, ox = start_ox; tx < size().width && ox < other->size().width; ++tx, ++ox) {
352                         float const alpha = float (op[3]) / 255;
353                         tp[0] = (tp[0] * (1 - alpha)) + op[0] * alpha;
354                         tp[1] = (tp[1] * (1 - alpha)) + op[1] * alpha;
355                         tp[2] = (tp[2] * (1 - alpha)) + op[2] * alpha;
356                         tp += 3;
357                         op += 4;
358                 }
359         }
360 }
361
362 void
363 Image::copy (shared_ptr<const Image> other, Position position)
364 {
365         /* Only implemented for RGB24 onto RGB24 so far */
366         assert (_pixel_format == PIX_FMT_RGB24 && other->pixel_format() == PIX_FMT_RGB24);
367         assert (position.x >= 0 && position.y >= 0);
368
369         int const N = min (position.x + other->size().width, size().width) - position.x;
370         for (int ty = position.y, oy = 0; ty < size().height && oy < other->size().height; ++ty, ++oy) {
371                 uint8_t * const tp = data()[0] + ty * stride()[0] + position.x * 3;
372                 uint8_t * const op = other->data()[0] + oy * other->stride()[0];
373                 memcpy (tp, op, N * 3);
374         }
375 }       
376
377 void
378 Image::read_from_socket (shared_ptr<Socket> socket)
379 {
380         for (int i = 0; i < components(); ++i) {
381                 uint8_t* p = data()[i];
382                 for (int y = 0; y < lines(i); ++y) {
383                         socket->read (p, line_size()[i]);
384                         p += stride()[i];
385                 }
386         }
387 }
388
389 void
390 Image::write_to_socket (shared_ptr<Socket> socket) const
391 {
392         for (int i = 0; i < components(); ++i) {
393                 uint8_t* p = data()[i];
394                 for (int y = 0; y < lines(i); ++y) {
395                         socket->write (p, line_size()[i]);
396                         p += stride()[i];
397                 }
398         }
399 }
400
401
402 float
403 Image::bytes_per_pixel (int c) const
404 {
405         AVPixFmtDescriptor const * d = av_pix_fmt_desc_get(_pixel_format);
406         if (!d) {
407                 throw PixelFormatError (N_("lines()"), _pixel_format);
408         }
409
410         if (c >= components()) {
411                 return 0;
412         }
413
414         float bpp[4] = { 0, 0, 0, 0 };
415
416         bpp[0] = floor ((d->comp[0].depth_minus1 + 1 + 7) / 8);
417         if (d->nb_components > 1) {
418                 bpp[1] = floor ((d->comp[1].depth_minus1 + 1 + 7) / 8) / pow (2.0f, d->log2_chroma_w);
419         }
420         if (d->nb_components > 2) {
421                 bpp[2] = floor ((d->comp[2].depth_minus1 + 1 + 7) / 8) / pow (2.0f, d->log2_chroma_w);
422         }
423         if (d->nb_components > 3) {
424                 bpp[3] = floor ((d->comp[3].depth_minus1 + 1 + 7) / 8) / pow (2.0f, d->log2_chroma_w);
425         }
426         
427         if ((d->flags & PIX_FMT_PLANAR) == 0) {
428                 /* Not planar; sum them up */
429                 return bpp[0] + bpp[1] + bpp[2] + bpp[3];
430         }
431
432         return bpp[c];
433 }
434
435 /** Construct a SimpleImage of a given size and format, allocating memory
436  *  as required.
437  *
438  *  @param p Pixel format.
439  *  @param s Size in pixels.
440  */
441 SimpleImage::SimpleImage (AVPixelFormat p, libdcp::Size s, bool aligned)
442         : Image (p)
443         , _size (s)
444         , _aligned (aligned)
445 {
446         allocate ();
447 }
448
449 void
450 SimpleImage::allocate ()
451 {
452         _data = (uint8_t **) av_malloc (4 * sizeof (uint8_t *));
453         _data[0] = _data[1] = _data[2] = _data[3] = 0;
454         
455         _line_size = (int *) av_malloc (4 * sizeof (int));
456         _line_size[0] = _line_size[1] = _line_size[2] = _line_size[3] = 0;
457         
458         _stride = (int *) av_malloc (4 * sizeof (int));
459         _stride[0] = _stride[1] = _stride[2] = _stride[3] = 0;
460
461         for (int i = 0; i < components(); ++i) {
462                 _line_size[i] = _size.width * bytes_per_pixel(i);
463                 _stride[i] = stride_round_up (i, _line_size, _aligned ? 32 : 1);
464                 _data[i] = (uint8_t *) av_malloc (_stride[i] * lines (i));
465         }
466 }
467
468 SimpleImage::SimpleImage (SimpleImage const & other)
469         : Image (other)
470         , _size (other._size)
471         , _aligned (other._aligned)
472 {
473         allocate ();
474
475         for (int i = 0; i < components(); ++i) {
476                 uint8_t* p = _data[i];
477                 uint8_t* q = other._data[i];
478                 for (int j = 0; j < lines(i); ++j) {
479                         memcpy (p, q, _line_size[i]);
480                         p += stride()[i];
481                         q += other.stride()[i];
482                 }
483         }
484 }
485
486 SimpleImage::SimpleImage (AVFrame* frame)
487         : Image (static_cast<AVPixelFormat> (frame->format))
488         , _size (frame->width, frame->height)
489         , _aligned (true)
490 {
491         allocate ();
492
493         for (int i = 0; i < components(); ++i) {
494                 uint8_t* p = _data[i];
495                 uint8_t* q = frame->data[i];
496                 for (int j = 0; j < lines(i); ++j) {
497                         memcpy (p, q, _line_size[i]);
498                         p += stride()[i];
499                         /* AVFrame's linesize is what we call `stride' */
500                         q += frame->linesize[i];
501                 }
502         }
503 }
504
505 SimpleImage::SimpleImage (shared_ptr<const Image> other)
506         : Image (*other.get())
507 {
508         _size = other->size ();
509         _aligned = true;
510
511         allocate ();
512
513         for (int i = 0; i < components(); ++i) {
514                 assert(line_size()[i] == other->line_size()[i]);
515                 uint8_t* p = _data[i];
516                 uint8_t* q = other->data()[i];
517                 for (int j = 0; j < lines(i); ++j) {
518                         memcpy (p, q, line_size()[i]);
519                         p += stride()[i];
520                         q += other->stride()[i];
521                 }
522         }
523 }
524
525 SimpleImage&
526 SimpleImage::operator= (SimpleImage const & other)
527 {
528         if (this == &other) {
529                 return *this;
530         }
531
532         SimpleImage tmp (other);
533         swap (tmp);
534         return *this;
535 }
536
537 void
538 SimpleImage::swap (SimpleImage & other)
539 {
540         Image::swap (other);
541         
542         std::swap (_size, other._size);
543
544         for (int i = 0; i < 4; ++i) {
545                 std::swap (_data[i], other._data[i]);
546                 std::swap (_line_size[i], other._line_size[i]);
547                 std::swap (_stride[i], other._stride[i]);
548         }
549
550         std::swap (_aligned, other._aligned);
551 }
552
553 /** Destroy a SimpleImage */
554 SimpleImage::~SimpleImage ()
555 {
556         for (int i = 0; i < components(); ++i) {
557                 av_free (_data[i]);
558         }
559
560         av_free (_data);
561         av_free (_line_size);
562         av_free (_stride);
563 }
564
565 uint8_t **
566 SimpleImage::data () const
567 {
568         return _data;
569 }
570
571 int *
572 SimpleImage::line_size () const
573 {
574         return _line_size;
575 }
576
577 int *
578 SimpleImage::stride () const
579 {
580         return _stride;
581 }
582
583 libdcp::Size
584 SimpleImage::size () const
585 {
586         return _size;
587 }
588
589 bool
590 SimpleImage::aligned () const
591 {
592         return _aligned;
593 }
594
595 RGBPlusAlphaImage::RGBPlusAlphaImage (shared_ptr<const Image> im)
596         : SimpleImage (im->pixel_format(), im->size(), false)
597 {
598         assert (im->pixel_format() == PIX_FMT_RGBA);
599
600         _alpha = (uint8_t *) av_malloc (im->size().width * im->size().height);
601
602         uint8_t* in = im->data()[0];
603         uint8_t* out = data()[0];
604         uint8_t* out_alpha = _alpha;
605         for (int y = 0; y < im->size().height; ++y) {
606                 uint8_t* in_r = in;
607                 for (int x = 0; x < im->size().width; ++x) {
608                         *out++ = *in_r++;
609                         *out++ = *in_r++;
610                         *out++ = *in_r++;
611                         *out_alpha++ = *in_r++;
612                 }
613
614                 in += im->stride()[0];
615         }
616 }
617
618 RGBPlusAlphaImage::~RGBPlusAlphaImage ()
619 {
620         av_free (_alpha);
621 }
622