Debian Codegraph @

utils/v4l2-ctl/v4l2-ctl-streaming.cpp

raw
1 #include <cstring>
2
3 #include <netdb.h>
4 #include <sys/types.h>
5
6 #include <linux/media.h>
7
8 #include "compiler.h"
9 #include "v4l2-ctl.h"
10 #include "v4l-stream.h"
11 #include <media-info.h>
12
13 extern "C" {
14 #include "v4l2-tpg.h"
15 }
16
17 static unsigned stream_count;
18 static unsigned stream_skip;
19 static __u32 memory = V4L2_MEMORY_MMAP;
20 static __u32 out_memory = V4L2_MEMORY_MMAP;
21 static int stream_sleep_count = -1;
22 static int stream_sleep_ms = 1000;
23 static unsigned stream_sleep_mode = 1;
24 static bool stream_no_query;
25 static unsigned stream_pat;
26 static bool stream_loop;
27 static bool stream_out_square;
28 static bool stream_out_border;
29 static bool stream_out_sav;
30 static bool stream_out_eav;
31 static int stream_out_pixel_aspect = -1;
32 static tpg_video_aspect stream_out_video_aspect;
33 static u8 stream_out_alpha;
34 static bool stream_out_alpha_red_only;
35 static bool stream_out_rgb_lim_range;
36 static unsigned stream_out_perc_fill = 100;
37 static v4l2_std_id stream_out_std;
38 static bool stream_out_refresh;
39 static tpg_move_mode stream_out_hor_mode = TPG_MOVE_NONE;
40 static tpg_move_mode stream_out_vert_mode = TPG_MOVE_NONE;
41 static unsigned reqbufs_count_cap = 0;
42 static unsigned reqbufs_count_out = 0;
43 static char *file_to;
44 static bool to_with_hdr;
45 static char *host_to;
46 #ifndef NO_STREAM_TO
47 static unsigned host_port_to = V4L_STREAM_PORT;
48 static unsigned bpl_cap[VIDEO_MAX_PLANES];
49 #endif
50 static bool host_lossless;
51 static int host_fd_to = -1;
52 static unsigned comp_perc;
53 static unsigned comp_perc_count;
54 static char *file_from;
55 static bool from_with_hdr;
56 static char *host_from;
57 static unsigned host_port_from = V4L_STREAM_PORT;
58 static int host_fd_from = -1;
59 static struct tpg_data tpg;
60 static unsigned output_field = V4L2_FIELD_NONE;
61 static bool output_field_alt;
62 static unsigned bpl_out[VIDEO_MAX_PLANES];
63 static bool last_buffer = false;
64 static codec_ctx *ctx;
65
66 static unsigned int cropped_width;
67 static unsigned int cropped_height;
68 static unsigned int composed_width;
69 static unsigned int composed_height;
70 static bool support_cap_compose;
71 static bool support_out_crop;
72 static bool in_source_change_event;
73
74 static __u64 last_fwht_bf_ts;
75 static fwht_cframe_hdr last_fwht_hdr;
76
77 struct request_fwht {
78 int fd;
79 __u64 ts;
80 struct v4l2_ctrl_fwht_params params;
81 };
82
83 static request_fwht fwht_reqs[VIDEO_MAX_FRAME];
84
85 #define TS_WINDOW 241
86 #define FILE_HDR_ID v4l2_fourcc('V', 'h', 'd', 'r')
87
88 enum codec_type {
89 NOT_CODEC,
90 ENCODER,
91 DECODER
92 };
93
94 static enum codec_type codec_type;
95
96 #define QUEUE_ERROR -1
97 #define QUEUE_STOPPED -2
98 #define QUEUE_OFF_ON -3
99
100 class fps_timestamps {
101 private:
102 unsigned idx;
103 bool full;
104 double first;
105 double sum;
106 double ts[TS_WINDOW];
107 unsigned seq[TS_WINDOW];
108 unsigned dropped_buffers;
109 bool alternate_fields;
110 unsigned field_cnt;
111 unsigned last_field;
112
113 public:
114 fps_timestamps()
115 {
116 reset();
117 }
118
119 void reset() {
120 idx = 0;
121 full = false;
122 first = sum = 0;
123 dropped_buffers = 0;
124 last_field = 0;
125 field_cnt = 0;
126 alternate_fields = false;
127 }
128
129 void determine_field(int fd, unsigned type);
130 bool add_ts(double ts_secs, unsigned sequence, unsigned field);
131 bool has_fps(bool continuous);
132 double fps();
133 unsigned dropped();
134 };
135
136 static bool need_sleep(unsigned count)
137 {
138 if (stream_sleep_count <= 0)
139 return false;
140
141 if (!(stream_sleep_mode & 1) && count > (unsigned)stream_sleep_count)
142 return false;
143
144 return !(count % stream_sleep_count);
145 }
146
147 static void do_sleep()
148 {
149 int ms = stream_sleep_ms;
150
151 if (!ms) {
152 // For modes 2 and 3 just don't sleep in this case
153 if (stream_sleep_mode >= 2) {
154 stderr_info("streamoff, streamon\n");
155 return;
156 }
157
158 stderr_info("sleeping forever...\n");
159 while (1)
160 sleep(100);
161 }
162
163 if (ms < 0)
164 ms = ((__u64)-ms * rand()) / RAND_MAX + 1;
165
166 if (stream_sleep_mode >= 2)
167 stderr_info("streamoff, sleep %d ms, streamon\n", ms);
168 else if (stream_sleep_ms < 0 || verbose)
169 stderr_info("sleep %d ms\n", ms);
170 else
171 stderr_info("\n");
172 fflush(stderr);
173
174 struct timespec t;
175 t.tv_sec = ms / 1000;
176 t.tv_nsec = (ms % 1000) * 1000000;
177 nanosleep(&t, NULL);
178 }
179
180 void fps_timestamps::determine_field(int fd, unsigned type)
181 {
182 struct v4l2_format fmt = { };
183
184 fmt.type = type;
185 ioctl(fd, VIDIOC_G_FMT, &fmt);
186 cv4l_fmt cfmt(fmt);
187 alternate_fields = cfmt.g_field() == V4L2_FIELD_ALTERNATE;
188 }
189
190 bool fps_timestamps::add_ts(double ts_secs, unsigned sequence, unsigned field)
191 {
192 if (ts_secs <= 0) {
193 struct timespec ts_cur;
194
195 clock_gettime(CLOCK_MONOTONIC, &ts_cur);
196 ts_secs = ts_cur.tv_sec + ts_cur.tv_nsec / 1000000000.0;
197 }
198
199 if (alternate_fields &&
200 field != V4L2_FIELD_TOP && field != V4L2_FIELD_BOTTOM)
201 return false;
202
203 if (!full && idx == 0) {
204 ts[idx] = ts_secs;
205 seq[TS_WINDOW - 1] = sequence;
206 seq[idx++] = sequence;
207 first = ts_secs;
208 last_field = field;
209 field_cnt++;
210 return true;
211 }
212
213 unsigned prev_idx = (idx + TS_WINDOW - 1) % TS_WINDOW;
214 unsigned next_idx = (idx + 1) % TS_WINDOW;
215
216 if (seq[prev_idx] == sequence) {
217 if (alternate_fields) {
218 if (last_field == field)
219 return false;
220 if (field_cnt != 1)
221 return false;
222 field_cnt++;
223 last_field = field;
224 }
225 } else {
226 if (alternate_fields) {
227 if (field_cnt == 1) {
228 dropped_buffers++;
229 last_field = last_field == V4L2_FIELD_TOP ?
230 V4L2_FIELD_BOTTOM : V4L2_FIELD_TOP;
231 }
232 field_cnt = 1;
233 if (field == last_field) {
234 dropped_buffers++;
235 field_cnt++;
236 }
237 last_field = field;
238 }
239 if (seq[prev_idx] - sequence > 1) {
240 unsigned dropped = sequence - seq[prev_idx] - 1;
241
242 if (alternate_fields)
243 dropped *= 2;
244 dropped_buffers += dropped;
245 }
246 }
247
248 if (!full) {
249 sum += ts_secs - ts[idx - 1];
250 ts[idx] = ts_secs;
251 seq[idx++] = sequence;
252 if (idx == TS_WINDOW) {
253 full = true;
254 idx = 0;
255 }
256 return true;
257 }
258
259 sum -= ts[next_idx] - ts[idx];
260 ts[idx] = ts_secs;
261 seq[idx] = sequence;
262 idx = next_idx;
263 sum += ts_secs - ts[prev_idx];
264 return true;
265 }
266
267 bool fps_timestamps::has_fps(bool continuous = false)
268 {
269 unsigned prev_idx = (idx + TS_WINDOW - 1) % TS_WINDOW;
270
271 if (!continuous && ts[prev_idx] - first < 1.0)
272 return false;
273 return full || idx > 4;
274 }
275
276 unsigned fps_timestamps::dropped()
277 {
278 unsigned res = dropped_buffers;
279
280 dropped_buffers = 0;
281 return res;
282 }
283
284 double fps_timestamps::fps()
285 {
286 unsigned prev_idx = (idx + TS_WINDOW - 1) % TS_WINDOW;
287 double cnt = seq[prev_idx] - seq[full ? idx : 0];
288 double period = sum / cnt;
289 double fps = 1.0 / period;
290
291 first += static_cast<unsigned>(ts[prev_idx] - first);
292 return fps;
293 };
294
295 void streaming_usage()
296 {
297 printf("\nVideo Streaming options:\n"
298 " --stream-count <count>\n"
299 " stream <count> buffers. The default is to keep streaming\n"
300 " forever. This count does not include the number of initial\n"
301 " skipped buffers as is passed by --stream-skip.\n"
302 " --stream-skip <count>\n"
303 " skip the first <count> buffers. The default is 0.\n"
304 " --stream-sleep count=<c>,sleep=<ms>,mode=<mode>\n"
305 " Sleep for <ms> milliseconds (default=1000) after <c> buffers.\n"
306 " If <c> is 0, then only sleep right after streaming starts.\n"
307 " If <ms> is 0, then sleep forever (modes 0 and 1) or not at all\n"
308 " (for modes 2 and 3), if <ms> is positive, then sleep for <ms>\n"
309 " milliseconds, if <ms> is negative, then sleep for a random\n"
310 " time between 1 and -<ms> milliseconds.\n"
311 " There are different modes for this:\n"
312 " <mode>=0: the sleep happens only once after <c> buffers.\n"
313 " <mode>=1: the sleep happens every <c> buffers (default).\n"
314 " <mode>=2: as 0, but call STREAMOFF/ON before/after the sleep.\n"
315 " <mode>=3: as 1, but call STREAMOFF/ON before/after the sleep.\n"
316 #ifndef NO_STREAM_TO
317 " --stream-to <file> stream to this file. The default is to discard the\n"
318 " data. If <file> is '-', then the data is written to stdout\n"
319 " and the --silent option is turned on automatically.\n"
320 " --stream-to-hdr <file> stream to this file. Same as --stream-to, but each\n"
321 " frame is prefixed by a header. Use for compressed data.\n"
322 " --stream-to-host <hostname[:port]>\n"
323 " stream to this host. The default port is %d.\n"
324 " --stream-lossless always use lossless video compression.\n"
325 #endif
326 " --stream-poll use non-blocking mode and select() to stream.\n"
327 " --stream-buf-caps show capture buffer capabilities\n"
328 "  --stream-show-delta-now\n"
329 "                     output the difference between the buffer timestamp and current\n"
330 "                     clock, if the buffer timestamp source is the monotonic clock.\n"
331 "                     Requires --verbose as well.\n"
332 " --stream-mmap <count>\n"
333 " capture video using mmap() [VIDIOC_(D)QBUF]\n"
334 " count: the number of buffers to allocate. The default is 3.\n"
335 " --stream-user <count>\n"
336 " capture video using user pointers [VIDIOC_(D)QBUF]\n"
337 " count: the number of buffers to allocate. The default is 3.\n"
338 " --stream-dmabuf capture video using dmabuf [VIDIOC_(D)QBUF]\n"
339 " Requires a corresponding --stream-out-mmap option.\n"
340 " --stream-from <file>\n"
341 " stream from this file. The default is to generate a pattern.\n"
342 " If <file> is '-', then the data is read from stdin.\n"
343 " --stream-from-hdr <file> stream from this file. Same as --stream-from, but each\n"
344 " frame is prefixed by a header. Use for compressed data.\n"
345 " --stream-from-host <hostname[:port]>\n"
346 " stream from this host. The default port is %d.\n"
347 " --stream-no-query Do not query and set the DV timings or standard before streaming.\n"
348 " --stream-loop loop when the end of the file we are streaming from is reached.\n"
349 " The default is to stop.\n"
350 " --stream-out-pattern <count>\n"
351 " choose output test pattern. The default is 0.\n"
352 " --stream-out-square\n"
353 " show a square in the middle of the output test pattern.\n"
354 " --stream-out-border\n"
355 " show a border around the pillar/letterboxed video.\n"
356 " --stream-out-sav insert an SAV code in every line.\n"
357 " --stream-out-eav insert an EAV code in every line.\n"
358 " --stream-out-pixel-aspect <aspect>\n"
359 " select a pixel aspect ratio. The default is to autodetect.\n"
360 " <aspect> can be one of: square, ntsc, pal\n"
361 " --stream-out-video-aspect <aspect>\n"
362 " select a video aspect ratio. The default is to use the frame ratio.\n"
363 " <aspect> can be one of: 4x3, 14x9, 16x9, anamorphic\n"
364 " --stream-out-alpha <alpha-value>\n"
365 " value to use for the alpha component, range 0-255. The default is 0.\n"
366 " --stream-out-alpha-red-only\n"
367 " only use the --stream-out-alpha value for the red colors,\n"
368 " for all others use 0.\n"
369 " --stream-out-rgb-lim-range\n"
370 " Encode RGB values as limited [16-235] instead of full range.\n"
371 " --stream-out-hor-speed <speed>\n"
372 " choose speed for horizontal movement. The default is 0,\n"
373 " and the range is [-3...3].\n"
374 " --stream-out-vert-speed <speed>\n"
375 " choose speed for vertical movement. The default is 0,\n"
376 " and the range is [-3...3].\n"
377 " --stream-out-perc-fill <percentage>\n"
378 " percentage of the frame to actually fill. The default is 100%%.\n"
379 " --stream-out-buf-caps\n"
380 " show output buffer capabilities\n"
381 " --stream-out-mmap <count>\n"
382 " output video using mmap() [VIDIOC_(D)QBUF]\n"
383 " count: the number of buffers to allocate. The default is 4.\n"
384 " --stream-out-user <count>\n"
385 " output video using user pointers [VIDIOC_(D)QBUF]\n"
386 " count: the number of buffers to allocate. The default is 4.\n"
387 " --stream-out-dmabuf\n"
388 " output video using dmabuf [VIDIOC_(D)QBUF]\n"
389 " Requires a corresponding --stream-mmap option.\n"
390 " --list-patterns list available patterns for use with --stream-out-pattern.\n"
391 " --list-buffers list all video buffers [VIDIOC_QUERYBUF]\n"
392 " --list-buffers-out list all video output buffers [VIDIOC_QUERYBUF]\n"
393 " --list-buffers-vbi list all VBI buffers [VIDIOC_QUERYBUF]\n"
394 " --list-buffers-vbi-out\n"
395 " list all VBI output buffers [VIDIOC_QUERYBUF]\n"
396 " --list-buffers-sliced-vbi\n"
397 " list all sliced VBI buffers [VIDIOC_QUERYBUF]\n"
398 " --list-buffers-sliced-vbi-out\n"
399 " list all sliced VBI output buffers [VIDIOC_QUERYBUF]\n"
400 " --list-buffers-sdr\n"
401 " list all SDR RX buffers [VIDIOC_QUERYBUF]\n"
402 " --list-buffers-sdr-out\n"
403 " list all SDR TX buffers [VIDIOC_QUERYBUF]\n"
404 " --list-buffers-meta\n"
405 " list all Meta RX buffers [VIDIOC_QUERYBUF]\n",
406 #ifndef NO_STREAM_TO
407 V4L_STREAM_PORT,
408 #endif
409 V4L_STREAM_PORT);
410 }
411
412 static void get_codec_type(cv4l_fd &fd)
413 {
414 cv4l_disable_trace dt(fd);
415 struct v4l2_fmtdesc fmt_desc = {};
416 int num_cap_fmts = 0;
417 int num_compressed_cap_fmts = 0;
418 int num_out_fmts = 0;
419 int num_compressed_out_fmts = 0;
420
421 codec_type = NOT_CODEC;
422
423 if (!fd.has_vid_m2m())
424 return;
425
426 if (fd.enum_fmt(fmt_desc, true, 0, fd.g_type()))
427 return;
428
429 do {
430 if (is_codec_format(fmt_desc))
431 num_compressed_cap_fmts++;
432 num_cap_fmts++;
433 } while (!fd.enum_fmt(fmt_desc));
434
435
436 if (fd.enum_fmt(fmt_desc, true, 0, v4l_type_invert(fd.g_type())))
437 return;
438
439 do {
440 if (is_codec_format(fmt_desc))
441 num_compressed_out_fmts++;
442 num_out_fmts++;
443 } while (!fd.enum_fmt(fmt_desc));
444
445 if (num_compressed_out_fmts == 0 && num_compressed_cap_fmts == num_cap_fmts) {
446 codec_type = ENCODER;
447 return;
448 }
449
450 if (num_compressed_cap_fmts == 0 && num_compressed_out_fmts == num_out_fmts) {
451 codec_type = DECODER;
452 return;
453 }
454 }
455
456 static void get_cap_compose_rect(cv4l_fd &fd)
457 {
458 cv4l_disable_trace dt(fd);
459 v4l2_selection sel;
460
461 memset(&sel, 0, sizeof(sel));
462 sel.type = vidcap_buftype;
463 sel.target = V4L2_SEL_TGT_COMPOSE;
464
465 if (fd.g_selection(sel) == 0) {
466 support_cap_compose = true;
467 composed_width = sel.r.width;
468 composed_height = sel.r.height;
469 } else {
470 support_cap_compose = false;
471 }
472 }
473
474 static void get_out_crop_rect(cv4l_fd &fd)
475 {
476 cv4l_disable_trace dt(fd);
477 v4l2_selection sel;
478
479 memset(&sel, 0, sizeof(sel));
480 sel.type = vidout_buftype;
481 sel.target = V4L2_SEL_TGT_CROP;
482
483 if (fd.g_selection(sel) == 0) {
484 support_out_crop = true;
485 cropped_width = sel.r.width;
486 cropped_height = sel.r.height;
487 } else {
488 support_out_crop = false;
489 }
490 }
491
492 static void set_time_stamp(cv4l_buffer &buf)
493 {
494 if ((buf.g_flags() & V4L2_BUF_FLAG_TIMESTAMP_MASK) != V4L2_BUF_FLAG_TIMESTAMP_COPY)
495 return;
496 buf.s_timestamp_clock();
497 }
498
499 static __u32 read_u32(FILE *f)
500 {
501 __u32 v;
502
503 if (fread(&v, 1, sizeof(v), f) != sizeof(v))
504 return 0;
505 return ntohl(v);
506 }
507
508 static void write_u32(FILE *f, __u32 v)
509 {
510 v = htonl(v);
511 fwrite(&v, 1, sizeof(v), f);
512 }
513
514 static std::string timestamp_type2s(__u32 flags)
515 {
516 char buf[20];
517
518 switch (flags & V4L2_BUF_FLAG_TIMESTAMP_MASK) {
519 case V4L2_BUF_FLAG_TIMESTAMP_UNKNOWN:
520 return "Unknown";
521 case V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC:
522 return "Monotonic";
523 case V4L2_BUF_FLAG_TIMESTAMP_COPY:
524 return "Copy";
525 default:
526 sprintf(buf, "Type %d", (flags & V4L2_BUF_FLAG_TIMESTAMP_MASK) >> 13);
527 return std::string(buf);
528 }
529 }
530
531 static std::string timestamp_src2s(__u32 flags)
532 {
533 char buf[20];
534
535 switch (flags & V4L2_BUF_FLAG_TSTAMP_SRC_MASK) {
536 case V4L2_BUF_FLAG_TSTAMP_SRC_EOF:
537 return "End-of-Frame";
538 case V4L2_BUF_FLAG_TSTAMP_SRC_SOE:
539 return "Start-of-Exposure";
540 default:
541 sprintf(buf, "Source %d", (flags & V4L2_BUF_FLAG_TSTAMP_SRC_MASK) >> 16);
542 return std::string(buf);
543 }
544 }
545
546 static void print_buffer(FILE *f, struct v4l2_buffer &buf)
547 {
548 const unsigned ts_flags = V4L2_BUF_FLAG_TIMESTAMP_MASK | V4L2_BUF_FLAG_TSTAMP_SRC_MASK;
549
550 fprintf(f, "\tIndex : %d\n", buf.index);
551 fprintf(f, "\tType : %s\n", buftype2s(buf.type).c_str());
552 fprintf(f, "\tFlags : %s\n", bufferflags2s(buf.flags & ~ts_flags).c_str());
553 fprintf(f, "\tField : %s\n", field2s(buf.field).c_str());
554 fprintf(f, "\tSequence : %u\n", buf.sequence);
555 fprintf(f, "\tLength : %u\n", buf.length);
556 fprintf(f, "\tBytesused: %u\n", buf.bytesused);
557 fprintf(f, "\tTimestamp: %llu.%06llus (%s, %s)\n",
558 static_cast<__u64>(buf.timestamp.tv_sec), static_cast<__u64>(buf.timestamp.tv_usec),
559 timestamp_type2s(buf.flags).c_str(), timestamp_src2s(buf.flags).c_str());
560 if (buf.flags & V4L2_BUF_FLAG_TIMECODE) {
561 static constexpr int fps_types[] = { 0, 24, 25, 30, 50, 60 };
562 int fps = buf.timecode.type;
563
564 if (fps > 5)
565 fps = 0;
566 fprintf(f, "\tTimecode : %dfps %s %dh %dm %ds %df (0x%02x 0x%02x 0x%02x 0x%02x)\n",
567 fps_types[fps],
568 tc_flags2s(buf.timecode.flags).c_str(),
569 buf.timecode.hours, buf.timecode.minutes,
570 buf.timecode.seconds, buf.timecode.frames,
571 buf.timecode.userbits[0], buf.timecode.userbits[1],
572 buf.timecode.userbits[2], buf.timecode.userbits[3]);
573 }
574 if (buf.type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE ||
575 buf.type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) {
576 for (unsigned i = 0; i < buf.length; i++) {
577 struct v4l2_plane *p = buf.m.planes + i;
578
579 fprintf(f, "\tPlane : %d\n", i);
580 fprintf(f, "\t\tLength : %u\n", p->length);
581 fprintf(f, "\t\tBytesused : %u\n", p->bytesused);
582 fprintf(f, "\t\tData Offset: %u\n", p->data_offset);
583 }
584 }
585
586 fprintf(f, "\n");
587 }
588
589 static void print_concise_buffer(FILE *f, cv4l_buffer &buf, cv4l_fmt &fmt,
590 cv4l_queue &q, fps_timestamps &fps_ts,
591 int comp_perc, bool skip_ts = false)
592 {
593 static double last_ts;
594
595 fprintf(f, "%s dqbuf: %*u seq: %6u bytesused: ",
596 v4l_type_is_output(buf.g_type()) ? "out" : "cap",
597 reqbufs_count_cap > 10 ? 2 : 1, buf.g_index(), buf.g_sequence());
598
599 bool have_data_offset = false;
600
601 for (unsigned i = 0; i < buf.g_num_planes(); i++) {
602 fprintf(f, "%s%u", i ? "/" : "", buf.g_bytesused(i));
603 if (buf.g_data_offset(i))
604 have_data_offset = true;
605 }
606 if (have_data_offset) {
607 fprintf(f, " offset: ");
608 for (unsigned i = 0; i < buf.g_num_planes(); i++)
609 fprintf(f, "%s%u", i ? "/" : "", buf.g_data_offset(i));
610 }
611 if (comp_perc >= 0)
612 fprintf(f, " compression: %d%%", comp_perc);
613
614 if (!skip_ts && (buf.g_flags() & V4L2_BUF_FLAG_TIMESTAMP_MASK) != V4L2_BUF_FLAG_TIMESTAMP_COPY) {
615 double ts = buf.g_timestamp().tv_sec + buf.g_timestamp().tv_usec / 1000000.0;
616 fprintf(f, " ts: %.06f", ts);
617 if (last_ts != 0.0)
618 fprintf(f, " delta: %.03f ms", (ts - last_ts) * 1000.0);
619 if (options[OptStreamShowDeltaNow] &&
620 (buf.g_flags() & V4L2_BUF_FLAG_TIMESTAMP_MASK) ==
621 V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC) {
622 timespec ts_clock;
623
624 clock_gettime(CLOCK_MONOTONIC, &ts_clock);
625 fprintf(f, " delta now: %+.03f ms",
626 ((ts_clock.tv_sec + ts_clock.tv_nsec / 1000000000.0) - ts) * 1000.0);
627 }
628 last_ts = ts;
629
630 if (fps_ts.has_fps(true))
631 fprintf(stderr, " fps: %.02f", fps_ts.fps());
632
633 unsigned dropped = fps_ts.dropped();
634
635 if (dropped)
636 fprintf(stderr, " dropped: %u", dropped);
637 }
638
639 fprintf(f, " field: %s", field2s(buf.g_field()).c_str());
640
641 __u32 fl = buf.g_flags() & (V4L2_BUF_FLAG_ERROR |
642 V4L2_BUF_FLAG_KEYFRAME |
643 V4L2_BUF_FLAG_PFRAME |
644 V4L2_BUF_FLAG_BFRAME |
645 V4L2_BUF_FLAG_LAST |
646 V4L2_BUF_FLAG_TIMESTAMP_MASK |
647 V4L2_BUF_FLAG_TSTAMP_SRC_MASK |
648 V4L2_BUF_FLAG_TIMECODE);
649 if (fl)
650 fprintf(f, " (%s)", bufferflags2s(fl).c_str());
651 fprintf(f, "\n");
652 if (v4l_type_is_meta(buf.g_type()) && buf.g_bytesused(0) &&
653 !(buf.g_flags() & V4L2_BUF_FLAG_ERROR))
654 print_meta_buffer(f, buf, fmt, q);
655
656 if ((capabilities & V4L2_CAP_TOUCH) && buf.g_bytesused(0) &&
657 !(buf.g_flags() & V4L2_BUF_FLAG_ERROR) &&
658 (fmt.g_width() < 64 || fmt.g_height() < 64))
659 print_touch_buffer(f, buf, fmt, q);
660 }
661
662 static void stream_buf_caps(cv4l_fd &fd, unsigned buftype)
663 {
664 v4l2_create_buffers cbufs;
665
666 memset(&cbufs, 0, sizeof(cbufs));
667 cbufs.format.type = buftype;
668 cbufs.memory = V4L2_MEMORY_MMAP;
669 if (!v4l_ioctl(fd.g_v4l_fd(), VIDIOC_CREATE_BUFS, &cbufs)) {
670 bool has_max_num_buffers =
671 cbufs.capabilities & V4L2_BUF_CAP_SUPPORTS_MAX_NUM_BUFFERS;
672
673 cbufs.capabilities &= ~V4L2_BUF_CAP_SUPPORTS_MAX_NUM_BUFFERS;
674 printf("Streaming I/O Capabilities for %s: %s",
675 buftype2s(buftype).c_str(),
676 bufcap2s(cbufs.capabilities).c_str());
677 if (has_max_num_buffers)
678 printf(", max-num-buffers=%u", cbufs.max_num_buffers);
679 printf("\n");
680 return;
681 }
682 v4l2_requestbuffers rbufs;
683 memset(&rbufs, 0, sizeof(rbufs));
684 rbufs.type = buftype;
685 rbufs.memory = V4L2_MEMORY_MMAP;
686 if (v4l_ioctl(fd.g_v4l_fd(), VIDIOC_REQBUFS, &rbufs))
687 return;
688 printf("Streaming I/O Capabilities for %s: %s\n",
689 buftype2s(buftype).c_str(),
690 bufcap2s(rbufs.capabilities).c_str());
691 }
692
693 static void list_buffers(cv4l_fd &fd, unsigned buftype)
694 {
695 cv4l_disable_trace dt(fd);
696 int i;
697
698 for (i = 0; i < VIDEO_MAX_FRAME; i++) {
699 cv4l_buffer buf(buftype);
700
701 if (fd.querybuf(buf, i))
702 break;
703 if (i == 0)
704 printf("VIDIOC_QUERYBUF:\n");
705 print_buffer(stdout, buf.buf);
706 }
707 }
708
709 void streaming_cmd(int ch, char *optarg)
710 {
711 char *value, *subs;
712 unsigned i;
713 int speed;
714
715 switch (ch) {
716 case OptStreamCount:
717 stream_count = strtoul(optarg, nullptr, 0);
718 break;
719 case OptStreamSkip:
720 stream_skip = strtoul(optarg, nullptr, 0);
721 break;
722 case OptStreamSleep:
723 subs = optarg;
724 while (*subs != '\0') {
725 static constexpr const char *subopts[] = {
726 "count",
727 "sleep",
728 "mode",
729 nullptr
730 };
731
732 switch (parse_subopt(&subs, subopts, &value)) {
733 case 0:
734 stream_sleep_count = strtoul(value, nullptr, 0);
735 break;
736 case 1:
737 stream_sleep_ms = strtoul(value, nullptr, 0);
738 break;
739 case 2:
740 stream_sleep_mode = strtoul(value, nullptr, 0);
741 if (stream_sleep_mode < 4)
742 break;
743 fallthrough;
744 default:
745 streaming_usage();
746 std::exit(EXIT_FAILURE);
747 }
748 }
749 break;
750 case OptStreamNoQuery:
751 stream_no_query = true;
752 break;
753 case OptStreamLoop:
754 stream_loop = true;
755 break;
756 case OptStreamOutPattern:
757 stream_pat = strtoul(optarg, nullptr, 0);
758 for (i = 0; tpg_pattern_strings[i]; i++) ;
759 if (stream_pat >= i)
760 stream_pat = 0;
761 break;
762 case OptStreamOutSquare:
763 stream_out_square = true;
764 break;
765 case OptStreamOutBorder:
766 stream_out_border = true;
767 break;
768 case OptStreamOutInsertSAV:
769 stream_out_sav = true;
770 break;
771 case OptStreamOutInsertEAV:
772 stream_out_eav = true;
773 break;
774 case OptStreamOutPixelAspect:
775 if (!strcmp(optarg, "square"))
776 stream_out_pixel_aspect = TPG_PIXEL_ASPECT_SQUARE;
777 else if (!strcmp(optarg, "ntsc"))
778 stream_out_pixel_aspect = TPG_PIXEL_ASPECT_NTSC;
779 else if (!strcmp(optarg, "pal"))
780 stream_out_pixel_aspect = TPG_PIXEL_ASPECT_PAL;
781 else
782 streaming_usage();
783 break;
784 case OptStreamOutVideoAspect:
785 if (!strcmp(optarg, "4x3"))
786 stream_out_video_aspect = TPG_VIDEO_ASPECT_4X3;
787 else if (!strcmp(optarg, "14x9"))
788 stream_out_video_aspect = TPG_VIDEO_ASPECT_14X9_CENTRE;
789 else if (!strcmp(optarg, "16x9"))
790 stream_out_video_aspect = TPG_VIDEO_ASPECT_16X9_CENTRE;
791 else if (!strcmp(optarg, "anamorphic"))
792 stream_out_video_aspect = TPG_VIDEO_ASPECT_16X9_ANAMORPHIC;
793 else
794 streaming_usage();
795 break;
796 case OptStreamOutAlphaComponent:
797 stream_out_alpha = strtoul(optarg, nullptr, 0);
798 break;
799 case OptStreamOutAlphaRedOnly:
800 stream_out_alpha_red_only = true;
801 break;
802 case OptStreamOutRGBLimitedRange:
803 stream_out_rgb_lim_range = true;
804 break;
805 case OptStreamOutHorSpeed:
806 case OptStreamOutVertSpeed:
807 speed = strtol(optarg, nullptr, 0);
808 if (speed < -3)
809 speed = -3;
810 if (speed > 3)
811 speed = 3;
812 if (ch == OptStreamOutHorSpeed)
813 stream_out_hor_mode = static_cast<tpg_move_mode>(speed + 3);
814 else
815 stream_out_vert_mode = static_cast<tpg_move_mode>(speed + 3);
816 break;
817 case OptStreamOutPercFill:
818 stream_out_perc_fill = strtoul(optarg, nullptr, 0);
819 if (stream_out_perc_fill > 100)
820 stream_out_perc_fill = 100;
821 if (stream_out_perc_fill < 1)
822 stream_out_perc_fill = 1;
823 break;
824 case OptStreamTo:
825 file_to = optarg;
826 to_with_hdr = false;
827 if (!strcmp(file_to, "-"))
828 options[OptSilent] = true;
829 break;
830 case OptStreamToHdr:
831 file_to = optarg;
832 to_with_hdr = true;
833 if (!strcmp(file_to, "-"))
834 options[OptSilent] = true;
835 break;
836 case OptStreamToHost:
837 host_to = optarg;
838 break;
839 case OptStreamLossless:
840 host_lossless = true;
841 break;
842 case OptStreamFrom:
843 file_from = optarg;
844 from_with_hdr = false;
845 break;
846 case OptStreamFromHdr:
847 file_from = optarg;
848 from_with_hdr = true;
849 break;
850 case OptStreamFromHost:
851 host_from = optarg;
852 break;
853 case OptStreamUser:
854 memory = V4L2_MEMORY_USERPTR;
855 fallthrough;
856 case OptStreamMmap:
857 if (optarg)
858 reqbufs_count_cap = strtoul(optarg, nullptr, 0);
859 break;
860 case OptStreamDmaBuf:
861 memory = V4L2_MEMORY_DMABUF;
862 break;
863 case OptStreamOutUser:
864 out_memory = V4L2_MEMORY_USERPTR;
865 fallthrough;
866 case OptStreamOutMmap:
867 if (optarg)
868 reqbufs_count_out = strtoul(optarg, nullptr, 0);
869 break;
870 case OptStreamOutDmaBuf:
871 out_memory = V4L2_MEMORY_DMABUF;
872 break;
873 }
874 }
875
876 /*
877 * Assume that the fwht stream is valid and that each
878 * frame starts right after the previous one.
879 */
880 static bool read_fwht_frame(cv4l_fmt &fmt, unsigned char *buf,
881 FILE *fpointer, unsigned &sz,
882 unsigned &expected_len, unsigned buf_len)
883 {
884 expected_len = sizeof(struct fwht_cframe_hdr);
885 if (expected_len > buf_len)
886 return false;
887 sz = fread(&last_fwht_hdr, 1, sizeof(struct fwht_cframe_hdr), fpointer);
888 if (sz < sizeof(struct fwht_cframe_hdr))
889 return true;
890
891 expected_len = ntohl(last_fwht_hdr.size);
892 if (expected_len > buf_len)
893 return false;
894 sz = fread(buf, 1, ntohl(last_fwht_hdr.size), fpointer);
895 return true;
896 }
897
898 static void set_fwht_stateless_params(struct v4l2_ctrl_fwht_params &fwht_params,
899 const struct fwht_cframe_hdr *hdr,
900 __u64 last_bf_ts)
901 {
902 fwht_params.backward_ref_ts = last_bf_ts;
903 fwht_params.version = ntohl(hdr->version);
904 fwht_params.width = ntohl(hdr->width);
905 fwht_params.height = ntohl(hdr->height);
906 fwht_params.flags = ntohl(hdr->flags);
907 fwht_params.colorspace = ntohl(hdr->colorspace);
908 fwht_params.xfer_func = ntohl(hdr->xfer_func);
909 fwht_params.ycbcr_enc = ntohl(hdr->ycbcr_enc);
910 fwht_params.quantization = ntohl(hdr->quantization);
911
912 /*
913 * if last_bf_ts is 0 it indicates that either this is the
914 * first frame, or that last frame returned with an error so
915 * it is better not to reference it so the error won't propagate
916 */
917 if (!last_bf_ts)
918 fwht_params.flags |= V4L2_FWHT_FL_I_FRAME;
919 }
920
921 static int alloc_fwht_req(int media_fd, unsigned index)
922 {
923 int rc = 0;
924
925 rc = ioctl(media_fd, MEDIA_IOC_REQUEST_ALLOC, &fwht_reqs[index]);
926 if (rc < 0) {
927 fprintf(stderr, "Unable to allocate media request: %s\n",
928 strerror(errno));
929 return rc;
930 }
931
932 return 0;
933 }
934
935 static void set_fwht_req_by_idx(unsigned idx, const struct fwht_cframe_hdr *hdr,
936 __u64 last_bf_ts, __u64 ts)
937 {
938 struct v4l2_ctrl_fwht_params fwht_params;
939
940 set_fwht_stateless_params(fwht_params, hdr, last_bf_ts);
941
942 fwht_reqs[idx].ts = ts;
943 fwht_reqs[idx].params = fwht_params;
944 }
945
946 static int get_fwht_req_by_ts(__u64 ts)
947 {
948 for (int idx = 0; idx < VIDEO_MAX_FRAME; idx++) {
949 if (fwht_reqs[idx].ts == ts)
950 return idx;
951 }
952 return -1;
953 }
954
955 static bool set_fwht_req_by_fd(const struct fwht_cframe_hdr *hdr,
956 int req_fd, __u64 last_bf_ts, __u64 ts)
957 {
958 struct v4l2_ctrl_fwht_params fwht_params;
959
960 set_fwht_stateless_params(fwht_params, hdr, last_bf_ts);
961
962 for (auto &fwht_req : fwht_reqs) {
963 if (fwht_req.fd == req_fd) {
964 fwht_req.ts = ts;
965 fwht_req.params = fwht_params;
966 return true;
967 }
968 }
969 return false;
970 }
971
972 static int set_fwht_ext_ctrl(cv4l_fd &fd, const struct fwht_cframe_hdr *hdr,
973 __u64 last_bf_ts, int req_fd)
974 {
975 v4l2_ext_controls controls;
976 struct v4l2_ext_control control;
977 struct v4l2_ctrl_fwht_params fwht_params;
978
979 memset(&control, 0, sizeof(control));
980 memset(&controls, 0, sizeof(controls));
981
982 set_fwht_stateless_params(fwht_params, hdr, last_bf_ts);
983
984 control.id = V4L2_CID_STATELESS_FWHT_PARAMS;
985 control.ptr = &fwht_params;
986 control.size = sizeof(fwht_params);
987 controls.which = V4L2_CTRL_WHICH_REQUEST_VAL;
988 controls.request_fd = req_fd;
989 controls.controls = &control;
990 controls.count = 1;
991 return fd.s_ext_ctrls(controls);
992 }
993
994 static bool read_write_padded_frame(cv4l_fmt &fmt, unsigned char *buf,
995 FILE *fpointer, unsigned &sz,
996 unsigned &expected_len, unsigned buf_len,
997 bool is_read)
998 {
999 const struct v4l2_fwht_pixfmt_info *info =
1000 v4l2_fwht_find_pixfmt(fmt.g_pixelformat());
1001 unsigned coded_height = fmt.g_height();
1002 unsigned real_width;
1003 unsigned real_height;
1004 unsigned char *plane_p = buf;
1005 unsigned char *row_p;
1006 unsigned stride = fmt.g_bytesperline();
1007
1008 if (is_read) {
1009 real_width = cropped_width;
1010 real_height = cropped_height;
1011 } else {
1012 real_width = composed_width;
1013 real_height = composed_height;
1014 }
1015
1016 sz = 0;
1017 expected_len = real_width * real_height * info->sizeimage_mult / info->sizeimage_div;
1018 if (expected_len > buf_len)
1019 return false;
1020 for (unsigned plane_idx = 0; plane_idx < info->planes_num; plane_idx++) {
1021 bool is_chroma_plane = plane_idx == 1 || plane_idx == 2;
1022 unsigned h_div = is_chroma_plane ? info->height_div : 1;
1023 unsigned w_div = is_chroma_plane ? info->width_div : 1;
1024 unsigned step = is_chroma_plane ? info->chroma_step :
1025 info->luma_alpha_step;
1026 unsigned int consume_sz = step * real_width / w_div;
1027
1028 if (info->planes_num == 3 && plane_idx == 1)
1029 stride /= 2;
1030
1031 if (plane_idx == 1 &&
1032 (info->id == V4L2_PIX_FMT_NV24 || info->id == V4L2_PIX_FMT_NV42))
1033 stride *= 2;
1034
1035 row_p = plane_p;
1036 for (unsigned i = 0; i < real_height / h_div; i++) {
1037 unsigned int wsz = 0;
1038
1039 if (is_read)
1040 wsz = fread(row_p, 1, consume_sz, fpointer);
1041 else
1042 wsz = fwrite(row_p, 1, consume_sz, fpointer);
1043 if (wsz == 0 && i == 0 && plane_idx == 0)
1044 break;
1045 if (wsz != consume_sz) {
1046 fprintf(stderr, "padding: needed %u bytes, got %u\n", consume_sz, wsz);
1047 return true;
1048 }
1049 sz += wsz;
1050 row_p += stride;
1051 }
1052 plane_p += stride * (coded_height / h_div);
1053 if (sz == 0)
1054 break;
1055 }
1056 return true;
1057 }
1058
1059 static bool fill_buffer_from_file(cv4l_fd &fd, cv4l_queue &q, cv4l_buffer &b,
1060 cv4l_fmt &fmt, FILE *fin)
1061 {
1062 static bool first = true;
1063 static bool is_fwht = false;
1064
1065 if (host_fd_from >= 0) {
1066 for (;;) {
1067 unsigned packet = read_u32(fin);
1068
1069 if (packet == V4L_STREAM_PACKET_END) {
1070 fprintf(stderr, "END packet read\n");
1071 return false;
1072 }
1073
1074 char buf[1024];
1075 unsigned sz = read_u32(fin);
1076
1077 if (packet == V4L_STREAM_PACKET_FRAME_VIDEO_RLE ||
1078 packet == V4L_STREAM_PACKET_FRAME_VIDEO_FWHT) {
1079 is_fwht = packet == V4L_STREAM_PACKET_FRAME_VIDEO_FWHT;
1080 if (is_fwht && !ctx) {
1081 fprintf(stderr, "cannot support FWHT encoding\n");
1082 return false;
1083 }
1084 break;
1085 }
1086
1087 fprintf(stderr, "expected FRAME_VIDEO, got 0x%08x\n", packet);
1088 while (sz) {
1089 unsigned rdsize = sz > sizeof(buf) ? sizeof(buf) : sz;
1090
1091 int n = fread(buf, 1, rdsize, fin);
1092 if (n < 0) {
1093 fprintf(stderr, "error reading %d bytes\n", sz);
1094 return false;
1095 }
1096 sz -= n;
1097 }
1098 }
1099
1100 unsigned sz = read_u32(fin);
1101
1102 if (sz != V4L_STREAM_PACKET_FRAME_VIDEO_SIZE_HDR) {
1103 fprintf(stderr, "unsupported FRAME_VIDEO size\n");
1104 return false;
1105 }
1106 read_u32(fin); // ignore field
1107 read_u32(fin); // ignore flags
1108 for (unsigned j = 0; j < q.g_num_planes(); j++) {
1109 __u8 *buf = static_cast<__u8 *>(q.g_dataptr(b.g_index(), j));
1110
1111 sz = read_u32(fin);
1112 if (sz != V4L_STREAM_PACKET_FRAME_VIDEO_SIZE_PLANE_HDR) {
1113 fprintf(stderr, "unsupported FRAME_VIDEO plane size\n");
1114 return false;
1115 }
1116 __u32 size = read_u32(fin);
1117 __u32 comp_size = read_u32(fin);
1118 __u32 offset = size - comp_size;
1119 unsigned sz = comp_size;
1120 __u8 *read_buf = buf;
1121
1122 if (is_fwht) {
1123 read_buf = new __u8[comp_size];
1124 offset = 0;
1125 }
1126
1127 if (size > q.g_length(j)) {
1128 fprintf(stderr, "plane size is too large (%u > %u)\n",
1129 size, q.g_length(j));
1130 return false;
1131 }
1132 while (sz) {
1133 int n = fread(read_buf + offset, 1, sz, fin);
1134 if (n < 0) {
1135 fprintf(stderr, "error reading %d bytes\n", sz);
1136 return false;
1137 }
1138 if (static_cast<__u32>(n) == sz)
1139 break;
1140 offset += n;
1141 sz -= n;
1142 }
1143 if (is_fwht) {
1144 fwht_decompress(ctx, read_buf, comp_size, buf, size);
1145 delete [] read_buf;
1146 } else {
1147 rle_decompress(buf, size, comp_size, bpl_out[j]);
1148 }
1149 }
1150 return true;
1151 }
1152
1153 restart:
1154 if (from_with_hdr) {
1155 __u32 v;
1156
1157 if (!fread(&v, sizeof(v), 1, fin)) {
1158 if (first) {
1159 fprintf(stderr, "Insufficient data\n");
1160 return false;
1161 }
1162 if (stream_loop) {
1163 fseek(fin, 0, SEEK_SET);
1164 first = true;
1165 goto restart;
1166 }
1167 return false;
1168 }
1169 if (ntohl(v) != FILE_HDR_ID) {
1170 fprintf(stderr, "Unknown header ID\n");
1171 return false;
1172 }
1173 }
1174
1175 for (unsigned j = 0; j < q.g_num_planes(); j++) {
1176 void *buf = q.g_dataptr(b.g_index(), j);
1177 unsigned buf_len = q.g_length(j);
1178 unsigned expected_len = q.g_length(j);
1179 unsigned sz;
1180 cv4l_fmt fmt;
1181 bool res = true;
1182
1183 fd.g_fmt(fmt, q.g_type());
1184 if (from_with_hdr) {
1185 expected_len = read_u32(fin);
1186 if (expected_len > q.g_length(j)) {
1187 fprintf(stderr, "plane size is too large (%u > %u)\n",
1188 expected_len, q.g_length(j));
1189 return false;
1190 }
1191 }
1192
1193 if (fmt.g_pixelformat() == V4L2_PIX_FMT_FWHT_STATELESS)
1194 res = read_fwht_frame(fmt, static_cast<unsigned char *>(buf), fin,
1195 sz, expected_len, buf_len);
1196 else if (codec_type != NOT_CODEC && support_out_crop &&
1197 v4l2_fwht_find_pixfmt(fmt.g_pixelformat()))
1198 res = read_write_padded_frame(fmt, static_cast<unsigned char *>(buf),
1199 fin, sz, expected_len, buf_len, true);
1200 else
1201 sz = fread(buf, 1, expected_len, fin);
1202
1203 if (!res) {
1204 fprintf(stderr, "amount intended to be read/written is larger than the buffer size\n");
1205 return false;
1206 }
1207 if (first && sz != expected_len && fmt.g_bytesperline(j)) {
1208 fprintf(stderr, "%s: size read (%u) is different than needed (%u) in the first frame\n",
1209 __func__, sz, expected_len);
1210 return false;
1211 }
1212 if (j == 0 && sz == 0 && stream_loop) {
1213 fseek(fin, 0, SEEK_SET);
1214 first = true;
1215 goto restart;
1216 }
1217 b.s_bytesused(sz, j);
1218 if (sz == expected_len)
1219 continue;
1220 if (sz == 0)
1221 return false;
1222 if (sz && fmt.g_bytesperline(j))
1223 fprintf(stderr, "%u != %u\n", sz, expected_len);
1224 }
1225 first = false;
1226 return true;
1227 }
1228
1229 static int do_setup_out_buffers(cv4l_fd &fd, cv4l_queue &q, FILE *fin, bool qbuf,
1230 bool ignore_count_skip)
1231 {
1232 tpg_pixel_aspect aspect = TPG_PIXEL_ASPECT_SQUARE;
1233 cv4l_fmt fmt(q.g_type());
1234 u32 field;
1235 unsigned p;
1236 bool can_fill = false;
1237 bool is_video = q.g_type() == V4L2_BUF_TYPE_VIDEO_OUTPUT ||
1238 q.g_type() == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
1239 bool is_meta = q.g_type() == V4L2_BUF_TYPE_META_OUTPUT;
1240
1241 if (q.obtain_bufs(&fd)) {
1242 fprintf(stderr, "%s q.obtain_bufs failed\n", __func__);
1243 return QUEUE_ERROR;
1244 }
1245
1246 fd.g_fmt(fmt, q.g_type());
1247 {
1248 cv4l_disable_trace dt(fd);
1249 if (fd.g_std(stream_out_std)) {
1250 struct v4l2_dv_timings timings;
1251
1252 stream_out_std = 0;
1253 if (fd.g_dv_timings(timings))
1254 memset(&timings, 0, sizeof(timings));
1255 else if (timings.bt.width == 720 && timings.bt.height == 480)
1256 aspect = TPG_PIXEL_ASPECT_NTSC;
1257 else if (timings.bt.width == 720 && timings.bt.height == 576)
1258 aspect = TPG_PIXEL_ASPECT_PAL;
1259 } else if (stream_out_std & V4L2_STD_525_60) {
1260 aspect = TPG_PIXEL_ASPECT_NTSC;
1261 } else if (stream_out_std & V4L2_STD_625_50) {
1262 aspect = TPG_PIXEL_ASPECT_PAL;
1263 }
1264 }
1265
1266 field = fmt.g_field();
1267
1268 output_field = field;
1269 output_field_alt = field == V4L2_FIELD_ALTERNATE;
1270 if (V4L2_FIELD_HAS_T_OR_B(field))
1271 output_field = (stream_out_std & V4L2_STD_525_60) ?
1272 V4L2_FIELD_BOTTOM : V4L2_FIELD_TOP;
1273
1274 if (is_video) {
1275 tpg_init(&tpg, 640, 360);
1276 tpg_alloc(&tpg, fmt.g_width());
1277 can_fill = tpg_s_fourcc(&tpg, fmt.g_pixelformat());
1278 tpg_reset_source(&tpg, fmt.g_width(), fmt.g_frame_height(), field);
1279 tpg_s_colorspace(&tpg, fmt.g_colorspace());
1280 tpg_s_xfer_func(&tpg, fmt.g_xfer_func());
1281 tpg_s_ycbcr_enc(&tpg, fmt.g_ycbcr_enc());
1282 tpg_s_quantization(&tpg, fmt.g_quantization());
1283 for (p = 0; p < fmt.g_num_planes(); p++)
1284 tpg_s_bytesperline(&tpg, p,
1285 fmt.g_bytesperline(p));
1286 tpg_s_pattern(&tpg, static_cast<tpg_pattern>(stream_pat));
1287 tpg_s_mv_hor_mode(&tpg, stream_out_hor_mode);
1288 tpg_s_mv_vert_mode(&tpg, stream_out_vert_mode);
1289 tpg_s_show_square(&tpg, stream_out_square);
1290 tpg_s_show_border(&tpg, stream_out_border);
1291 tpg_s_insert_sav(&tpg, stream_out_sav);
1292 tpg_s_insert_eav(&tpg, stream_out_eav);
1293 tpg_s_perc_fill(&tpg, stream_out_perc_fill);
1294 if (stream_out_rgb_lim_range)
1295 tpg_s_real_rgb_range(&tpg, V4L2_DV_RGB_RANGE_LIMITED);
1296 tpg_s_alpha_component(&tpg, stream_out_alpha);
1297 tpg_s_alpha_mode(&tpg, stream_out_alpha_red_only);
1298 tpg_s_video_aspect(&tpg, stream_out_video_aspect);
1299 switch (stream_out_pixel_aspect) {
1300 case -1:
1301 tpg_s_pixel_aspect(&tpg, aspect);
1302 break;
1303 default:
1304 tpg_s_pixel_aspect(&tpg, static_cast<tpg_pixel_aspect>(stream_out_pixel_aspect));
1305 break;
1306 }
1307 field = output_field;
1308 if (can_fill && ((V4L2_FIELD_HAS_T_OR_B(field) && (stream_count & 1)) ||
1309 !tpg_pattern_is_static(&tpg)))
1310 stream_out_refresh = true;
1311 }
1312
1313 for (unsigned i = 0; i < q.g_buffers(); i++) {
1314 cv4l_buffer buf(q);
1315
1316 if (fd.querybuf(buf, i)) {
1317 fprintf(stderr, "%s fd.querybuf failed\n", __func__);
1318 return QUEUE_ERROR;
1319 }
1320
1321 buf.update(q, i);
1322 for (unsigned j = 0; j < q.g_num_planes(); j++)
1323 buf.s_bytesused(buf.g_length(j), j);
1324 if (is_video) {
1325 buf.s_field(field);
1326 tpg_s_field(&tpg, field, output_field_alt);
1327 if (output_field_alt) {
1328 if (field == V4L2_FIELD_TOP)
1329 field = V4L2_FIELD_BOTTOM;
1330 else if (field == V4L2_FIELD_BOTTOM)
1331 field = V4L2_FIELD_TOP;
1332 }
1333
1334 if (can_fill) {
1335 for (unsigned j = 0; j < q.g_num_planes(); j++)
1336 tpg_fillbuffer(&tpg, stream_out_std, j, static_cast<u8 *>(q.g_dataptr(i, j)));
1337 }
1338 }
1339 if (is_meta)
1340 meta_fillbuffer(buf, fmt, q);
1341
1342 if (fin && !fill_buffer_from_file(fd, q, buf, fmt, fin))
1343 return QUEUE_STOPPED;
1344
1345 if (fmt.g_pixelformat() == V4L2_PIX_FMT_FWHT_STATELESS) {
1346 struct v4l2_capability vcap = {};
1347 fd.querycap(vcap);
1348 int media_fd = mi_get_media_fd(fd.g_fd(), (const char *)vcap.bus_info);
1349
1350 if (media_fd < 0) {
1351 fprintf(stderr, "%s: mi_get_media_fd failed\n", __func__);
1352 return media_fd;
1353 }
1354
1355 if (alloc_fwht_req(media_fd, i))
1356 return QUEUE_ERROR;
1357 buf.s_request_fd(fwht_reqs[i].fd);
1358 buf.or_flags(V4L2_BUF_FLAG_REQUEST_FD);
1359
1360 if (set_fwht_ext_ctrl(fd, &last_fwht_hdr, last_fwht_bf_ts,
1361 buf.g_request_fd())) {
1362 fprintf(stderr, "%s: set_fwht_ext_ctrl failed on %dth buf: %s\n",
1363 __func__, i, strerror(errno));
1364 return QUEUE_ERROR;
1365 }
1366 }
1367 if (qbuf) {
1368 fps_timestamps fps_ts;
1369
1370 set_time_stamp(buf);
1371 if (fd.qbuf(buf))
1372 return QUEUE_ERROR;
1373 tpg_update_mv_count(&tpg, V4L2_FIELD_HAS_T_OR_B(field));
1374 if (!verbose)
1375 stderr_info(">");
1376 fflush(stderr);
1377 if (!ignore_count_skip && stream_count)
1378 if (!--stream_count)
1379 return QUEUE_STOPPED;
1380 }
1381 if (fmt.g_pixelformat() == V4L2_PIX_FMT_FWHT_STATELESS) {
1382 set_fwht_req_by_idx(i, &last_fwht_hdr,
1383 last_fwht_bf_ts, buf.g_timestamp_ns());
1384 last_fwht_bf_ts = buf.g_timestamp_ns();
1385 if (ioctl(buf.g_request_fd(), MEDIA_REQUEST_IOC_QUEUE) < 0) {
1386 fprintf(stderr, "Unable to queue media request: %s\n",
1387 strerror(errno));
1388 return QUEUE_ERROR;
1389 }
1390 }
1391 }
1392 if (qbuf)
1393 output_field = field;
1394 return 0;
1395 }
1396
1397 static void write_buffer_to_file(cv4l_fd &fd, cv4l_queue &q, cv4l_buffer &buf,
1398 cv4l_fmt &fmt, FILE *fout)
1399 {
1400 #ifndef NO_STREAM_TO
1401 unsigned comp_size[VIDEO_MAX_PLANES];
1402 __u8 *comp_ptr[VIDEO_MAX_PLANES];
1403
1404 if (host_fd_to >= 0) {
1405 unsigned tot_comp_size = 0;
1406 unsigned tot_used = 0;
1407
1408 for (unsigned j = 0; j < buf.g_num_planes(); j++) {
1409 __u32 used = buf.g_bytesused(j);
1410 unsigned offset = buf.g_data_offset(j);
1411 u8 *p = static_cast<u8 *>(q.g_dataptr(buf.g_index(), j)) + offset;
1412
1413 if (ctx) {
1414 comp_ptr[j] = fwht_compress(ctx, p,
1415 used - offset, &comp_size[j]);
1416 } else {
1417 comp_ptr[j] = p;
1418 comp_size[j] = rle_compress(p, used - offset,
1419 bpl_cap[j]);
1420 }
1421 tot_comp_size += comp_size[j];
1422 tot_used += used - offset;
1423 }
1424 write_u32(fout, ctx ? V4L_STREAM_PACKET_FRAME_VIDEO_FWHT :
1425 V4L_STREAM_PACKET_FRAME_VIDEO_RLE);
1426 write_u32(fout, V4L_STREAM_PACKET_FRAME_VIDEO_SIZE(buf.g_num_planes()) + tot_comp_size);
1427 write_u32(fout, V4L_STREAM_PACKET_FRAME_VIDEO_SIZE_HDR);
1428 write_u32(fout, buf.g_field());
1429 write_u32(fout, buf.g_flags());
1430 comp_perc += (tot_comp_size * 100 / tot_used);
1431 comp_perc_count++;
1432 }
1433 if (to_with_hdr)
1434 write_u32(fout, FILE_HDR_ID);
1435 for (unsigned j = 0; j < buf.g_num_planes(); j++) {
1436 __u32 used = buf.g_bytesused(j);
1437 unsigned offset = buf.g_data_offset(j);
1438 unsigned sz;
1439
1440 if (offset > used) {
1441 // Should never happen
1442 fprintf(stderr, "offset %d > used %d!\n",
1443 offset, used);
1444 offset = 0;
1445 }
1446 used -= offset;
1447 if (host_fd_to >= 0) {
1448 write_u32(fout, V4L_STREAM_PACKET_FRAME_VIDEO_SIZE_PLANE_HDR);
1449 write_u32(fout, used);
1450 write_u32(fout, comp_size[j]);
1451 used = comp_size[j];
1452 } else if (to_with_hdr) {
1453 write_u32(fout, used);
1454 }
1455 if (host_fd_to >= 0)
1456 sz = fwrite(comp_ptr[j] + offset, 1, used, fout);
1457 else if (codec_type != NOT_CODEC && support_cap_compose &&
1458 v4l2_fwht_find_pixfmt(fmt.g_pixelformat()))
1459 read_write_padded_frame(fmt, static_cast<u8 *>(q.g_dataptr(buf.g_index(), j)) + offset,
1460 fout, sz, used, used, false);
1461 else
1462 sz = fwrite(static_cast<u8 *>(q.g_dataptr(buf.g_index(), j)) + offset, 1, used, fout);
1463
1464 if (sz != used)
1465 fprintf(stderr, "%u != %u\n", sz, used);
1466 }
1467 if (host_fd_to >= 0)
1468 fflush(fout);
1469 #endif
1470 }
1471
1472 static int do_handle_cap(cv4l_fd &fd, cv4l_queue &q, FILE *fout, int *index,
1473 unsigned &count, fps_timestamps &fps_ts, cv4l_fmt &fmt,
1474 bool ignore_count_skip)
1475 {
1476 char ch = '<';
1477 int ret;
1478 cv4l_buffer buf(q);
1479
1480 for (;;) {
1481 ret = fd.dqbuf(buf);
1482 if (ret == EAGAIN)
1483 return 0;
1484 if (ret == EPIPE)
1485 return QUEUE_STOPPED;
1486 if (ret) {
1487 fprintf(stderr, "%s: failed: %s\n", "VIDIOC_DQBUF", strerror(errno));
1488 return QUEUE_ERROR;
1489 }
1490 if (buf.g_flags() & V4L2_BUF_FLAG_LAST) {
1491 last_buffer = true;
1492 break;
1493 }
1494 if (!(buf.g_flags() & V4L2_BUF_FLAG_ERROR))
1495 break;
1496 if (verbose)
1497 print_concise_buffer(stderr, buf, fmt, q, fps_ts, -1);
1498 if (fd.qbuf(buf))
1499 return QUEUE_ERROR;
1500 }
1501
1502 bool is_empty_frame = !buf.g_bytesused(0);
1503 bool is_error_frame = buf.g_flags() & V4L2_BUF_FLAG_ERROR;
1504
1505 double ts_secs = buf.g_timestamp().tv_sec + buf.g_timestamp().tv_usec / 1000000.0;
1506 fps_ts.add_ts(ts_secs, buf.g_sequence(), buf.g_field());
1507
1508 if (fout && (!stream_skip || ignore_count_skip) &&
1509 !is_empty_frame && !is_error_frame)
1510 write_buffer_to_file(fd, q, buf, fmt, fout);
1511
1512 if (buf.g_flags() & V4L2_BUF_FLAG_KEYFRAME)
1513 ch = 'K';
1514 else if (buf.g_flags() & V4L2_BUF_FLAG_PFRAME)
1515 ch = 'P';
1516 else if (buf.g_flags() & V4L2_BUF_FLAG_BFRAME)
1517 ch = 'B';
1518 if (verbose) {
1519 print_concise_buffer(stderr, buf, fmt, q, fps_ts,
1520 host_fd_to >= 0 ? 100 - comp_perc / comp_perc_count : -1);
1521 comp_perc_count = comp_perc = 0;
1522 }
1523 if (!last_buffer && index == nullptr) {
1524 /*
1525 * EINVAL in qbuf can happen if this is the last buffer before
1526 * a dynamic resolution change sequence. In this case the buffer
1527 * has the size that fits the old resolution and might not
1528 * fit to the new one.
1529 */
1530 if (fd.qbuf(buf) && errno != EINVAL) {
1531 fprintf(stderr, "%s: qbuf error\n", __func__);
1532 return QUEUE_ERROR;
1533 }
1534 }
1535 if (index)
1536 *index = buf.g_index();
1537
1538 if (!verbose) {
1539 stderr_info("%c", ch);
1540 fflush(stderr);
1541
1542 if (fps_ts.has_fps()) {
1543 unsigned dropped = fps_ts.dropped();
1544
1545 stderr_info(" %.02f fps", fps_ts.fps());
1546 if (dropped)
1547 stderr_info(", dropped buffers: %u", dropped);
1548 if (host_fd_to >= 0)
1549 stderr_info(" %d%% compression", 100 - comp_perc / comp_perc_count);
1550 comp_perc_count = comp_perc = 0;
1551 stderr_info("\n");
1552 }
1553 }
1554 count++;
1555
1556 if (ignore_count_skip)
1557 return 0;
1558
1559 if (need_sleep(count)) {
1560 if (stream_sleep_mode & 2)
1561 return QUEUE_OFF_ON;
1562 do_sleep();
1563 }
1564
1565 if (is_empty_frame || is_error_frame)
1566 return 0;
1567
1568 if (stream_skip) {
1569 stream_skip--;
1570 return 0;
1571 }
1572
1573 if (stream_count == 0)
1574 return 0;
1575
1576 if (--stream_count == 0)
1577 return QUEUE_STOPPED;
1578
1579 return 0;
1580 }
1581
1582 static int do_handle_out(cv4l_fd &fd, cv4l_queue &q, FILE *fin, cv4l_buffer *cap,
1583 unsigned &count, fps_timestamps &fps_ts, cv4l_fmt fmt,
1584 bool stopped, bool ignore_count_skip)
1585 {
1586 cv4l_buffer buf(q);
1587 bool is_meta = q.g_type() == V4L2_BUF_TYPE_META_OUTPUT;
1588 int ret = 0;
1589
1590 if (cap) {
1591 buf.s_index(cap->g_index());
1592
1593 if (fd.querybuf(buf)) {
1594 fprintf(stderr, "%s fd.querybuf failed\n", __func__);
1595 return QUEUE_ERROR;
1596 }
1597
1598 for (unsigned j = 0; j < buf.g_num_planes(); j++) {
1599 unsigned data_offset = cap->g_data_offset(j);
1600
1601 if (q.g_memory() == V4L2_MEMORY_USERPTR) {
1602 buf.s_userptr(static_cast<u8 *>(cap->g_userptr(j)) + data_offset, j);
1603 buf.s_bytesused(cap->g_bytesused(j) - data_offset, j);
1604 buf.s_data_offset(0, j);
1605 } else if (q.g_memory() == V4L2_MEMORY_DMABUF) {
1606 __u32 bytesused = cap->g_bytesused(j);
1607 /*
1608 * bytesused comes from the exported cap buffer
1609 * but the length of the out buffer might be smaller
1610 * so take the smaller of the two
1611 */
1612 if (bytesused > buf.g_length(j))
1613 bytesused = buf.g_length(j);
1614 buf.s_bytesused(bytesused, j);
1615 buf.s_data_offset(data_offset, j);
1616 buf.s_fd(q.g_fd(buf.g_index(), j));
1617 }
1618 }
1619 } else {
1620 ret = fd.dqbuf(buf);
1621 if (ret == EAGAIN)
1622 return 0;
1623
1624 double ts_secs = buf.g_timestamp().tv_sec + buf.g_timestamp().tv_usec / 1000000.0;
1625 fps_ts.add_ts(ts_secs, buf.g_sequence(), buf.g_field());
1626 if (verbose)
1627 print_concise_buffer(stderr, buf, fmt, q, fps_ts, -1);
1628
1629 for (unsigned j = 0; j < buf.g_num_planes(); j++)
1630 buf.s_bytesused(buf.g_length(j), j);
1631 }
1632 if (ret) {
1633 fprintf(stderr, "%s: failed: %s\n", "VIDIOC_DQBUF", strerror(ret));
1634 return QUEUE_ERROR;
1635 }
1636 if (fps_ts.has_fps()) {
1637 unsigned dropped = fps_ts.dropped();
1638
1639 stderr_info(" %.02f fps", fps_ts.fps());
1640 if (dropped)
1641 stderr_info(", dropped buffers: %u", dropped);
1642 stderr_info("\n");
1643 }
1644 if (stopped)
1645 return 0;
1646
1647 buf.s_field(output_field);
1648 tpg_s_field(&tpg, output_field, output_field_alt);
1649 if (output_field_alt) {
1650 if (output_field == V4L2_FIELD_TOP)
1651 output_field = V4L2_FIELD_BOTTOM;
1652 else if (output_field == V4L2_FIELD_BOTTOM)
1653 output_field = V4L2_FIELD_TOP;
1654 }
1655
1656 if (fin && !fill_buffer_from_file(fd, q, buf, fmt, fin))
1657 return QUEUE_STOPPED;
1658
1659 if (!fin && stream_out_refresh) {
1660 for (unsigned j = 0; j < buf.g_num_planes(); j++)
1661 tpg_fillbuffer(&tpg, stream_out_std, j,
1662 static_cast<u8 *>(q.g_dataptr(buf.g_index(), j)));
1663 }
1664 if (is_meta)
1665 meta_fillbuffer(buf, fmt, q);
1666
1667 if (fmt.g_pixelformat() == V4L2_PIX_FMT_FWHT_STATELESS) {
1668 if (ioctl(buf.g_request_fd(), MEDIA_REQUEST_IOC_REINIT, NULL)) {
1669 fprintf(stderr, "Unable to reinit media request: %s\n",
1670 strerror(errno));
1671 return QUEUE_ERROR;
1672 }
1673
1674 if (set_fwht_ext_ctrl(fd, &last_fwht_hdr, last_fwht_bf_ts,
1675 buf.g_request_fd())) {
1676 fprintf(stderr, "%s: set_fwht_ext_ctrl failed: %s\n",
1677 __func__, strerror(errno));
1678 return QUEUE_ERROR;
1679 }
1680 }
1681
1682 set_time_stamp(buf);
1683
1684 if (fd.qbuf(buf)) {
1685 fprintf(stderr, "%s: failed: %s\n", "VIDIOC_QBUF", strerror(errno));
1686 return QUEUE_ERROR;
1687 }
1688 if (fmt.g_pixelformat() == V4L2_PIX_FMT_FWHT_STATELESS) {
1689 if (!set_fwht_req_by_fd(&last_fwht_hdr, buf.g_request_fd(), last_fwht_bf_ts,
1690 buf.g_timestamp_ns())) {
1691 fprintf(stderr, "%s: request for fd %d does not exist\n",
1692 __func__, buf.g_request_fd());
1693 return QUEUE_ERROR;
1694 }
1695
1696 last_fwht_bf_ts = buf.g_timestamp_ns();
1697 if (ioctl(buf.g_request_fd(), MEDIA_REQUEST_IOC_QUEUE) < 0) {
1698 fprintf(stderr, "Unable to queue media request: %s\n",
1699 strerror(errno));
1700 return QUEUE_ERROR;
1701 }
1702 }
1703
1704 tpg_update_mv_count(&tpg, V4L2_FIELD_HAS_T_OR_B(output_field));
1705
1706 if (!verbose)
1707 stderr_info(">");
1708 fflush(stderr);
1709
1710 count++;
1711
1712 if (ignore_count_skip)
1713 return 0;
1714
1715 if (need_sleep(count)) {
1716 if (stream_sleep_mode & 2)
1717 return QUEUE_OFF_ON;
1718 do_sleep();
1719 }
1720
1721 if (stream_skip) {
1722 stream_skip--;
1723 return 0;
1724 }
1725
1726 if (stream_count == 0)
1727 return 0;
1728 if (--stream_count == 0)
1729 return QUEUE_STOPPED;
1730
1731 return 0;
1732 }
1733
1734 static int do_handle_out_to_in(cv4l_fd &out_fd, cv4l_fd &fd, cv4l_queue &out, cv4l_queue &in)
1735 {
1736 cv4l_buffer buf(out);
1737 int ret;
1738
1739 do {
1740 ret = out_fd.dqbuf(buf);
1741 } while (ret == EAGAIN);
1742 if (ret) {
1743 fprintf(stderr, "%s: failed: %s\n", "VIDIOC_DQBUF", strerror(errno));
1744 return QUEUE_ERROR;
1745 }
1746 buf.init(in, buf.g_index());
1747 ret = fd.querybuf(buf);
1748 if (ret == 0)
1749 ret = fd.qbuf(buf);
1750 if (ret) {
1751 fprintf(stderr, "%s: failed: %s\n", "VIDIOC_QBUF", strerror(errno));
1752 return QUEUE_ERROR;
1753 }
1754 return 0;
1755 }
1756
1757 static FILE *open_output_file(cv4l_fd &fd)
1758 {
1759 FILE *fout = nullptr;
1760
1761 #ifndef NO_STREAM_TO
1762 if (file_to) {
1763 if (!strcmp(file_to, "-"))
1764 return stdout;
1765 fout = fopen(file_to, "w+");
1766 if (!fout)
1767 fprintf(stderr, "could not open %s for writing\n", file_to);
1768 return fout;
1769 }
1770 if (!host_to)
1771 return nullptr;
1772
1773 char *p = std::strchr(host_to, ':');
1774 struct sockaddr_in serv_addr;
1775 struct hostent *server;
1776 struct v4l2_fract aspect;
1777 unsigned width, height;
1778 cv4l_fmt cfmt;
1779
1780 fd.g_fmt(cfmt);
1781
1782 aspect = fd.g_pixel_aspect(width, height);
1783 if (p) {
1784 host_port_to = strtoul(p + 1, nullptr, 0);
1785 *p = '\0';
1786 }
1787 host_fd_to = socket(AF_INET, SOCK_STREAM, 0);
1788 if (host_fd_to < 0) {
1789 fprintf(stderr, "cannot open socket");
1790 std::exit(EXIT_SUCCESS);
1791 }
1792 server = gethostbyname(host_to);
1793 if (server == nullptr) {
1794 fprintf(stderr, "no such host %s\n", host_to);
1795 std::exit(EXIT_SUCCESS);
1796 }
1797 memset(reinterpret_cast<char *>(&serv_addr), 0, sizeof(serv_addr));
1798 serv_addr.sin_family = AF_INET;
1799 memcpy(reinterpret_cast<char *>(&serv_addr.sin_addr.s_addr),
1800 server->h_addr,
1801 server->h_length);
1802 serv_addr.sin_port = htons(host_port_to);
1803 if (connect(host_fd_to, reinterpret_cast<struct sockaddr *>(&serv_addr), sizeof(serv_addr)) < 0) {
1804 fprintf(stderr, "could not connect\n");
1805 std::exit(EXIT_SUCCESS);
1806 }
1807 fout = fdopen(host_fd_to, "a");
1808 write_u32(fout, V4L_STREAM_ID);
1809 write_u32(fout, V4L_STREAM_VERSION);
1810 write_u32(fout, V4L_STREAM_PACKET_FMT_VIDEO);
1811 write_u32(fout, V4L_STREAM_PACKET_FMT_VIDEO_SIZE(cfmt.g_num_planes()));
1812 write_u32(fout, V4L_STREAM_PACKET_FMT_VIDEO_SIZE_FMT);
1813 write_u32(fout, cfmt.g_num_planes());
1814 write_u32(fout, cfmt.g_pixelformat());
1815 write_u32(fout, cfmt.g_width());
1816 write_u32(fout, cfmt.g_height());
1817 write_u32(fout, cfmt.g_field());
1818 write_u32(fout, cfmt.g_colorspace());
1819 write_u32(fout, cfmt.g_ycbcr_enc());
1820 write_u32(fout, cfmt.g_quantization());
1821 write_u32(fout, cfmt.g_xfer_func());
1822 write_u32(fout, cfmt.g_flags());
1823 write_u32(fout, aspect.numerator);
1824 write_u32(fout, aspect.denominator);
1825 for (unsigned i = 0; i < cfmt.g_num_planes(); i++) {
1826 write_u32(fout, V4L_STREAM_PACKET_FMT_VIDEO_SIZE_FMT_PLANE);
1827 write_u32(fout, cfmt.g_sizeimage(i));
1828 write_u32(fout, cfmt.g_bytesperline(i));
1829 bpl_cap[i] = rle_calc_bpl(cfmt.g_bytesperline(i), cfmt.g_pixelformat());
1830 }
1831 if (!host_lossless) {
1832 unsigned visible_width = support_cap_compose ? composed_width : cfmt.g_width();
1833 unsigned visible_height = support_cap_compose ? composed_height : cfmt.g_height();
1834
1835 ctx = fwht_alloc(cfmt.g_pixelformat(), visible_width, visible_height,
1836 cfmt.g_width(), cfmt.g_height(),
1837 cfmt.g_field(), cfmt.g_colorspace(), cfmt.g_xfer_func(),
1838 cfmt.g_ycbcr_enc(), cfmt.g_quantization());
1839 }
1840 fflush(fout);
1841 #endif
1842 return fout;
1843 }
1844
1845 static void streaming_set_cap(cv4l_fd &fd, cv4l_fd &exp_fd)
1846 {
1847 int fd_flags = fcntl(fd.g_fd(), F_GETFL);
1848 cv4l_queue q(fd.g_type(), memory);
1849 cv4l_queue exp_q(exp_fd.g_type(), V4L2_MEMORY_MMAP);
1850 fps_timestamps fps_ts;
1851 bool use_poll = options[OptStreamPoll];
1852 unsigned count;
1853 bool eos;
1854 bool source_change;
1855 FILE *fout = nullptr;
1856 cv4l_fmt fmt;
1857
1858 if (!(capabilities & (V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_VIDEO_CAPTURE_MPLANE |
1859 V4L2_CAP_VBI_CAPTURE | V4L2_CAP_SLICED_VBI_CAPTURE |
1860 V4L2_CAP_META_CAPTURE | V4L2_CAP_SDR_CAPTURE |
1861 V4L2_CAP_VIDEO_M2M | V4L2_CAP_VIDEO_M2M_MPLANE))) {
1862 fprintf(stderr, "unsupported stream type\n");
1863 return;
1864 }
1865 if (options[OptStreamDmaBuf] && exp_fd.g_fd() < 0) {
1866 fprintf(stderr, "--stream-dmabuf can only work in combination with --export-device\n");
1867 return;
1868 }
1869 switch (q.g_type()) {
1870 case V4L2_BUF_TYPE_VIDEO_CAPTURE:
1871 case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:
1872 break;
1873 default:
1874 if (host_to) {
1875 fprintf(stderr, "--stream-to-host is not supported for non-video streams\n");
1876 return;
1877 }
1878 break;
1879 }
1880
1881 subscribe_event(fd, V4L2_EVENT_EOS);
1882 if (use_poll)
1883 subscribe_event(fd, V4L2_EVENT_SOURCE_CHANGE);
1884
1885 recover:
1886 eos = false;
1887 source_change = false;
1888 count = 0;
1889
1890 if (!stream_no_query) {
1891 cv4l_disable_trace dt(fd);
1892 struct v4l2_dv_timings new_dv_timings = {};
1893 v4l2_std_id new_std;
1894 struct v4l2_input in = { };
1895
1896 if (!fd.g_input(in.index) && !fd.enum_input(in, true, in.index)) {
1897 if (in.capabilities & V4L2_IN_CAP_DV_TIMINGS) {
1898 while (fd.query_dv_timings(new_dv_timings))
1899 sleep(1);
1900 fd.s_dv_timings(new_dv_timings);
1901 stderr_info("New timings found\n");
1902 } else if (in.capabilities & V4L2_IN_CAP_STD) {
1903 if (!fd.query_std(new_std))
1904 fd.s_std(new_std);
1905 }
1906 }
1907 }
1908
1909 fout = open_output_file(fd);
1910
1911 if (q.reqbufs(&fd, reqbufs_count_cap)) {
1912 if (q.g_type() != V4L2_BUF_TYPE_VBI_CAPTURE ||
1913 !fd.has_raw_vbi_cap() || !fd.has_sliced_vbi_cap())
1914 goto done;
1915 fd.s_type(V4L2_BUF_TYPE_SLICED_VBI_CAPTURE);
1916 q.init(fd.g_type(), memory);
1917 if (q.reqbufs(&fd, reqbufs_count_cap))
1918 goto done;
1919 }
1920
1921 if (options[OptStreamDmaBuf]) {
1922 if (exp_q.reqbufs(&exp_fd, reqbufs_count_cap))
1923 goto done;
1924 if (q.export_bufs(&exp_fd, exp_fd.g_type()))
1925 goto done;
1926 }
1927
1928 if (q.obtain_bufs(&fd))
1929 goto done;
1930
1931 fd.g_fmt(fmt);
1932
1933 restart:
1934 if (q.queue_all(&fd))
1935 goto done;
1936
1937 fps_ts.determine_field(fd.g_fd(), q.g_type());
1938
1939 if (fd.streamon())
1940 goto done;
1941
1942 fd.s_trace(0);
1943 exp_fd.s_trace(0);
1944
1945 if (stream_sleep_count == 0)
1946 do_sleep();
1947
1948 if (use_poll)
1949 fcntl(fd.g_fd(), F_SETFL, fd_flags | O_NONBLOCK);
1950
1951 while (!eos && !source_change) {
1952 fd_set read_fds;
1953 fd_set exception_fds;
1954 struct timeval tv = { use_poll ? 2 : 0, 0 };
1955 int r;
1956
1957 FD_ZERO(&exception_fds);
1958 FD_SET(fd.g_fd(), &exception_fds);
1959 FD_ZERO(&read_fds);
1960 FD_SET(fd.g_fd(), &read_fds);
1961 r = select(fd.g_fd() + 1, use_poll ? &read_fds : nullptr, nullptr, &exception_fds, &tv);
1962
1963 if (r == -1) {
1964 if (EINTR == errno)
1965 continue;
1966 stderr_info("select error: %s\n",
1967 strerror(errno));
1968 goto done;
1969 }
1970 if (use_poll && r == 0) {
1971 stderr_info("select timeout\n");
1972 goto done;
1973 }
1974
1975 if (FD_ISSET(fd.g_fd(), &exception_fds)) {
1976 struct v4l2_event ev;
1977
1978 while (!fd.dqevent(ev)) {
1979 switch (ev.type) {
1980 case V4L2_EVENT_SOURCE_CHANGE:
1981 source_change = true;
1982 if (!verbose)
1983 stderr_info("\n");
1984 stderr_info("SOURCE CHANGE EVENT\n");
1985 break;
1986 case V4L2_EVENT_EOS:
1987 eos = true;
1988 if (!verbose)
1989 stderr_info("\n");
1990 stderr_info("EOS EVENT\n");
1991 fflush(stderr);
1992 break;
1993 }
1994 }
1995 }
1996
1997 if (FD_ISSET(fd.g_fd(), &read_fds)) {
1998 r = do_handle_cap(fd, q, fout, nullptr,
1999 count, fps_ts, fmt, false);
2000 if (r == QUEUE_OFF_ON) {
2001 fd.streamoff();
2002 fps_ts.reset();
2003 do_sleep();
2004 goto restart;
2005 }
2006
2007 if (r < 0)
2008 break;
2009 }
2010
2011 }
2012 fd.streamoff();
2013 fcntl(fd.g_fd(), F_SETFL, fd_flags);
2014 stderr_info("\n");
2015
2016 q.free(&fd);
2017 tpg_free(&tpg);
2018 if (source_change && !stream_no_query)
2019 goto recover;
2020
2021 done:
2022 if (options[OptStreamDmaBuf])
2023 exp_q.close_exported_fds();
2024 if (fout && fout != stdout) {
2025 if (host_fd_to >= 0)
2026 write_u32(fout, V4L_STREAM_PACKET_END);
2027 fclose(fout);
2028 }
2029 }
2030
2031 static FILE *open_input_file(cv4l_fd &fd, __u32 type)
2032 {
2033 FILE *fin = nullptr;
2034
2035 if (file_from) {
2036 if (!strcmp(file_from, "-"))
2037 return stdin;
2038 fin = fopen(file_from, "r");
2039 if (!fin)
2040 fprintf(stderr, "could not open %s for reading\n", file_from);
2041 return fin;
2042 }
2043 if (!host_from)
2044 return nullptr;
2045
2046 char *p = std::strchr(host_from, ':');
2047 int listen_fd;
2048 socklen_t clilen;
2049 struct sockaddr_in serv_addr = {}, cli_addr;
2050
2051 if (p) {
2052 host_port_from = strtoul(p + 1, nullptr, 0);
2053 *p = '\0';
2054 }
2055 listen_fd = socket(AF_INET, SOCK_STREAM, 0);
2056 if (listen_fd < 0) {
2057 fprintf(stderr, "could not opening socket\n");
2058 std::exit(EXIT_FAILURE);
2059 }
2060 serv_addr.sin_family = AF_INET;
2061 serv_addr.sin_addr.s_addr = INADDR_ANY;
2062 serv_addr.sin_port = htons(host_port_from);
2063 if (bind(listen_fd, reinterpret_cast<struct sockaddr *>(&serv_addr), sizeof(serv_addr)) < 0) {
2064 fprintf(stderr, "could not bind\n");
2065 std::exit(EXIT_FAILURE);
2066 }
2067 listen(listen_fd, 1);
2068 clilen = sizeof(cli_addr);
2069 host_fd_from = accept(listen_fd, reinterpret_cast<struct sockaddr *>(&cli_addr), &clilen);
2070 if (host_fd_from < 0) {
2071 fprintf(stderr, "could not accept\n");
2072 std::exit(EXIT_FAILURE);
2073 }
2074 fin = fdopen(host_fd_from, "r");
2075 if (read_u32(fin) != V4L_STREAM_ID) {
2076 fprintf(stderr, "unknown protocol ID\n");
2077 std::exit(EXIT_FAILURE);
2078 }
2079 if (read_u32(fin) != V4L_STREAM_VERSION) {
2080 fprintf(stderr, "unknown protocol version\n");
2081 std::exit(EXIT_FAILURE);
2082 }
2083 for (;;) {
2084 __u32 packet = read_u32(fin);
2085 char buf[1024];
2086
2087 if (packet == V4L_STREAM_PACKET_END) {
2088 fprintf(stderr, "END packet read\n");
2089 std::exit(EXIT_FAILURE);
2090 }
2091
2092 if (packet == V4L_STREAM_PACKET_FMT_VIDEO)
2093 break;
2094
2095 unsigned sz = read_u32(fin);
2096 while (sz) {
2097 unsigned rdsize = sz > sizeof(buf) ? sizeof(buf) : sz;
2098 int n;
2099
2100 n = fread(buf, 1, rdsize, fin);
2101 if (n < 0) {
2102 fprintf(stderr, "error reading %d bytes\n", sz);
2103 std::exit(EXIT_FAILURE);
2104 }
2105 sz -= n;
2106 }
2107 }
2108 read_u32(fin);
2109
2110 cv4l_fmt cfmt(type);
2111
2112 unsigned sz = read_u32(fin);
2113
2114 if (sz != V4L_STREAM_PACKET_FMT_VIDEO_SIZE_FMT) {
2115 fprintf(stderr, "unsupported FMT_VIDEO size\n");
2116 std::exit(EXIT_FAILURE);
2117 }
2118 cfmt.s_num_planes(read_u32(fin));
2119 cfmt.s_pixelformat(read_u32(fin));
2120 cfmt.s_width(read_u32(fin));
2121 cfmt.s_height(read_u32(fin));
2122 cfmt.s_field(read_u32(fin));
2123 cfmt.s_colorspace(read_u32(fin));
2124 cfmt.s_ycbcr_enc(read_u32(fin));
2125 cfmt.s_quantization(read_u32(fin));
2126 cfmt.s_xfer_func(read_u32(fin));
2127 cfmt.s_flags(read_u32(fin));
2128 unsigned visible_width = support_out_crop ? cropped_width : cfmt.g_width();
2129 unsigned visible_height = support_out_crop ? cropped_height : cfmt.g_height();
2130
2131 ctx = fwht_alloc(cfmt.g_pixelformat(), visible_width, visible_height,
2132 cfmt.g_width(), cfmt.g_height(),
2133 cfmt.g_field(), cfmt.g_colorspace(), cfmt.g_xfer_func(),
2134 cfmt.g_ycbcr_enc(), cfmt.g_quantization());
2135
2136 read_u32(fin); // pixelaspect.numerator
2137 read_u32(fin); // pixelaspect.denominator
2138
2139 for (unsigned i = 0; i < cfmt.g_num_planes(); i++) {
2140 unsigned sz = read_u32(fin);
2141
2142 if (sz != V4L_STREAM_PACKET_FMT_VIDEO_SIZE_FMT_PLANE) {
2143 fprintf(stderr, "unsupported FMT_VIDEO plane size\n");
2144 std::exit(EXIT_FAILURE);
2145 }
2146 cfmt.s_sizeimage(read_u32(fin), i);
2147 cfmt.s_bytesperline(read_u32(fin), i);
2148 bpl_out[i] = rle_calc_bpl(cfmt.g_bytesperline(i), cfmt.g_pixelformat());
2149 }
2150 if (fd.s_fmt(cfmt)) {
2151 fprintf(stderr, "failed to set new format\n");
2152 std::exit(EXIT_FAILURE);
2153 }
2154 return fin;
2155 }
2156
2157 static void streaming_set_out(cv4l_fd &fd, cv4l_fd &exp_fd)
2158 {
2159 __u32 type = fd.has_vid_m2m() ? v4l_type_invert(fd.g_type()) : fd.g_type();
2160 cv4l_queue q(type, out_memory);
2161 cv4l_queue exp_q(exp_fd.g_type(), V4L2_MEMORY_MMAP);
2162 int fd_flags = fcntl(fd.g_fd(), F_GETFL);
2163 bool use_poll = options[OptStreamPoll];
2164 fps_timestamps fps_ts;
2165 unsigned count = 0;
2166 bool stopped = false;
2167 FILE *fin = nullptr;
2168 cv4l_fmt fmt;
2169
2170 fd.g_fmt(fmt);
2171
2172 if (!(capabilities & (V4L2_CAP_VIDEO_OUTPUT | V4L2_CAP_VIDEO_OUTPUT_MPLANE |
2173 V4L2_CAP_VBI_OUTPUT | V4L2_CAP_SLICED_VBI_OUTPUT |
2174 V4L2_CAP_SDR_OUTPUT | V4L2_CAP_META_OUTPUT |
2175 V4L2_CAP_VIDEO_M2M | V4L2_CAP_VIDEO_M2M_MPLANE))) {
2176 fprintf(stderr, "unsupported stream type\n");
2177 return;
2178 }
2179 if (options[OptStreamOutDmaBuf] && exp_fd.g_fd() < 0) {
2180 fprintf(stderr, "--stream-out-dmabuf can only work in combination with --export-device\n");
2181 return;
2182 }
2183 switch (q.g_type()) {
2184 case V4L2_BUF_TYPE_VIDEO_OUTPUT:
2185 case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE:
2186 break;
2187 default:
2188 if (host_from) {
2189 fprintf(stderr, "--stream-from-host is not supported for non-video streams\n");
2190 return;
2191 }
2192 break;
2193 }
2194
2195 fin = open_input_file(fd, type);
2196
2197 if (q.reqbufs(&fd, reqbufs_count_out)) {
2198 if (q.g_type() != V4L2_BUF_TYPE_VBI_OUTPUT ||
2199 !fd.has_raw_vbi_out() || !fd.has_sliced_vbi_out())
2200 goto done;
2201 fd.s_type(V4L2_BUF_TYPE_SLICED_VBI_OUTPUT);
2202 q.init(fd.g_type(), memory);
2203 if (q.reqbufs(&fd, reqbufs_count_out))
2204 goto done;
2205 }
2206
2207 if (options[OptStreamOutDmaBuf]) {
2208 if (exp_q.reqbufs(&exp_fd, reqbufs_count_out))
2209 goto done;
2210 if (q.export_bufs(&exp_fd, exp_fd.g_type()))
2211 goto done;
2212 }
2213
2214 if (q.obtain_bufs(&fd))
2215 goto done;
2216
2217 restart:
2218 if (do_setup_out_buffers(fd, q, fin, true, false) < 0)
2219 goto done;
2220
2221 fps_ts.determine_field(fd.g_fd(), type);
2222
2223 if (fd.streamon())
2224 goto done;
2225
2226 fd.s_trace(0);
2227 exp_fd.s_trace(0);
2228
2229 if (stream_sleep_count == 0)
2230 do_sleep();
2231
2232 if (use_poll)
2233 fcntl(fd.g_fd(), F_SETFL, fd_flags | O_NONBLOCK);
2234
2235 for (;;) {
2236 int r;
2237
2238 if (use_poll) {
2239 fd_set fds;
2240 struct timeval tv;
2241
2242 FD_ZERO(&fds);
2243 FD_SET(fd.g_fd(), &fds);
2244
2245 /* Timeout. */
2246 tv.tv_sec = 2;
2247 tv.tv_usec = 0;
2248
2249 r = select(fd.g_fd() + 1, nullptr, &fds, nullptr, &tv);
2250
2251 if (r == -1) {
2252 if (EINTR == errno)
2253 continue;
2254 stderr_info("select error: %s\n",
2255 strerror(errno));
2256 goto done;
2257 }
2258
2259 if (r == 0) {
2260 stderr_info("select timeout\n");
2261 goto done;
2262 }
2263 }
2264 r = do_handle_out(fd, q, fin, nullptr,
2265 count, fps_ts, fmt, stopped, false);
2266 if (r == QUEUE_OFF_ON) {
2267 fd.streamoff();
2268 fps_ts.reset();
2269 do_sleep();
2270 goto restart;
2271 }
2272 if (r == QUEUE_STOPPED)
2273 stopped = true;
2274 if (r < 0)
2275 break;
2276
2277 }
2278
2279 if (options[OptDecoderCmd]) {
2280 fd.decoder_cmd(dec_cmd);
2281 options[OptDecoderCmd] = false;
2282 }
2283 fd.streamoff();
2284 fcntl(fd.g_fd(), F_SETFL, fd_flags);
2285 stderr_info("\n");
2286
2287 q.free(&fd);
2288 tpg_free(&tpg);
2289
2290 done:
2291 if (options[OptStreamOutDmaBuf])
2292 exp_q.close_exported_fds();
2293 if (fin && fin != stdin)
2294 fclose(fin);
2295 }
2296
2297 enum stream_type {
2298 CAP,
2299 OUT,
2300 };
2301
2302 static int capture_setup(cv4l_fd &fd, cv4l_queue &in, cv4l_fd *exp_fd, cv4l_fmt *new_fmt = nullptr)
2303 {
2304 if (fd.streamoff(in.g_type())) {
2305 fprintf(stderr, "%s: fd.streamoff error\n", __func__);
2306 return -1;
2307 }
2308
2309 /* release any buffer allocated */
2310 if (in.reqbufs(&fd)) {
2311 fprintf(stderr, "%s: in.reqbufs 0 error\n", __func__);
2312 return -1;
2313 }
2314
2315 if (options[OptSetVideoFormat]) {
2316 cv4l_fmt fmt;
2317
2318 if (vidcap_get_and_update_fmt(fd, fmt)) {
2319 fprintf(stderr, "%s: vidcap_get_and_update_fmt error\n",
2320 __func__);
2321 return -1;
2322 }
2323 fd.s_fmt(fmt, in.g_type());
2324 if (new_fmt)
2325 *new_fmt = fmt;
2326 } else if (new_fmt) {
2327 fd.g_fmt(*new_fmt, in.g_type());
2328 }
2329 get_cap_compose_rect(fd);
2330
2331 if (in.reqbufs(&fd, reqbufs_count_cap)) {
2332 fprintf(stderr, "%s: in.reqbufs %u error\n", __func__,
2333 reqbufs_count_cap);
2334 return -1;
2335 }
2336
2337 if (exp_fd && in.export_bufs(exp_fd, exp_fd->g_type()))
2338 return -1;
2339 if (in.obtain_bufs(&fd) || in.queue_all(&fd)) {
2340 fprintf(stderr, "%s: in.obtain_bufs error\n", __func__);
2341 return -1;
2342 }
2343
2344 if (fd.streamon(in.g_type())) {
2345 fprintf(stderr, "%s: fd.streamon error\n", __func__);
2346 return -1;
2347 }
2348 return 0;
2349 }
2350
2351 static void stateful_m2m(cv4l_fd &fd, cv4l_queue &in, cv4l_queue &out,
2352 FILE *fin, FILE *fout, cv4l_fmt &fmt_in,
2353 const cv4l_fmt &fmt_out, cv4l_fd *exp_fd_p)
2354 {
2355 int fd_flags = fcntl(fd.g_fd(), F_GETFL);
2356 fps_timestamps fps_ts[2];
2357 unsigned count[2] = { 0, 0 };
2358 fd_set fds[3];
2359 fd_set *rd_fds = &fds[0]; /* for capture */
2360 fd_set *ex_fds = &fds[1]; /* for capture */
2361 fd_set *wr_fds = &fds[2]; /* for output */
2362 bool cap_streaming = false;
2363 static struct v4l2_encoder_cmd enc_stop = {
2364 .cmd = V4L2_ENC_CMD_STOP,
2365 };
2366 static struct v4l2_decoder_cmd dec_stop = {
2367 .cmd = V4L2_DEC_CMD_STOP,
2368 };
2369
2370 bool have_eos = subscribe_event(fd, V4L2_EVENT_EOS);
2371 bool is_encoder = false;
2372 bool ignore_count_skip = codec_type == ENCODER;
2373
2374 if (have_eos) {
2375 cv4l_fmt fmt(in.g_type());
2376
2377 fd.g_fmt(fmt);
2378 is_encoder = !fmt.g_bytesperline();
2379 }
2380
2381 bool have_source_change = subscribe_event(fd, V4L2_EVENT_SOURCE_CHANGE);
2382 bool stopped = false;
2383
2384 if (out.reqbufs(&fd, reqbufs_count_out))
2385 return;
2386
2387 switch (do_setup_out_buffers(fd, out, fout, true, !ignore_count_skip)) {
2388 case 0:
2389 break;
2390 case QUEUE_STOPPED:
2391 stopped = true;
2392 break;
2393 default:
2394 return;
2395 }
2396
2397 if (fd.streamon(out.g_type()))
2398 return;
2399
2400 fd.s_trace(0);
2401 if (exp_fd_p)
2402 exp_fd_p->s_trace(0);
2403
2404 if (codec_type != DECODER || !have_source_change)
2405 if (capture_setup(fd, in, exp_fd_p))
2406 return;
2407
2408 fps_ts[CAP].determine_field(fd.g_fd(), in.g_type());
2409 fps_ts[OUT].determine_field(fd.g_fd(), out.g_type());
2410
2411 if (stream_sleep_count == 0)
2412 do_sleep();
2413
2414 fcntl(fd.g_fd(), F_SETFL, fd_flags | O_NONBLOCK);
2415
2416 if (have_eos && stopped) {
2417 if (!verbose)
2418 stderr_info("\n");
2419 stderr_info("STOP %sCODER\n", is_encoder ? "EN" : "DE");
2420 if (is_encoder)
2421 fd.encoder_cmd(enc_stop);
2422 else
2423 fd.decoder_cmd(dec_stop);
2424 }
2425
2426 while (rd_fds || wr_fds || ex_fds) {
2427 struct timeval tv = { 2, 0 };
2428 struct timeval stopped_tv = { 0, 500000 };
2429 int r = 0;
2430
2431 if (rd_fds) {
2432 FD_ZERO(rd_fds);
2433 FD_SET(fd.g_fd(), rd_fds);
2434 }
2435
2436 if (ex_fds) {
2437 FD_ZERO(ex_fds);
2438 FD_SET(fd.g_fd(), ex_fds);
2439 }
2440
2441 if (wr_fds) {
2442 FD_ZERO(wr_fds);
2443 FD_SET(fd.g_fd(), wr_fds);
2444 }
2445
2446 r = select(fd.g_fd() + 1, rd_fds, wr_fds, ex_fds,
2447 stopped ? &stopped_tv : &tv);
2448
2449 if (r == -1) {
2450 if (EINTR == errno)
2451 continue;
2452 stderr_info("select error: %s\n",
2453 strerror(errno));
2454 return;
2455 }
2456 if (r == 0) {
2457 if (!stopped)
2458 stderr_info("select timeout");
2459 stderr_info("\n");
2460 return;
2461 }
2462
2463 if (ex_fds && FD_ISSET(fd.g_fd(), ex_fds)) {
2464 struct v4l2_event ev;
2465
2466 while (!fd.dqevent(ev)) {
2467 if (ev.type == V4L2_EVENT_EOS) {
2468 wr_fds = nullptr;
2469 if (!verbose)
2470 stderr_info("\n");
2471 stderr_info("EOS EVENT\n");
2472 fflush(stderr);
2473 } else if (ev.type == V4L2_EVENT_SOURCE_CHANGE) {
2474 if (!verbose)
2475 stderr_info("\n");
2476 stderr_info("SOURCE CHANGE EVENT\n");
2477 in_source_change_event = true;
2478
2479 /*
2480 * if capture is not streaming, the
2481 * driver will not send a last buffer so
2482 * we set it here
2483 */
2484 if (!cap_streaming)
2485 last_buffer = true;
2486 }
2487 }
2488 }
2489
2490 if (rd_fds && FD_ISSET(fd.g_fd(), rd_fds)) {
2491 r = do_handle_cap(fd, in, fin, nullptr,
2492 count[CAP], fps_ts[CAP], fmt_in,
2493 ignore_count_skip);
2494 if (r == QUEUE_STOPPED)
2495 break;
2496 if (r < 0) {
2497 rd_fds = nullptr;
2498 if (!have_eos) {
2499 ex_fds = nullptr;
2500 break;
2501 }
2502 }
2503 }
2504
2505 if (wr_fds && FD_ISSET(fd.g_fd(), wr_fds)) {
2506 r = do_handle_out(fd, out, fout, nullptr,
2507 count[OUT], fps_ts[OUT], fmt_out, stopped,
2508 !ignore_count_skip);
2509 if (r == QUEUE_STOPPED) {
2510 stopped = true;
2511 if (have_eos) {
2512 if (!verbose)
2513 stderr_info("\n");
2514 stderr_info("STOP %sCODER\n", is_encoder ? "EN" : "DE");
2515 if (is_encoder)
2516 fd.encoder_cmd(enc_stop);
2517 else
2518 fd.decoder_cmd(dec_stop);
2519 }
2520 } else if (r < 0) {
2521 break;
2522 }
2523 }
2524
2525 if (last_buffer) {
2526 if (in_source_change_event) {
2527 struct v4l2_control ctrl = {
2528 .id = V4L2_CID_MIN_BUFFERS_FOR_CAPTURE,
2529 };
2530
2531 {
2532 cv4l_disable_trace dt(fd);
2533 if (!fd.g_ctrl(ctrl))
2534 reqbufs_count_cap = ctrl.value;
2535 }
2536
2537 in_source_change_event = false;
2538 last_buffer = false;
2539 if (capture_setup(fd, in, exp_fd_p, &fmt_in))
2540 return;
2541 fps_ts[CAP].reset();
2542 fps_ts[OUT].reset();
2543 cap_streaming = true;
2544 } else {
2545 break;
2546 }
2547 }
2548 }
2549
2550 fcntl(fd.g_fd(), F_SETFL, fd_flags);
2551 stderr_info("\n");
2552
2553 fd.streamoff(in.g_type());
2554 fd.streamoff(out.g_type());
2555 in.free(&fd);
2556 out.free(&fd);
2557 tpg_free(&tpg);
2558 }
2559
2560 static void stateless_m2m(cv4l_fd &fd, cv4l_queue &in, cv4l_queue &out,
2561 FILE *fin, FILE *fout, cv4l_fmt &fmt_in,
2562 const cv4l_fmt &fmt_out, cv4l_fd *exp_fd_p)
2563 {
2564 fps_timestamps fps_ts[2];
2565 unsigned count[2] = { 0, 0 };
2566 int fd_flags = fcntl(fd.g_fd(), F_GETFL);
2567 bool stopped = false;
2568
2569 if (out.reqbufs(&fd, reqbufs_count_out)) {
2570 fprintf(stderr, "%s: out.reqbufs failed\n", __func__);
2571 return;
2572 }
2573
2574 if (in.reqbufs(&fd, reqbufs_count_cap)) {
2575 fprintf(stderr, "%s: in.reqbufs failed\n", __func__);
2576 return;
2577 }
2578
2579 if (exp_fd_p && in.export_bufs(exp_fd_p, exp_fd_p->g_type()))
2580 return;
2581
2582 if (in.obtain_bufs(&fd)) {
2583 fprintf(stderr, "%s: in.obtain_bufs error\n", __func__);
2584 return;
2585 }
2586
2587 if (do_setup_out_buffers(fd, out, fout, true, true) == QUEUE_ERROR) {
2588 fprintf(stderr, "%s: do_setup_out_buffers failed\n", __func__);
2589 return;
2590 }
2591
2592 if (in.queue_all(&fd)) {
2593 fprintf(stderr, "%s: in.queue_all failed\n", __func__);
2594 return;
2595 }
2596
2597 if (fd.streamon(out.g_type())) {
2598 fprintf(stderr, "%s: streamon for out failed\n", __func__);
2599 return;
2600 }
2601
2602 if (fd.streamon(in.g_type())) {
2603 fprintf(stderr, "%s: streamon for in failed\n", __func__);
2604 return;
2605 }
2606 int index = 0;
2607 bool queue_lst_buf = false;
2608 cv4l_buffer last_in_buf;
2609
2610 fcntl(fd.g_fd(), F_SETFL, fd_flags | O_NONBLOCK);
2611
2612 while (true) {
2613 fd_set except_fds;
2614 int req_fd = fwht_reqs[index].fd;
2615 struct timeval tv = { 2, 0 };
2616
2617 if (req_fd < 0)
2618 break;
2619
2620 FD_ZERO(&except_fds);
2621 FD_SET(req_fd, &except_fds);
2622
2623 int rc = select(req_fd + 1, nullptr, nullptr, &except_fds, &tv);
2624
2625 if (rc == 0) {
2626 fprintf(stderr, "Timeout when waiting for media request\n");
2627 return;
2628 }
2629 if (rc < 0) {
2630 fprintf(stderr, "Unable to select media request: %s\n",
2631 strerror(errno));
2632 return;
2633 }
2634 /*
2635 * it is safe to queue back last cap buffer only after
2636 * the following request is done so that the buffer
2637 * is not needed anymore as a reference frame
2638 */
2639 if (queue_lst_buf) {
2640 if (fd.qbuf(last_in_buf)) {
2641 stderr_info("%s: qbuf failed\n", __func__);
2642 return;
2643 }
2644 }
2645 int buf_idx = -1;
2646 /*
2647 * fin is not sent to do_handle_cap since the capture buf is
2648 * written to the file in current function
2649 */
2650 rc = do_handle_cap(fd, in, nullptr, &buf_idx, count[CAP],
2651 fps_ts[CAP], fmt_in, false);
2652 if (rc && rc != QUEUE_STOPPED) {
2653 stderr_info("%s: do_handle_cap err\n", __func__);
2654 return;
2655 }
2656 /*
2657 * in case of an error in the frame, set last ts to 0 as a
2658 * means to recover so that next request will not use a
2659 * reference buffer. Otherwise the error flag will be set to
2660 * all the future capture buffers.
2661 */
2662 if (buf_idx == -1) {
2663 stderr_info("%s: frame returned with error\n", __func__);
2664 last_fwht_bf_ts = 0;
2665 } else {
2666 cv4l_buffer cap_buf(in, index);
2667 if (fd.querybuf(cap_buf))
2668 return;
2669 last_in_buf = cap_buf;
2670 queue_lst_buf = true;
2671 if (fin && cap_buf.g_bytesused(0) &&
2672 !(cap_buf.g_flags() & V4L2_BUF_FLAG_ERROR)) {
2673 int idx = get_fwht_req_by_ts(cap_buf.g_timestamp_ns());
2674
2675 if (idx < 0) {
2676 fprintf(stderr, "%s: could not find request from buffer\n", __func__);
2677 fprintf(stderr, "%s: ts = %llu\n", __func__, cap_buf.g_timestamp_ns());
2678 return;
2679 }
2680 composed_width = fwht_reqs[idx].params.width;
2681 composed_height = fwht_reqs[idx].params.height;
2682 write_buffer_to_file(fd, in, cap_buf,
2683 fmt_in, fin);
2684 }
2685 }
2686 if (rc == QUEUE_STOPPED)
2687 return;
2688
2689 if (!stopped) {
2690 rc = do_handle_out(fd, out, fout, nullptr, count[OUT],
2691 fps_ts[OUT], fmt_out, false, true);
2692 if (rc) {
2693 stopped = true;
2694 if (rc != QUEUE_STOPPED)
2695 stderr_info("%s: output stream ended\n", __func__);
2696 close(req_fd);
2697 fwht_reqs[index].fd = -1;
2698 }
2699 }
2700 index = (index + 1) % out.g_buffers();
2701 }
2702
2703 fcntl(fd.g_fd(), F_SETFL, fd_flags);
2704 stderr_info("\n");
2705
2706 fd.streamoff(in.g_type());
2707 fd.streamoff(out.g_type());
2708 in.free(&fd);
2709 out.free(&fd);
2710 tpg_free(&tpg);
2711 }
2712
2713 static void streaming_set_m2m(cv4l_fd &fd, cv4l_fd &exp_fd)
2714 {
2715 cv4l_queue in(fd.g_type(), memory);
2716 cv4l_queue out(v4l_type_invert(fd.g_type()), out_memory);
2717 cv4l_queue exp_q(exp_fd.g_type(), V4L2_MEMORY_MMAP);
2718 cv4l_fd *exp_fd_p = nullptr;
2719 FILE *file[2] = {nullptr, nullptr};
2720 cv4l_fmt fmt[2];
2721
2722 fd.g_fmt(fmt[OUT], out.g_type());
2723 fd.g_fmt(fmt[CAP], in.g_type());
2724
2725 if (!fd.has_vid_m2m()) {
2726 fprintf(stderr, "unsupported m2m stream type\n");
2727 return;
2728 }
2729 if (options[OptStreamDmaBuf] && options[OptStreamOutDmaBuf]) {
2730 fprintf(stderr, "--stream-dmabuf and --stream-out-dmabuf not supported for m2m devices\n");
2731 return;
2732 }
2733 if ((options[OptStreamDmaBuf] || options[OptStreamOutDmaBuf]) && exp_fd.g_fd() < 0) {
2734 fprintf(stderr, "--stream-dmabuf or --stream-out-dmabuf can only work in combination with --export-device\n");
2735 return;
2736 }
2737
2738 file[CAP] = open_output_file(fd);
2739 file[OUT] = open_input_file(fd, out.g_type());
2740
2741 if (options[OptStreamDmaBuf]) {
2742 if (exp_q.reqbufs(&exp_fd, reqbufs_count_cap))
2743 goto done;
2744 exp_fd_p = &exp_fd;
2745 }
2746
2747 if (options[OptStreamOutDmaBuf]) {
2748 if (exp_q.reqbufs(&exp_fd, reqbufs_count_out))
2749 goto done;
2750 if (out.export_bufs(&exp_fd, exp_fd.g_type()))
2751 goto done;
2752 }
2753 if (fmt[OUT].g_pixelformat() == V4L2_PIX_FMT_FWHT_STATELESS)
2754 stateless_m2m(fd, in, out, file[CAP], file[OUT], fmt[CAP], fmt[OUT], exp_fd_p);
2755 else
2756 stateful_m2m(fd, in, out, file[CAP], file[OUT], fmt[CAP], fmt[OUT], exp_fd_p);
2757
2758 done:
2759 if (options[OptStreamDmaBuf] || options[OptStreamOutDmaBuf])
2760 exp_q.close_exported_fds();
2761
2762 if (file[CAP] && file[CAP] != stdout)
2763 fclose(file[CAP]);
2764
2765 if (file[OUT] && file[OUT] != stdin)
2766 fclose(file[OUT]);
2767 }
2768
2769 static void streaming_set_cap2out(cv4l_fd &fd, cv4l_fd &out_fd)
2770 {
2771 int fd_flags = fcntl(fd.g_fd(), F_GETFL);
2772 bool use_poll = options[OptStreamPoll];
2773 bool use_dmabuf = options[OptStreamDmaBuf] || options[OptStreamOutDmaBuf];
2774 bool use_userptr = options[OptStreamUser] && options[OptStreamOutUser];
2775 __u32 out_type = out_fd.has_vid_m2m() ? v4l_type_invert(out_fd.g_type()) : out_fd.g_type();
2776 cv4l_queue in(fd.g_type(), memory);
2777 cv4l_queue out(out_type, out_memory);
2778 fps_timestamps fps_ts[2];
2779 unsigned count[2] = { 0, 0 };
2780 FILE *file[2] = {nullptr, nullptr};
2781 fd_set fds;
2782 unsigned cnt = 0;
2783 cv4l_fmt fmt[2];
2784
2785 out_fd.g_fmt(fmt[OUT], out.g_type());
2786 fd.g_fmt(fmt[CAP], in.g_type());
2787 if (!(capabilities & (V4L2_CAP_VIDEO_CAPTURE |
2788 V4L2_CAP_VIDEO_CAPTURE_MPLANE |
2789 V4L2_CAP_VIDEO_M2M |
2790 V4L2_CAP_VIDEO_M2M_MPLANE))) {
2791 fprintf(stderr, "unsupported capture stream type\n");
2792 return;
2793 }
2794 if (!(out_capabilities & (V4L2_CAP_VIDEO_OUTPUT |
2795 V4L2_CAP_VIDEO_OUTPUT_MPLANE |
2796 V4L2_CAP_VIDEO_M2M |
2797 V4L2_CAP_VIDEO_M2M_MPLANE))) {
2798 fprintf(stderr, "unsupported output stream type\n");
2799 return;
2800 }
2801 if (options[OptStreamDmaBuf] && !options[OptStreamOutMmap]) {
2802 fprintf(stderr, "--stream-dmabuf can only work in combination with --stream-out-mmap\n");
2803 return;
2804 }
2805 if (options[OptStreamOutDmaBuf] && !options[OptStreamMmap]) {
2806 fprintf(stderr, "--stream-out-dmabuf can only work in combination with --stream-mmap\n");
2807 return;
2808 }
2809 if (options[OptStreamDmaBuf])
2810 reqbufs_count_cap = reqbufs_count_out;
2811 if (options[OptStreamOutDmaBuf])
2812 reqbufs_count_out = reqbufs_count_cap;
2813 if (!use_dmabuf && !use_userptr) {
2814 fprintf(stderr, "Allowed combinations (for now):\n");
2815 fprintf(stderr, "\t--stream-mmap and --stream-out-dmabuf\n");
2816 fprintf(stderr, "\t--stream-dmabuf and --stream-out-mmap\n");
2817 fprintf(stderr, "\t--stream-user and --stream-out-user\n");
2818 return;
2819 }
2820
2821 if (file_to) {
2822 if (!strcmp(file_to, "-"))
2823 file[CAP] = stdout;
2824 else
2825 file[CAP] = fopen(file_to, "w+");
2826 if (!file[CAP]) {
2827 fprintf(stderr, "could not open %s for writing\n", file_to);
2828 return;
2829 }
2830 }
2831
2832 if (file_from) {
2833 if (!strcmp(file_from, "-"))
2834 file[OUT] = stdin;
2835 else
2836 file[OUT] = fopen(file_from, "r");
2837 if (!file[OUT]) {
2838 fprintf(stderr, "could not open %s for reading\n", file_from);
2839 return;
2840 }
2841 }
2842
2843 if (in.reqbufs(&fd, reqbufs_count_cap) ||
2844 out.reqbufs(&out_fd, reqbufs_count_out))
2845 goto done;
2846
2847 if (options[OptStreamDmaBuf]) {
2848 if (in.export_bufs(&out_fd, out.g_type()))
2849 goto done;
2850 } else if (options[OptStreamOutDmaBuf]) {
2851 if (out.export_bufs(&fd, in.g_type()))
2852 goto done;
2853 }
2854
2855 if (in.g_num_planes() != out.g_num_planes()) {
2856 fprintf(stderr, "mismatch between number of planes\n");
2857 goto done;
2858 }
2859 if (in.obtain_bufs(&fd)) {
2860 fprintf(stderr, "%s: in.obtain_bufs failed\n", __func__);
2861 goto done;
2862 }
2863
2864 if (in.queue_all(&fd)) {
2865 fprintf(stderr, "%s: in.queue_all failed\n", __func__);
2866 goto done;
2867 }
2868
2869
2870 if (do_setup_out_buffers(out_fd, out, file[OUT], false, false) == QUEUE_ERROR) {
2871 fprintf(stderr, "%s: do_setup_out_buffers failed\n", __func__);
2872 goto done;
2873 }
2874
2875 fps_ts[CAP].determine_field(fd.g_fd(), in.g_type());
2876 fps_ts[OUT].determine_field(out_fd.g_fd(), out.g_type());
2877
2878 if (fd.streamon() || out_fd.streamon())
2879 goto done;
2880
2881 fd.s_trace(0);
2882 out_fd.s_trace(0);
2883
2884 if (stream_sleep_count == 0)
2885 do_sleep();
2886
2887 if (use_poll)
2888 fcntl(fd.g_fd(), F_SETFL, fd_flags | O_NONBLOCK);
2889
2890 while (true) {
2891 struct timeval tv = { use_poll ? 2 : 0, 0 };
2892 int r = 0;
2893
2894 FD_ZERO(&fds);
2895 FD_SET(fd.g_fd(), &fds);
2896
2897 if (use_poll)
2898 r = select(fd.g_fd() + 1, &fds, nullptr, nullptr, &tv);
2899
2900 if (r == -1) {
2901 if (EINTR == errno)
2902 continue;
2903 stderr_info("select error: %s\n",
2904 strerror(errno));
2905 goto done;
2906 }
2907 if (use_poll && r == 0) {
2908 stderr_info("select timeout\n");
2909 goto done;
2910 }
2911
2912 if (FD_ISSET(fd.g_fd(), &fds)) {
2913 int index = -1;
2914
2915 r = do_handle_cap(fd, in, file[CAP], &index,
2916 count[CAP], fps_ts[CAP], fmt[CAP], true);
2917 if (r)
2918 stderr_info("handle cap %d\n", r);
2919 if (!r) {
2920 cv4l_buffer buf(in, index);
2921
2922 if (fd.querybuf(buf))
2923 break;
2924 r = do_handle_out(out_fd, out, file[OUT], &buf,
2925 count[OUT], fps_ts[OUT], fmt[OUT],
2926 false, false);
2927 }
2928 if (r)
2929 stderr_info("handle out %d\n", r);
2930 if (!r && cnt++ > 1)
2931 r = do_handle_out_to_in(out_fd, fd, out, in);
2932 if (r)
2933 stderr_info("handle out2in %d\n", r);
2934 if (r < 0) {
2935 fd.streamoff();
2936 out_fd.streamoff();
2937 break;
2938 }
2939 }
2940 }
2941
2942 done:
2943 fcntl(fd.g_fd(), F_SETFL, fd_flags);
2944 stderr_info("\n");
2945
2946 if (options[OptStreamDmaBuf])
2947 out.close_exported_fds();
2948 if (options[OptStreamOutDmaBuf])
2949 in.close_exported_fds();
2950
2951 in.free(&fd);
2952 out.free(&out_fd);
2953 tpg_free(&tpg);
2954
2955 if (file[CAP] && file[CAP] != stdout)
2956 fclose(file[CAP]);
2957
2958 if (file[OUT] && file[OUT] != stdin)
2959 fclose(file[OUT]);
2960 }
2961
2962 void streaming_set(cv4l_fd &fd, cv4l_fd &out_fd, cv4l_fd &exp_fd)
2963 {
2964 int do_cap = options[OptStreamMmap] + options[OptStreamUser] + options[OptStreamDmaBuf];
2965 int do_out = options[OptStreamOutMmap] + options[OptStreamOutUser] + options[OptStreamOutDmaBuf];
2966
2967 if (out_fd.g_fd() < 0) {
2968 out_capabilities = capabilities;
2969 out_priv_magic = priv_magic;
2970 }
2971
2972 if (do_cap > 1) {
2973 fprintf(stderr, "only one of --stream-mmap/user/dmabuf is allowed\n");
2974 return;
2975 }
2976 if (do_out > 1) {
2977 fprintf(stderr, "only one of --stream-out-mmap/user/dmabuf is allowed\n");
2978 return;
2979 }
2980
2981 unsigned int old_trace_fd = fd.g_trace();
2982 unsigned int old_trace_out_fd = out_fd.g_trace();
2983 unsigned int old_trace_exp_fd = exp_fd.g_trace();
2984
2985 get_cap_compose_rect(fd);
2986 get_out_crop_rect(fd);
2987 get_codec_type(fd);
2988
2989 if (!reqbufs_count_cap) {
2990 struct v4l2_control ctrl = {
2991 .id = V4L2_CID_MIN_BUFFERS_FOR_CAPTURE,
2992 };
2993
2994 cv4l_disable_trace dt(fd);
2995 if (!fd.g_ctrl(ctrl))
2996 reqbufs_count_cap = ctrl.value;
2997 if (!reqbufs_count_cap)
2998 reqbufs_count_cap = 4;
2999 }
3000 if (!reqbufs_count_out) {
3001 struct v4l2_control ctrl = {
3002 .id = V4L2_CID_MIN_BUFFERS_FOR_OUTPUT,
3003 };
3004
3005 cv4l_disable_trace dt(fd);
3006 if (!fd.g_ctrl(ctrl))
3007 reqbufs_count_out = ctrl.value;
3008 if (!reqbufs_count_out)
3009 reqbufs_count_out = 4;
3010 }
3011
3012 if (do_cap && do_out && out_fd.g_fd() < 0)
3013 streaming_set_m2m(fd, exp_fd);
3014 else if (do_cap && do_out)
3015 streaming_set_cap2out(fd, out_fd);
3016 else if (do_cap)
3017 streaming_set_cap(fd, exp_fd);
3018 else if (do_out)
3019 streaming_set_out(fd, exp_fd);
3020
3021 fd.s_trace(old_trace_fd);
3022 out_fd.s_trace(old_trace_out_fd);
3023 exp_fd.s_trace(old_trace_exp_fd);
3024 }
3025
3026 void streaming_list(cv4l_fd &fd, cv4l_fd &out_fd)
3027 {
3028 cv4l_fd *p_out_fd = out_fd.g_fd() < 0 ? &fd : &out_fd;
3029
3030 if (out_fd.g_fd() < 0)
3031 out_capabilities = capabilities;
3032
3033 if (options[OptListBuffers])
3034 list_buffers(fd, fd.g_type());
3035
3036 if (options[OptListBuffersOut])
3037 list_buffers(*p_out_fd, p_out_fd->has_vid_m2m() ?
3038 v4l_type_invert(p_out_fd->g_type()) : p_out_fd->g_type());
3039
3040 if (options[OptStreamBufCaps])
3041 stream_buf_caps(fd, fd.g_type());
3042
3043 if (options[OptStreamOutBufCaps])
3044 stream_buf_caps(*p_out_fd, p_out_fd->has_vid_m2m() ?
3045 v4l_type_invert(p_out_fd->g_type()) : p_out_fd->g_type());
3046
3047 if (options[OptListBuffersVbi])
3048 list_buffers(fd, V4L2_BUF_TYPE_VBI_CAPTURE);
3049
3050 if (options[OptListBuffersSlicedVbi])
3051 list_buffers(fd, V4L2_BUF_TYPE_SLICED_VBI_CAPTURE);
3052
3053 if (options[OptListBuffersVbiOut])
3054 list_buffers(*p_out_fd, V4L2_BUF_TYPE_VBI_OUTPUT);
3055
3056 if (options[OptListBuffersSlicedVbiOut])
3057 list_buffers(*p_out_fd, V4L2_BUF_TYPE_SLICED_VBI_OUTPUT);
3058
3059 if (options[OptListBuffersSdr])
3060 list_buffers(fd, V4L2_BUF_TYPE_SDR_CAPTURE);
3061
3062 if (options[OptListBuffersSdrOut])
3063 list_buffers(fd, V4L2_BUF_TYPE_SDR_OUTPUT);
3064
3065 if (options[OptListBuffersMeta])
3066 list_buffers(fd, V4L2_BUF_TYPE_META_CAPTURE);
3067
3068 if (options[OptListPatterns]) {
3069 printf("List of available patterns:\n");
3070 for (unsigned i = 0; tpg_pattern_strings[i]; i++)
3071 printf("\t%2d: %s\n", i, tpg_pattern_strings[i]);
3072 }
3073 }