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