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