]> git.sesse.net Git - ffmpeg/blob - libavcodec/v4l2_buffers.c
avcodec/v4l2_buffers: teach ff_v4l2_buffer_avframe_to_buf about contiguous planar...
[ffmpeg] / libavcodec / v4l2_buffers.c
1 /*
2  * V4L2 buffer helper functions.
3  *
4  * Copyright (C) 2017 Alexis Ballier <aballier@gentoo.org>
5  * Copyright (C) 2017 Jorge Ramirez <jorge.ramirez-ortiz@linaro.org>
6  *
7  * This file is part of FFmpeg.
8  *
9  * FFmpeg is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * FFmpeg is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with FFmpeg; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22  */
23
24 #include <linux/videodev2.h>
25 #include <sys/ioctl.h>
26 #include <sys/mman.h>
27 #include <unistd.h>
28 #include <fcntl.h>
29 #include <poll.h>
30 #include "libavcodec/avcodec.h"
31 #include "libavcodec/internal.h"
32 #include "libavutil/pixdesc.h"
33 #include "v4l2_context.h"
34 #include "v4l2_buffers.h"
35 #include "v4l2_m2m.h"
36
37 #define USEC_PER_SEC 1000000
38
39 static inline V4L2m2mContext *buf_to_m2mctx(V4L2Buffer *buf)
40 {
41     return V4L2_TYPE_IS_OUTPUT(buf->context->type) ?
42         container_of(buf->context, V4L2m2mContext, output) :
43         container_of(buf->context, V4L2m2mContext, capture);
44 }
45
46 static inline AVCodecContext *logger(V4L2Buffer *buf)
47 {
48     return buf_to_m2mctx(buf)->avctx;
49 }
50
51 static inline void v4l2_set_pts(V4L2Buffer *out, int64_t pts)
52 {
53     V4L2m2mContext *s = buf_to_m2mctx(out);
54     AVRational v4l2_timebase = { 1, USEC_PER_SEC };
55     int64_t v4l2_pts;
56
57     if (pts == AV_NOPTS_VALUE)
58         pts = 0;
59
60     /* convert pts to v4l2 timebase */
61     v4l2_pts = av_rescale_q(pts, s->avctx->time_base, v4l2_timebase);
62     out->buf.timestamp.tv_usec = v4l2_pts % USEC_PER_SEC;
63     out->buf.timestamp.tv_sec = v4l2_pts / USEC_PER_SEC;
64 }
65
66 static inline int64_t v4l2_get_pts(V4L2Buffer *avbuf)
67 {
68     V4L2m2mContext *s = buf_to_m2mctx(avbuf);
69     AVRational v4l2_timebase = { 1, USEC_PER_SEC };
70     int64_t v4l2_pts;
71
72     /* convert pts back to encoder timebase */
73     v4l2_pts = (int64_t)avbuf->buf.timestamp.tv_sec * USEC_PER_SEC +
74                         avbuf->buf.timestamp.tv_usec;
75
76     return av_rescale_q(v4l2_pts, v4l2_timebase, s->avctx->time_base);
77 }
78
79 static enum AVColorPrimaries v4l2_get_color_primaries(V4L2Buffer *buf)
80 {
81     enum v4l2_ycbcr_encoding ycbcr;
82     enum v4l2_colorspace cs;
83
84     cs = V4L2_TYPE_IS_MULTIPLANAR(buf->buf.type) ?
85         buf->context->format.fmt.pix_mp.colorspace :
86         buf->context->format.fmt.pix.colorspace;
87
88     ycbcr = V4L2_TYPE_IS_MULTIPLANAR(buf->buf.type) ?
89         buf->context->format.fmt.pix_mp.ycbcr_enc:
90         buf->context->format.fmt.pix.ycbcr_enc;
91
92     switch(ycbcr) {
93     case V4L2_YCBCR_ENC_XV709:
94     case V4L2_YCBCR_ENC_709: return AVCOL_PRI_BT709;
95     case V4L2_YCBCR_ENC_XV601:
96     case V4L2_YCBCR_ENC_601:return AVCOL_PRI_BT470M;
97     default:
98         break;
99     }
100
101     switch(cs) {
102     case V4L2_COLORSPACE_470_SYSTEM_BG: return AVCOL_PRI_BT470BG;
103     case V4L2_COLORSPACE_SMPTE170M: return AVCOL_PRI_SMPTE170M;
104     case V4L2_COLORSPACE_SMPTE240M: return AVCOL_PRI_SMPTE240M;
105     case V4L2_COLORSPACE_BT2020: return AVCOL_PRI_BT2020;
106     default:
107         break;
108     }
109
110     return AVCOL_PRI_UNSPECIFIED;
111 }
112
113 static enum AVColorRange v4l2_get_color_range(V4L2Buffer *buf)
114 {
115     enum v4l2_quantization qt;
116
117     qt = V4L2_TYPE_IS_MULTIPLANAR(buf->buf.type) ?
118         buf->context->format.fmt.pix_mp.quantization :
119         buf->context->format.fmt.pix.quantization;
120
121     switch (qt) {
122     case V4L2_QUANTIZATION_LIM_RANGE: return AVCOL_RANGE_MPEG;
123     case V4L2_QUANTIZATION_FULL_RANGE: return AVCOL_RANGE_JPEG;
124     default:
125         break;
126     }
127
128      return AVCOL_RANGE_UNSPECIFIED;
129 }
130
131 static enum AVColorSpace v4l2_get_color_space(V4L2Buffer *buf)
132 {
133     enum v4l2_ycbcr_encoding ycbcr;
134     enum v4l2_colorspace cs;
135
136     cs = V4L2_TYPE_IS_MULTIPLANAR(buf->buf.type) ?
137         buf->context->format.fmt.pix_mp.colorspace :
138         buf->context->format.fmt.pix.colorspace;
139
140     ycbcr = V4L2_TYPE_IS_MULTIPLANAR(buf->buf.type) ?
141         buf->context->format.fmt.pix_mp.ycbcr_enc:
142         buf->context->format.fmt.pix.ycbcr_enc;
143
144     switch(cs) {
145     case V4L2_COLORSPACE_SRGB: return AVCOL_SPC_RGB;
146     case V4L2_COLORSPACE_REC709: return AVCOL_SPC_BT709;
147     case V4L2_COLORSPACE_470_SYSTEM_M: return AVCOL_SPC_FCC;
148     case V4L2_COLORSPACE_470_SYSTEM_BG: return AVCOL_SPC_BT470BG;
149     case V4L2_COLORSPACE_SMPTE170M: return AVCOL_SPC_SMPTE170M;
150     case V4L2_COLORSPACE_SMPTE240M: return AVCOL_SPC_SMPTE240M;
151     case V4L2_COLORSPACE_BT2020:
152         if (ycbcr == V4L2_YCBCR_ENC_BT2020_CONST_LUM)
153             return AVCOL_SPC_BT2020_CL;
154         else
155              return AVCOL_SPC_BT2020_NCL;
156     default:
157         break;
158     }
159
160     return AVCOL_SPC_UNSPECIFIED;
161 }
162
163 static enum AVColorTransferCharacteristic v4l2_get_color_trc(V4L2Buffer *buf)
164 {
165     enum v4l2_ycbcr_encoding ycbcr;
166     enum v4l2_xfer_func xfer;
167     enum v4l2_colorspace cs;
168
169     cs = V4L2_TYPE_IS_MULTIPLANAR(buf->buf.type) ?
170         buf->context->format.fmt.pix_mp.colorspace :
171         buf->context->format.fmt.pix.colorspace;
172
173     ycbcr = V4L2_TYPE_IS_MULTIPLANAR(buf->buf.type) ?
174         buf->context->format.fmt.pix_mp.ycbcr_enc:
175         buf->context->format.fmt.pix.ycbcr_enc;
176
177     xfer = V4L2_TYPE_IS_MULTIPLANAR(buf->buf.type) ?
178         buf->context->format.fmt.pix_mp.xfer_func:
179         buf->context->format.fmt.pix.xfer_func;
180
181     switch (xfer) {
182     case V4L2_XFER_FUNC_709: return AVCOL_TRC_BT709;
183     case V4L2_XFER_FUNC_SRGB: return AVCOL_TRC_IEC61966_2_1;
184     default:
185         break;
186     }
187
188     switch (cs) {
189     case V4L2_COLORSPACE_470_SYSTEM_M: return AVCOL_TRC_GAMMA22;
190     case V4L2_COLORSPACE_470_SYSTEM_BG: return AVCOL_TRC_GAMMA28;
191     case V4L2_COLORSPACE_SMPTE170M: return AVCOL_TRC_SMPTE170M;
192     case V4L2_COLORSPACE_SMPTE240M: return AVCOL_TRC_SMPTE240M;
193     default:
194         break;
195     }
196
197     switch (ycbcr) {
198     case V4L2_YCBCR_ENC_XV709:
199     case V4L2_YCBCR_ENC_XV601: return AVCOL_TRC_BT1361_ECG;
200     default:
201         break;
202     }
203
204     return AVCOL_TRC_UNSPECIFIED;
205 }
206
207 static void v4l2_free_buffer(void *opaque, uint8_t *unused)
208 {
209     V4L2Buffer* avbuf = opaque;
210     V4L2m2mContext *s = buf_to_m2mctx(avbuf);
211
212     if (atomic_fetch_sub(&avbuf->context_refcount, 1) == 1) {
213         atomic_fetch_sub_explicit(&s->refcount, 1, memory_order_acq_rel);
214
215         if (s->reinit) {
216             if (!atomic_load(&s->refcount))
217                 sem_post(&s->refsync);
218         } else {
219             if (s->draining) {
220                 /* no need to queue more buffers to the driver */
221                 avbuf->status = V4L2BUF_AVAILABLE;
222             }
223             else if (avbuf->context->streamon)
224                 ff_v4l2_buffer_enqueue(avbuf);
225         }
226
227         av_buffer_unref(&avbuf->context_ref);
228     }
229 }
230
231 static int v4l2_buf_to_bufref(V4L2Buffer *in, int plane, AVBufferRef **buf)
232 {
233     V4L2m2mContext *s = buf_to_m2mctx(in);
234
235     if (plane >= in->num_planes)
236         return AVERROR(EINVAL);
237
238     /* even though most encoders return 0 in data_offset encoding vp8 does require this value */
239     *buf = av_buffer_create((char *)in->plane_info[plane].mm_addr + in->planes[plane].data_offset,
240                             in->plane_info[plane].length, v4l2_free_buffer, in, 0);
241     if (!*buf)
242         return AVERROR(ENOMEM);
243
244     if (in->context_ref)
245         atomic_fetch_add(&in->context_refcount, 1);
246     else {
247         in->context_ref = av_buffer_ref(s->self_ref);
248         if (!in->context_ref) {
249             av_buffer_unref(buf);
250             return AVERROR(ENOMEM);
251         }
252         in->context_refcount = 1;
253     }
254
255     in->status = V4L2BUF_RET_USER;
256     atomic_fetch_add_explicit(&s->refcount, 1, memory_order_relaxed);
257
258     return 0;
259 }
260
261 static int v4l2_bufref_to_buf(V4L2Buffer *out, int plane, const uint8_t* data, int size, int offset, AVBufferRef* bref)
262 {
263     unsigned int bytesused, length;
264
265     if (plane >= out->num_planes)
266         return AVERROR(EINVAL);
267
268     length = out->plane_info[plane].length;
269     bytesused = FFMIN(size+offset, length);
270
271     memcpy((uint8_t*)out->plane_info[plane].mm_addr+offset, data, FFMIN(size, length-offset));
272
273     if (V4L2_TYPE_IS_MULTIPLANAR(out->buf.type)) {
274         out->planes[plane].bytesused = bytesused;
275         out->planes[plane].length = length;
276     } else {
277         out->buf.bytesused = bytesused;
278         out->buf.length = length;
279     }
280
281     return 0;
282 }
283
284 /******************************************************************************
285  *
286  *              V4L2Buffer interface
287  *
288  ******************************************************************************/
289
290 int ff_v4l2_buffer_avframe_to_buf(const AVFrame *frame, V4L2Buffer *out)
291 {
292     int i, ret;
293     struct v4l2_format fmt = out->context->format;
294     int pixel_format = V4L2_TYPE_IS_MULTIPLANAR(fmt.type) ?
295                        fmt.fmt.pix_mp.pixelformat : fmt.fmt.pix.pixelformat;
296     int height       = V4L2_TYPE_IS_MULTIPLANAR(fmt.type) ?
297                        fmt.fmt.pix_mp.height : fmt.fmt.pix.height;
298     int is_planar_format = 0;
299
300     switch (pixel_format) {
301     case V4L2_PIX_FMT_YUV420M:
302     case V4L2_PIX_FMT_YVU420M:
303     case V4L2_PIX_FMT_YUV422M:
304     case V4L2_PIX_FMT_YVU422M:
305     case V4L2_PIX_FMT_YUV444M:
306     case V4L2_PIX_FMT_YVU444M:
307     case V4L2_PIX_FMT_NV12M:
308     case V4L2_PIX_FMT_NV21M:
309     case V4L2_PIX_FMT_NV12MT_16X16:
310     case V4L2_PIX_FMT_NV12MT:
311     case V4L2_PIX_FMT_NV16M:
312     case V4L2_PIX_FMT_NV61M:
313         is_planar_format = 1;
314     }
315
316     v4l2_set_pts(out, frame->pts);
317
318     if (!is_planar_format) {
319         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
320         int planes_nb = 0;
321         int offset = 0;
322
323         for (i = 0; i < desc->nb_components; i++)
324             planes_nb = FFMAX(planes_nb, desc->comp[i].plane + 1);
325
326         for (i = 0; i < planes_nb; i++) {
327             int size, h = height;
328             if (i == 1 || i == 2) {
329                 h = AV_CEIL_RSHIFT(h, desc->log2_chroma_h);
330             }
331             size = frame->linesize[i] * h;
332             ret = v4l2_bufref_to_buf(out, 0, frame->data[i], size, offset, frame->buf[i]);
333             if (ret)
334                 return ret;
335             offset += size;
336         }
337         return 0;
338     }
339
340     for (i = 0; i < out->num_planes; i++) {
341         ret = v4l2_bufref_to_buf(out, i, frame->buf[i]->data, frame->buf[i]->size, 0, frame->buf[i]);
342         if (ret)
343             return ret;
344     }
345
346     return 0;
347 }
348
349 int ff_v4l2_buffer_buf_to_avframe(AVFrame *frame, V4L2Buffer *avbuf)
350 {
351     V4L2m2mContext *s = buf_to_m2mctx(avbuf);
352     int i, ret;
353
354     av_frame_unref(frame);
355
356     /* 1. get references to the actual data */
357     for (i = 0; i < avbuf->num_planes; i++) {
358         ret = v4l2_buf_to_bufref(avbuf, i, &frame->buf[i]);
359         if (ret)
360             return ret;
361
362         frame->linesize[i] = avbuf->plane_info[i].bytesperline;
363         frame->data[i] = frame->buf[i]->data;
364     }
365
366     /* 1.1 fixup special cases */
367     switch (avbuf->context->av_pix_fmt) {
368     case AV_PIX_FMT_NV12:
369     case AV_PIX_FMT_NV21:
370         if (avbuf->num_planes > 1)
371             break;
372         frame->linesize[1] = avbuf->plane_info[0].bytesperline;
373         frame->data[1] = frame->buf[0]->data + avbuf->plane_info[0].bytesperline * avbuf->context->format.fmt.pix_mp.height;
374         break;
375     case AV_PIX_FMT_YUV420P:
376         if (avbuf->num_planes > 1)
377             break;
378         frame->linesize[1] = avbuf->plane_info[0].bytesperline >> 1;
379         frame->linesize[2] = avbuf->plane_info[0].bytesperline >> 1;
380         frame->data[1] = frame->buf[0]->data + avbuf->plane_info[0].bytesperline * avbuf->context->format.fmt.pix_mp.height;
381         frame->data[2] = frame->data[1] + ((avbuf->plane_info[0].bytesperline * avbuf->context->format.fmt.pix_mp.height) >> 2);
382         break;
383     default:
384         break;
385     }
386
387     /* 2. get frame information */
388     frame->key_frame = !!(avbuf->buf.flags & V4L2_BUF_FLAG_KEYFRAME);
389     frame->format = avbuf->context->av_pix_fmt;
390     frame->color_primaries = v4l2_get_color_primaries(avbuf);
391     frame->colorspace = v4l2_get_color_space(avbuf);
392     frame->color_range = v4l2_get_color_range(avbuf);
393     frame->color_trc = v4l2_get_color_trc(avbuf);
394     frame->pts = v4l2_get_pts(avbuf);
395
396     /* these two values are updated also during re-init in v4l2_process_driver_event */
397     frame->height = s->output.height;
398     frame->width = s->output.width;
399
400     /* 3. report errors upstream */
401     if (avbuf->buf.flags & V4L2_BUF_FLAG_ERROR) {
402         av_log(logger(avbuf), AV_LOG_ERROR, "%s: driver decode error\n", avbuf->context->name);
403         frame->decode_error_flags |= FF_DECODE_ERROR_INVALID_BITSTREAM;
404     }
405
406     return 0;
407 }
408
409 int ff_v4l2_buffer_buf_to_avpkt(AVPacket *pkt, V4L2Buffer *avbuf)
410 {
411     int ret;
412
413     av_packet_unref(pkt);
414     ret = v4l2_buf_to_bufref(avbuf, 0, &pkt->buf);
415     if (ret)
416         return ret;
417
418     pkt->size = V4L2_TYPE_IS_MULTIPLANAR(avbuf->buf.type) ? avbuf->buf.m.planes[0].bytesused : avbuf->buf.bytesused;
419     pkt->data = pkt->buf->data;
420
421     if (avbuf->buf.flags & V4L2_BUF_FLAG_KEYFRAME)
422         pkt->flags |= AV_PKT_FLAG_KEY;
423
424     if (avbuf->buf.flags & V4L2_BUF_FLAG_ERROR) {
425         av_log(logger(avbuf), AV_LOG_ERROR, "%s driver encode error\n", avbuf->context->name);
426         pkt->flags |= AV_PKT_FLAG_CORRUPT;
427     }
428
429     pkt->dts = pkt->pts = v4l2_get_pts(avbuf);
430
431     return 0;
432 }
433
434 int ff_v4l2_buffer_avpkt_to_buf(const AVPacket *pkt, V4L2Buffer *out)
435 {
436     int ret;
437
438     ret = v4l2_bufref_to_buf(out, 0, pkt->data, pkt->size, 0, pkt->buf);
439     if (ret)
440         return ret;
441
442     v4l2_set_pts(out, pkt->pts);
443
444     if (pkt->flags & AV_PKT_FLAG_KEY)
445         out->flags = V4L2_BUF_FLAG_KEYFRAME;
446
447     return 0;
448 }
449
450 int ff_v4l2_buffer_initialize(V4L2Buffer* avbuf, int index)
451 {
452     V4L2Context *ctx = avbuf->context;
453     int ret, i;
454
455     avbuf->buf.memory = V4L2_MEMORY_MMAP;
456     avbuf->buf.type = ctx->type;
457     avbuf->buf.index = index;
458
459     if (V4L2_TYPE_IS_MULTIPLANAR(ctx->type)) {
460         avbuf->buf.length = VIDEO_MAX_PLANES;
461         avbuf->buf.m.planes = avbuf->planes;
462     }
463
464     ret = ioctl(buf_to_m2mctx(avbuf)->fd, VIDIOC_QUERYBUF, &avbuf->buf);
465     if (ret < 0)
466         return AVERROR(errno);
467
468     if (V4L2_TYPE_IS_MULTIPLANAR(ctx->type)) {
469         avbuf->num_planes = 0;
470         for (;;) {
471             /* in MP, the V4L2 API states that buf.length means num_planes */
472             if (avbuf->num_planes >= avbuf->buf.length)
473                 break;
474             if (avbuf->buf.m.planes[avbuf->num_planes].length)
475                 avbuf->num_planes++;
476         }
477     } else
478         avbuf->num_planes = 1;
479
480     for (i = 0; i < avbuf->num_planes; i++) {
481
482         avbuf->plane_info[i].bytesperline = V4L2_TYPE_IS_MULTIPLANAR(ctx->type) ?
483             ctx->format.fmt.pix_mp.plane_fmt[i].bytesperline :
484             ctx->format.fmt.pix.bytesperline;
485
486         if (V4L2_TYPE_IS_MULTIPLANAR(ctx->type)) {
487             avbuf->plane_info[i].length = avbuf->buf.m.planes[i].length;
488             avbuf->plane_info[i].mm_addr = mmap(NULL, avbuf->buf.m.planes[i].length,
489                                            PROT_READ | PROT_WRITE, MAP_SHARED,
490                                            buf_to_m2mctx(avbuf)->fd, avbuf->buf.m.planes[i].m.mem_offset);
491         } else {
492             avbuf->plane_info[i].length = avbuf->buf.length;
493             avbuf->plane_info[i].mm_addr = mmap(NULL, avbuf->buf.length,
494                                           PROT_READ | PROT_WRITE, MAP_SHARED,
495                                           buf_to_m2mctx(avbuf)->fd, avbuf->buf.m.offset);
496         }
497
498         if (avbuf->plane_info[i].mm_addr == MAP_FAILED)
499             return AVERROR(ENOMEM);
500     }
501
502     avbuf->status = V4L2BUF_AVAILABLE;
503
504     if (V4L2_TYPE_IS_OUTPUT(ctx->type))
505         return 0;
506
507     if (V4L2_TYPE_IS_MULTIPLANAR(ctx->type)) {
508         avbuf->buf.m.planes = avbuf->planes;
509         avbuf->buf.length   = avbuf->num_planes;
510
511     } else {
512         avbuf->buf.bytesused = avbuf->planes[0].bytesused;
513         avbuf->buf.length    = avbuf->planes[0].length;
514     }
515
516     return ff_v4l2_buffer_enqueue(avbuf);
517 }
518
519 int ff_v4l2_buffer_enqueue(V4L2Buffer* avbuf)
520 {
521     int ret;
522
523     avbuf->buf.flags = avbuf->flags;
524
525     ret = ioctl(buf_to_m2mctx(avbuf)->fd, VIDIOC_QBUF, &avbuf->buf);
526     if (ret < 0)
527         return AVERROR(errno);
528
529     avbuf->status = V4L2BUF_IN_DRIVER;
530
531     return 0;
532 }