]> git.sesse.net Git - ffmpeg/blob - libavcodec/v4l2_buffers.c
avcodec/v4l2_buffers: split out AVFrame generation into helper method
[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 static int v4l2_buffer_buf_to_swframe(AVFrame *frame, V4L2Buffer *avbuf)
285 {
286     int i, ret;
287
288     frame->format = avbuf->context->av_pix_fmt;
289
290     for (i = 0; i < avbuf->num_planes; i++) {
291         ret = v4l2_buf_to_bufref(avbuf, i, &frame->buf[i]);
292         if (ret)
293             return ret;
294
295         frame->linesize[i] = avbuf->plane_info[i].bytesperline;
296         frame->data[i] = frame->buf[i]->data;
297     }
298
299     /* fixup special cases */
300     switch (avbuf->context->av_pix_fmt) {
301     case AV_PIX_FMT_NV12:
302     case AV_PIX_FMT_NV21:
303         if (avbuf->num_planes > 1)
304             break;
305         frame->linesize[1] = avbuf->plane_info[0].bytesperline;
306         frame->data[1] = frame->buf[0]->data + avbuf->plane_info[0].bytesperline * avbuf->context->format.fmt.pix_mp.height;
307         break;
308
309     case AV_PIX_FMT_YUV420P:
310         if (avbuf->num_planes > 1)
311             break;
312         frame->linesize[1] = avbuf->plane_info[0].bytesperline >> 1;
313         frame->linesize[2] = avbuf->plane_info[0].bytesperline >> 1;
314         frame->data[1] = frame->buf[0]->data + avbuf->plane_info[0].bytesperline * avbuf->context->format.fmt.pix_mp.height;
315         frame->data[2] = frame->data[1] + ((avbuf->plane_info[0].bytesperline * avbuf->context->format.fmt.pix_mp.height) >> 2);
316         break;
317
318     default:
319         break;
320     }
321
322     return 0;
323 }
324
325 /******************************************************************************
326  *
327  *              V4L2Buffer interface
328  *
329  ******************************************************************************/
330
331 int ff_v4l2_buffer_avframe_to_buf(const AVFrame *frame, V4L2Buffer *out)
332 {
333     int i, ret;
334     struct v4l2_format fmt = out->context->format;
335     int pixel_format = V4L2_TYPE_IS_MULTIPLANAR(fmt.type) ?
336                        fmt.fmt.pix_mp.pixelformat : fmt.fmt.pix.pixelformat;
337     int height       = V4L2_TYPE_IS_MULTIPLANAR(fmt.type) ?
338                        fmt.fmt.pix_mp.height : fmt.fmt.pix.height;
339     int is_planar_format = 0;
340
341     switch (pixel_format) {
342     case V4L2_PIX_FMT_YUV420M:
343     case V4L2_PIX_FMT_YVU420M:
344     case V4L2_PIX_FMT_YUV422M:
345     case V4L2_PIX_FMT_YVU422M:
346     case V4L2_PIX_FMT_YUV444M:
347     case V4L2_PIX_FMT_YVU444M:
348     case V4L2_PIX_FMT_NV12M:
349     case V4L2_PIX_FMT_NV21M:
350     case V4L2_PIX_FMT_NV12MT_16X16:
351     case V4L2_PIX_FMT_NV12MT:
352     case V4L2_PIX_FMT_NV16M:
353     case V4L2_PIX_FMT_NV61M:
354         is_planar_format = 1;
355     }
356
357     v4l2_set_pts(out, frame->pts);
358
359     if (!is_planar_format) {
360         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);
361         int planes_nb = 0;
362         int offset = 0;
363
364         for (i = 0; i < desc->nb_components; i++)
365             planes_nb = FFMAX(planes_nb, desc->comp[i].plane + 1);
366
367         for (i = 0; i < planes_nb; i++) {
368             int size, h = height;
369             if (i == 1 || i == 2) {
370                 h = AV_CEIL_RSHIFT(h, desc->log2_chroma_h);
371             }
372             size = frame->linesize[i] * h;
373             ret = v4l2_bufref_to_buf(out, 0, frame->data[i], size, offset, frame->buf[i]);
374             if (ret)
375                 return ret;
376             offset += size;
377         }
378         return 0;
379     }
380
381     for (i = 0; i < out->num_planes; i++) {
382         ret = v4l2_bufref_to_buf(out, i, frame->buf[i]->data, frame->buf[i]->size, 0, frame->buf[i]);
383         if (ret)
384             return ret;
385     }
386
387     return 0;
388 }
389
390 int ff_v4l2_buffer_buf_to_avframe(AVFrame *frame, V4L2Buffer *avbuf)
391 {
392     V4L2m2mContext *s = buf_to_m2mctx(avbuf);
393     int ret;
394
395     av_frame_unref(frame);
396
397     /* 1. get references to the actual data */
398     ret = v4l2_buffer_buf_to_swframe(frame, avbuf);
399     if (ret)
400         return ret;
401
402     /* 2. get frame information */
403     frame->key_frame = !!(avbuf->buf.flags & V4L2_BUF_FLAG_KEYFRAME);
404     frame->color_primaries = v4l2_get_color_primaries(avbuf);
405     frame->colorspace = v4l2_get_color_space(avbuf);
406     frame->color_range = v4l2_get_color_range(avbuf);
407     frame->color_trc = v4l2_get_color_trc(avbuf);
408     frame->pts = v4l2_get_pts(avbuf);
409
410     /* these two values are updated also during re-init in v4l2_process_driver_event */
411     frame->height = s->output.height;
412     frame->width = s->output.width;
413
414     /* 3. report errors upstream */
415     if (avbuf->buf.flags & V4L2_BUF_FLAG_ERROR) {
416         av_log(logger(avbuf), AV_LOG_ERROR, "%s: driver decode error\n", avbuf->context->name);
417         frame->decode_error_flags |= FF_DECODE_ERROR_INVALID_BITSTREAM;
418     }
419
420     return 0;
421 }
422
423 int ff_v4l2_buffer_buf_to_avpkt(AVPacket *pkt, V4L2Buffer *avbuf)
424 {
425     int ret;
426
427     av_packet_unref(pkt);
428     ret = v4l2_buf_to_bufref(avbuf, 0, &pkt->buf);
429     if (ret)
430         return ret;
431
432     pkt->size = V4L2_TYPE_IS_MULTIPLANAR(avbuf->buf.type) ? avbuf->buf.m.planes[0].bytesused : avbuf->buf.bytesused;
433     pkt->data = pkt->buf->data;
434
435     if (avbuf->buf.flags & V4L2_BUF_FLAG_KEYFRAME)
436         pkt->flags |= AV_PKT_FLAG_KEY;
437
438     if (avbuf->buf.flags & V4L2_BUF_FLAG_ERROR) {
439         av_log(logger(avbuf), AV_LOG_ERROR, "%s driver encode error\n", avbuf->context->name);
440         pkt->flags |= AV_PKT_FLAG_CORRUPT;
441     }
442
443     pkt->dts = pkt->pts = v4l2_get_pts(avbuf);
444
445     return 0;
446 }
447
448 int ff_v4l2_buffer_avpkt_to_buf(const AVPacket *pkt, V4L2Buffer *out)
449 {
450     int ret;
451
452     ret = v4l2_bufref_to_buf(out, 0, pkt->data, pkt->size, 0, pkt->buf);
453     if (ret)
454         return ret;
455
456     v4l2_set_pts(out, pkt->pts);
457
458     if (pkt->flags & AV_PKT_FLAG_KEY)
459         out->flags = V4L2_BUF_FLAG_KEYFRAME;
460
461     return 0;
462 }
463
464 int ff_v4l2_buffer_initialize(V4L2Buffer* avbuf, int index)
465 {
466     V4L2Context *ctx = avbuf->context;
467     int ret, i;
468
469     avbuf->buf.memory = V4L2_MEMORY_MMAP;
470     avbuf->buf.type = ctx->type;
471     avbuf->buf.index = index;
472
473     if (V4L2_TYPE_IS_MULTIPLANAR(ctx->type)) {
474         avbuf->buf.length = VIDEO_MAX_PLANES;
475         avbuf->buf.m.planes = avbuf->planes;
476     }
477
478     ret = ioctl(buf_to_m2mctx(avbuf)->fd, VIDIOC_QUERYBUF, &avbuf->buf);
479     if (ret < 0)
480         return AVERROR(errno);
481
482     if (V4L2_TYPE_IS_MULTIPLANAR(ctx->type)) {
483         avbuf->num_planes = 0;
484         for (;;) {
485             /* in MP, the V4L2 API states that buf.length means num_planes */
486             if (avbuf->num_planes >= avbuf->buf.length)
487                 break;
488             if (avbuf->buf.m.planes[avbuf->num_planes].length)
489                 avbuf->num_planes++;
490         }
491     } else
492         avbuf->num_planes = 1;
493
494     for (i = 0; i < avbuf->num_planes; i++) {
495
496         avbuf->plane_info[i].bytesperline = V4L2_TYPE_IS_MULTIPLANAR(ctx->type) ?
497             ctx->format.fmt.pix_mp.plane_fmt[i].bytesperline :
498             ctx->format.fmt.pix.bytesperline;
499
500         if (V4L2_TYPE_IS_MULTIPLANAR(ctx->type)) {
501             avbuf->plane_info[i].length = avbuf->buf.m.planes[i].length;
502             avbuf->plane_info[i].mm_addr = mmap(NULL, avbuf->buf.m.planes[i].length,
503                                            PROT_READ | PROT_WRITE, MAP_SHARED,
504                                            buf_to_m2mctx(avbuf)->fd, avbuf->buf.m.planes[i].m.mem_offset);
505         } else {
506             avbuf->plane_info[i].length = avbuf->buf.length;
507             avbuf->plane_info[i].mm_addr = mmap(NULL, avbuf->buf.length,
508                                           PROT_READ | PROT_WRITE, MAP_SHARED,
509                                           buf_to_m2mctx(avbuf)->fd, avbuf->buf.m.offset);
510         }
511
512         if (avbuf->plane_info[i].mm_addr == MAP_FAILED)
513             return AVERROR(ENOMEM);
514     }
515
516     avbuf->status = V4L2BUF_AVAILABLE;
517
518     if (V4L2_TYPE_IS_OUTPUT(ctx->type))
519         return 0;
520
521     if (V4L2_TYPE_IS_MULTIPLANAR(ctx->type)) {
522         avbuf->buf.m.planes = avbuf->planes;
523         avbuf->buf.length   = avbuf->num_planes;
524
525     } else {
526         avbuf->buf.bytesused = avbuf->planes[0].bytesused;
527         avbuf->buf.length    = avbuf->planes[0].length;
528     }
529
530     return ff_v4l2_buffer_enqueue(avbuf);
531 }
532
533 int ff_v4l2_buffer_enqueue(V4L2Buffer* avbuf)
534 {
535     int ret;
536
537     avbuf->buf.flags = avbuf->flags;
538
539     ret = ioctl(buf_to_m2mctx(avbuf)->fd, VIDIOC_QBUF, &avbuf->buf);
540     if (ret < 0)
541         return AVERROR(errno);
542
543     avbuf->status = V4L2BUF_IN_DRIVER;
544
545     return 0;
546 }