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