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