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