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