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