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