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