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