2 * Copyright (c) 2012 Stefano Sabatini
4 * This file is part of FFmpeg.
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 * send commands filter
26 #include "libavutil/avstring.h"
27 #include "libavutil/bprint.h"
28 #include "libavutil/eval.h"
29 #include "libavutil/file.h"
30 #include "libavutil/opt.h"
31 #include "libavutil/parseutils.h"
37 #define COMMAND_FLAG_ENTER 1
38 #define COMMAND_FLAG_LEAVE 2
39 #define COMMAND_FLAG_EXPR 4
41 static const char *const var_names[] = {
42 "N", /* frame number */
43 "T", /* frame time in seconds */
44 "POS", /* original position in the file of the frame */
45 "PTS", /* frame pts */
46 "TS", /* interval start time in seconds */
47 "TE", /* interval end time in seconds */
48 "TI", /* interval interpolated value: TI = (T - TS) / (TE - TS) */
63 static inline char *make_command_flags_str(AVBPrint *pbuf, int flags)
65 static const char * const flag_strings[] = { "enter", "leave", "expr" };
68 av_bprint_init(pbuf, 0, AV_BPRINT_SIZE_AUTOMATIC);
69 for (i = 0; i < FF_ARRAY_ELEMS(flag_strings); i++) {
72 av_bprint_chars(pbuf, '+', 1);
73 av_bprintf(pbuf, "%s", flag_strings[i]);
81 typedef struct Command {
83 char *target, *command, *arg;
87 typedef struct Interval {
88 int64_t start_ts; ///< start timestamp expressed as microseconds units
89 int64_t end_ts; ///< end timestamp expressed as microseconds units
90 int index; ///< unique index for these interval commands
93 int enabled; ///< current time detected inside this interval
96 typedef struct SendCmdContext {
101 char *commands_filename;
105 #define OFFSET(x) offsetof(SendCmdContext, x)
106 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM | AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_VIDEO_PARAM
107 static const AVOption options[] = {
108 { "commands", "set commands", OFFSET(commands_str), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS },
109 { "c", "set commands", OFFSET(commands_str), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS },
110 { "filename", "set commands file", OFFSET(commands_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS },
111 { "f", "set commands file", OFFSET(commands_filename), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, FLAGS },
115 #define SPACES " \f\t\n\r"
117 static void skip_comments(const char **buf)
120 /* skip leading spaces */
121 *buf += strspn(*buf, SPACES);
127 /* skip comment until the end of line */
128 *buf += strcspn(*buf, "\n");
134 #define COMMAND_DELIMS " \f\t\n\r,;"
136 static int parse_command(Command *cmd, int cmd_count, int interval_count,
137 const char **buf, void *log_ctx)
141 memset(cmd, 0, sizeof(Command));
142 cmd->index = cmd_count;
144 /* format: [FLAGS] target command arg */
145 *buf += strspn(*buf, SPACES);
149 (*buf)++; /* skip "[" */
152 int len = strcspn(*buf, "|+]");
154 if (!strncmp(*buf, "enter", strlen("enter"))) cmd->flags |= COMMAND_FLAG_ENTER;
155 else if (!strncmp(*buf, "leave", strlen("leave"))) cmd->flags |= COMMAND_FLAG_LEAVE;
156 else if (!strncmp(*buf, "expr", strlen("expr"))) cmd->flags |= COMMAND_FLAG_EXPR;
159 av_strlcpy(flag_buf, *buf, sizeof(flag_buf));
160 av_log(log_ctx, AV_LOG_ERROR,
161 "Unknown flag '%s' in interval #%d, command #%d\n",
162 flag_buf, interval_count, cmd_count);
163 return AVERROR(EINVAL);
168 if (!strspn(*buf, "+|")) {
169 av_log(log_ctx, AV_LOG_ERROR,
170 "Invalid flags char '%c' in interval #%d, command #%d\n",
171 **buf, interval_count, cmd_count);
172 return AVERROR(EINVAL);
179 av_log(log_ctx, AV_LOG_ERROR,
180 "Missing flag terminator or extraneous data found at the end of flags "
181 "in interval #%d, command #%d\n", interval_count, cmd_count);
182 return AVERROR(EINVAL);
184 (*buf)++; /* skip "]" */
186 cmd->flags = COMMAND_FLAG_ENTER;
189 *buf += strspn(*buf, SPACES);
190 cmd->target = av_get_token(buf, COMMAND_DELIMS);
191 if (!cmd->target || !cmd->target[0]) {
192 av_log(log_ctx, AV_LOG_ERROR,
193 "No target specified in interval #%d, command #%d\n",
194 interval_count, cmd_count);
195 ret = AVERROR(EINVAL);
199 *buf += strspn(*buf, SPACES);
200 cmd->command = av_get_token(buf, COMMAND_DELIMS);
201 if (!cmd->command || !cmd->command[0]) {
202 av_log(log_ctx, AV_LOG_ERROR,
203 "No command specified in interval #%d, command #%d\n",
204 interval_count, cmd_count);
205 ret = AVERROR(EINVAL);
209 *buf += strspn(*buf, SPACES);
210 cmd->arg = av_get_token(buf, COMMAND_DELIMS);
215 av_freep(&cmd->target);
216 av_freep(&cmd->command);
221 static int parse_commands(Command **cmds, int *nb_cmds, int interval_count,
222 const char **buf, void *log_ctx)
234 if ((ret = parse_command(&cmd, cmd_count, interval_count, buf, log_ctx)) < 0)
238 /* (re)allocate commands array if required */
240 n = FFMAX(16, 2*n); /* first allocation = 16, or double the number */
241 *cmds = av_realloc_f(*cmds, n, 2*sizeof(Command));
243 av_log(log_ctx, AV_LOG_ERROR,
244 "Could not (re)allocate command array\n");
245 return AVERROR(ENOMEM);
249 (*cmds)[(*nb_cmds)++] = cmd;
251 *buf += strspn(*buf, SPACES);
252 if (**buf && **buf != ';' && **buf != ',') {
253 av_log(log_ctx, AV_LOG_ERROR,
254 "Missing separator or extraneous data found at the end of "
255 "interval #%d, in command #%d\n",
256 interval_count, cmd_count);
257 av_log(log_ctx, AV_LOG_ERROR,
258 "Command was parsed as: flags:[%s] target:%s command:%s arg:%s\n",
259 make_command_flags_str(&pbuf, cmd.flags), cmd.target, cmd.command, cmd.arg);
260 return AVERROR(EINVAL);
271 #define DELIMS " \f\t\n\r,;"
273 static int parse_interval(Interval *interval, int interval_count,
274 const char **buf, void *log_ctx)
279 *buf += strspn(*buf, SPACES);
284 memset(interval, 0, sizeof(Interval));
285 interval->index = interval_count;
287 /* format: INTERVAL COMMANDS */
290 intervalstr = av_get_token(buf, DELIMS);
291 if (intervalstr && intervalstr[0]) {
294 start = av_strtok(intervalstr, "-", &end);
296 ret = AVERROR(EINVAL);
297 av_log(log_ctx, AV_LOG_ERROR,
298 "Invalid interval specification '%s' in interval #%d\n",
299 intervalstr, interval_count);
302 if ((ret = av_parse_time(&interval->start_ts, start, 1)) < 0) {
303 av_log(log_ctx, AV_LOG_ERROR,
304 "Invalid start time specification '%s' in interval #%d\n",
305 start, interval_count);
310 if ((ret = av_parse_time(&interval->end_ts, end, 1)) < 0) {
311 av_log(log_ctx, AV_LOG_ERROR,
312 "Invalid end time specification '%s' in interval #%d\n",
313 end, interval_count);
317 interval->end_ts = INT64_MAX;
319 if (interval->end_ts < interval->start_ts) {
320 av_log(log_ctx, AV_LOG_ERROR,
321 "Invalid end time '%s' in interval #%d: "
322 "cannot be lesser than start time '%s'\n",
323 end, interval_count, start);
324 ret = AVERROR(EINVAL);
328 av_log(log_ctx, AV_LOG_ERROR,
329 "No interval specified for interval #%d\n", interval_count);
330 ret = AVERROR(EINVAL);
335 ret = parse_commands(&interval->commands, &interval->nb_commands,
336 interval_count, buf, log_ctx);
339 av_free(intervalstr);
343 static int parse_intervals(Interval **intervals, int *nb_intervals,
344 const char *buf, void *log_ctx)
346 int interval_count = 0;
362 if ((ret = parse_interval(&interval, interval_count, &buf, log_ctx)) < 0)
365 buf += strspn(buf, SPACES);
368 av_log(log_ctx, AV_LOG_ERROR,
369 "Missing terminator or extraneous data found at the end of interval #%d\n",
371 return AVERROR(EINVAL);
373 buf++; /* skip ';' */
377 /* (re)allocate commands array if required */
378 if (*nb_intervals == n) {
379 n = FFMAX(16, 2*n); /* first allocation = 16, or double the number */
380 *intervals = av_realloc_f(*intervals, n, 2*sizeof(Interval));
382 av_log(log_ctx, AV_LOG_ERROR,
383 "Could not (re)allocate intervals array\n");
384 return AVERROR(ENOMEM);
388 (*intervals)[(*nb_intervals)++] = interval;
394 static int cmp_intervals(const void *a, const void *b)
396 const Interval *i1 = a;
397 const Interval *i2 = b;
398 return 2 * FFDIFFSIGN(i1->start_ts, i2->start_ts) + FFDIFFSIGN(i1->index, i2->index);
401 static av_cold int init(AVFilterContext *ctx)
403 SendCmdContext *s = ctx->priv;
406 if ((!!s->commands_filename + !!s->commands_str) != 1) {
407 av_log(ctx, AV_LOG_ERROR,
408 "One and only one of the filename or commands options must be specified\n");
409 return AVERROR(EINVAL);
412 if (s->commands_filename) {
413 uint8_t *file_buf, *buf;
415 ret = av_file_map(s->commands_filename,
416 &file_buf, &file_bufsize, 0, ctx);
420 /* create a 0-terminated string based on the read file */
421 buf = av_malloc(file_bufsize + 1);
423 av_file_unmap(file_buf, file_bufsize);
424 return AVERROR(ENOMEM);
426 memcpy(buf, file_buf, file_bufsize);
427 buf[file_bufsize] = 0;
428 av_file_unmap(file_buf, file_bufsize);
429 s->commands_str = buf;
432 if ((ret = parse_intervals(&s->intervals, &s->nb_intervals,
433 s->commands_str, ctx)) < 0)
436 if (s->nb_intervals == 0) {
437 av_log(ctx, AV_LOG_ERROR, "No commands were specified\n");
438 return AVERROR(EINVAL);
441 qsort(s->intervals, s->nb_intervals, sizeof(Interval), cmp_intervals);
443 av_log(ctx, AV_LOG_DEBUG, "Parsed commands:\n");
444 for (i = 0; i < s->nb_intervals; i++) {
446 Interval *interval = &s->intervals[i];
447 av_log(ctx, AV_LOG_VERBOSE, "start_time:%f end_time:%f index:%d\n",
448 (double)interval->start_ts/1000000, (double)interval->end_ts/1000000, interval->index);
449 for (j = 0; j < interval->nb_commands; j++) {
450 Command *cmd = &interval->commands[j];
451 av_log(ctx, AV_LOG_VERBOSE,
452 " [%s] target:%s command:%s arg:%s index:%d\n",
453 make_command_flags_str(&pbuf, cmd->flags), cmd->target, cmd->command, cmd->arg, cmd->index);
460 static av_cold void uninit(AVFilterContext *ctx)
462 SendCmdContext *s = ctx->priv;
465 for (i = 0; i < s->nb_intervals; i++) {
466 Interval *interval = &s->intervals[i];
467 for (j = 0; j < interval->nb_commands; j++) {
468 Command *cmd = &interval->commands[j];
469 av_freep(&cmd->target);
470 av_freep(&cmd->command);
473 av_freep(&interval->commands);
475 av_freep(&s->intervals);
478 static int filter_frame(AVFilterLink *inlink, AVFrame *ref)
480 AVFilterContext *ctx = inlink->dst;
481 SendCmdContext *s = ctx->priv;
485 if (ref->pts == AV_NOPTS_VALUE)
488 ts = av_rescale_q(ref->pts, inlink->time_base, AV_TIME_BASE_Q);
490 #define WITHIN_INTERVAL(ts, start_ts, end_ts) ((ts) >= (start_ts) && (ts) < (end_ts))
492 for (i = 0; i < s->nb_intervals; i++) {
493 Interval *interval = &s->intervals[i];
496 if (!interval->enabled && WITHIN_INTERVAL(ts, interval->start_ts, interval->end_ts)) {
497 flags += COMMAND_FLAG_ENTER;
498 interval->enabled = 1;
500 if (interval->enabled && !WITHIN_INTERVAL(ts, interval->start_ts, interval->end_ts)) {
501 flags += COMMAND_FLAG_LEAVE;
502 interval->enabled = 0;
504 if (interval->enabled)
505 flags += COMMAND_FLAG_EXPR;
509 av_log(ctx, AV_LOG_VERBOSE,
510 "[%s] interval #%d start_ts:%f end_ts:%f ts:%f\n",
511 make_command_flags_str(&pbuf, flags), interval->index,
512 (double)interval->start_ts/1000000, (double)interval->end_ts/1000000,
515 for (j = 0; flags && j < interval->nb_commands; j++) {
516 Command *cmd = &interval->commands[j];
517 char *cmd_arg = cmd->arg;
520 if (cmd->flags & flags) {
521 if (cmd->flags & COMMAND_FLAG_EXPR) {
522 double var_values[VAR_VARS_NB], res;
523 double start = TS2T(interval->start_ts, AV_TIME_BASE_Q);
524 double end = TS2T(interval->end_ts, AV_TIME_BASE_Q);
525 double current = TS2T(ref->pts, inlink->time_base);
527 var_values[VAR_N] = inlink->frame_count_in;
528 var_values[VAR_POS] = ref->pkt_pos == -1 ? NAN : ref->pkt_pos;
529 var_values[VAR_PTS] = TS2D(ref->pts);
530 var_values[VAR_T] = current;
531 var_values[VAR_TS] = start;
532 var_values[VAR_TE] = end;
533 var_values[VAR_TI] = (current - start) / (end - start);
535 if ((ret = av_expr_parse_and_eval(&res, cmd->arg, var_names, var_values,
536 NULL, NULL, NULL, NULL, NULL, 0, NULL)) < 0) {
537 av_log(ctx, AV_LOG_ERROR, "Invalid expression '%s' for command argument.\n", cmd->arg);
539 return AVERROR(EINVAL);
542 cmd_arg = av_asprintf("%g", res);
545 return AVERROR(ENOMEM);
548 av_log(ctx, AV_LOG_VERBOSE,
549 "Processing command #%d target:%s command:%s arg:%s\n",
550 cmd->index, cmd->target, cmd->command, cmd_arg);
551 ret = avfilter_graph_send_command(inlink->graph,
552 cmd->target, cmd->command, cmd_arg,
554 AVFILTER_CMD_FLAG_ONE);
555 av_log(ctx, AV_LOG_VERBOSE,
556 "Command reply for command #%d: ret:%s res:%s\n",
557 cmd->index, av_err2str(ret), buf);
558 if (cmd->flags & COMMAND_FLAG_EXPR)
566 switch (inlink->type) {
567 case AVMEDIA_TYPE_VIDEO:
568 case AVMEDIA_TYPE_AUDIO:
569 return ff_filter_frame(inlink->dst->outputs[0], ref);
572 return AVERROR(ENOSYS);
575 #if CONFIG_SENDCMD_FILTER
577 #define sendcmd_options options
578 AVFILTER_DEFINE_CLASS(sendcmd);
580 static const AVFilterPad sendcmd_inputs[] = {
583 .type = AVMEDIA_TYPE_VIDEO,
584 .filter_frame = filter_frame,
589 static const AVFilterPad sendcmd_outputs[] = {
592 .type = AVMEDIA_TYPE_VIDEO,
597 const AVFilter ff_vf_sendcmd = {
599 .description = NULL_IF_CONFIG_SMALL("Send commands to filters."),
602 .priv_size = sizeof(SendCmdContext),
603 .inputs = sendcmd_inputs,
604 .outputs = sendcmd_outputs,
605 .priv_class = &sendcmd_class,
610 #if CONFIG_ASENDCMD_FILTER
612 #define asendcmd_options options
613 AVFILTER_DEFINE_CLASS(asendcmd);
615 static const AVFilterPad asendcmd_inputs[] = {
618 .type = AVMEDIA_TYPE_AUDIO,
619 .filter_frame = filter_frame,
624 static const AVFilterPad asendcmd_outputs[] = {
627 .type = AVMEDIA_TYPE_AUDIO,
632 const AVFilter ff_af_asendcmd = {
634 .description = NULL_IF_CONFIG_SMALL("Send commands to filters."),
637 .priv_size = sizeof(SendCmdContext),
638 .inputs = asendcmd_inputs,
639 .outputs = asendcmd_outputs,
640 .priv_class = &asendcmd_class,