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