Typo in previous.
[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                 _line_size[0] = s.width;
314                 _line_size[1] = s.width / 2;
315                 _line_size[2] = s.width / 2;
316                 break;
317         case PIX_FMT_YUV422P10LE:
318                 _line_size[0] = s.width * 2;
319                 _line_size[1] = s.width;
320                 _line_size[2] = s.width;
321                 break;
322         default:
323                 assert (false);
324         }
325
326         for (int i = 0; i < components(); ++i) {
327                 _stride[i] = rounder (_line_size[i]);
328                 _data[i] = (uint8_t *) av_malloc (_stride[i] * lines (i));
329         }
330 }
331
332 /** Destroy a SimpleImage */
333 SimpleImage::~SimpleImage ()
334 {
335         for (int i = 0; i < components(); ++i) {
336                 av_free (_data[i]);
337         }
338
339         av_free (_data);
340         av_free (_line_size);
341         av_free (_stride);
342 }
343
344 uint8_t **
345 SimpleImage::data () const
346 {
347         return _data;
348 }
349
350 int *
351 SimpleImage::line_size () const
352 {
353         return _line_size;
354 }
355
356 int *
357 SimpleImage::stride () const
358 {
359         return _stride;
360 }
361
362 Size
363 SimpleImage::size () const
364 {
365         return _size;
366 }
367
368 AlignedImage::AlignedImage (PixelFormat f, Size s)
369         : SimpleImage (f, s, boost::bind (round_up, _1, 32))
370 {
371
372 }
373
374 CompactImage::CompactImage (PixelFormat f, Size s)
375         : SimpleImage (f, s, boost::bind (round_up, _1, 1))
376 {
377
378 }
379
380 CompactImage::CompactImage (shared_ptr<Image> im)
381         : SimpleImage (im->pixel_format(), im->size(), boost::bind (round_up, _1, 1))
382 {
383         assert (components() == im->components());
384
385         for (int c = 0; c < components(); ++c) {
386
387                 assert (line_size()[c] == im->line_size()[c]);
388
389                 uint8_t* t = data()[c];
390                 uint8_t* o = im->data()[c];
391                 
392                 for (int y = 0; y < lines(c); ++y) {
393                         memcpy (t, o, line_size()[c]);
394                         t += stride()[c];
395                         o += im->stride()[c];
396                 }
397         }
398 }
399
400 FilterBufferImage::FilterBufferImage (PixelFormat p, AVFilterBufferRef* b)
401         : Image (p)
402         , _buffer (b)
403 {
404
405 }
406
407 FilterBufferImage::~FilterBufferImage ()
408 {
409         avfilter_unref_buffer (_buffer);
410 }
411
412 uint8_t **
413 FilterBufferImage::data () const
414 {
415         return _buffer->data;
416 }
417
418 int *
419 FilterBufferImage::line_size () const
420 {
421         return _buffer->linesize;
422 }
423
424 int *
425 FilterBufferImage::stride () const
426 {
427         /* XXX? */
428         return _buffer->linesize;
429 }
430
431 Size
432 FilterBufferImage::size () const
433 {
434         return Size (_buffer->video->w, _buffer->video->h);
435 }
436
437 /** XXX: this could be generalised to use any format, but I don't
438  *  understand how avpicture_fill is supposed to be called with
439  *  multi-planar images.
440  */
441 RGBFrameImage::RGBFrameImage (Size s)
442         : Image (PIX_FMT_RGB24)
443         , _size (s)
444 {
445         _frame = avcodec_alloc_frame ();
446         if (_frame == 0) {
447                 throw EncodeError ("could not allocate frame");
448         }
449
450         _data = (uint8_t *) av_malloc (size().width * size().height * 3);
451         avpicture_fill ((AVPicture *) _frame, _data, PIX_FMT_RGB24, size().width, size().height);
452         _frame->width = size().width;
453         _frame->height = size().height;
454         _frame->format = PIX_FMT_RGB24;
455 }
456
457 RGBFrameImage::~RGBFrameImage ()
458 {
459         av_free (_data);
460         av_free (_frame);
461 }
462
463 uint8_t **
464 RGBFrameImage::data () const
465 {
466         return _frame->data;
467 }
468
469 int *
470 RGBFrameImage::line_size () const
471 {
472         return _frame->linesize;
473 }
474
475 int *
476 RGBFrameImage::stride () const
477 {
478         /* XXX? */
479         return line_size ();
480 }
481
482 Size
483 RGBFrameImage::size () const
484 {
485         return _size;
486 }