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