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