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