f_select.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. /*
  2. * Copyright (c) 2011 Stefano Sabatini
  3. *
  4. * This file is part of FFmpeg.
  5. *
  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.
  10. *
  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.
  15. *
  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
  19. */
  20. /**
  21. * @file
  22. * filter for selecting which frame passes in the filterchain
  23. */
  24. #include "libavutil/avstring.h"
  25. #include "libavutil/eval.h"
  26. #include "libavutil/fifo.h"
  27. #include "libavutil/internal.h"
  28. #include "libavutil/opt.h"
  29. #include "avfilter.h"
  30. #include "audio.h"
  31. #include "formats.h"
  32. #include "internal.h"
  33. #include "video.h"
  34. #include "scene_sad.h"
  35. static const char *const var_names[] = {
  36. "TB", ///< timebase
  37. "pts", ///< original pts in the file of the frame
  38. "start_pts", ///< first PTS in the stream, expressed in TB units
  39. "prev_pts", ///< previous frame PTS
  40. "prev_selected_pts", ///< previous selected frame PTS
  41. "t", ///< timestamp expressed in seconds
  42. "start_t", ///< first PTS in the stream, expressed in seconds
  43. "prev_t", ///< previous frame time
  44. "prev_selected_t", ///< previously selected time
  45. "pict_type", ///< the type of picture in the movie
  46. "I",
  47. "P",
  48. "B",
  49. "S",
  50. "SI",
  51. "SP",
  52. "BI",
  53. "PICT_TYPE_I",
  54. "PICT_TYPE_P",
  55. "PICT_TYPE_B",
  56. "PICT_TYPE_S",
  57. "PICT_TYPE_SI",
  58. "PICT_TYPE_SP",
  59. "PICT_TYPE_BI",
  60. "interlace_type", ///< the frame interlace type
  61. "PROGRESSIVE",
  62. "TOPFIRST",
  63. "BOTTOMFIRST",
  64. "consumed_samples_n",///< number of samples consumed by the filter (only audio)
  65. "samples_n", ///< number of samples in the current frame (only audio)
  66. "sample_rate", ///< sample rate (only audio)
  67. "n", ///< frame number (starting from zero)
  68. "selected_n", ///< selected frame number (starting from zero)
  69. "prev_selected_n", ///< number of the last selected frame
  70. "key", ///< tell if the frame is a key frame
  71. "pos", ///< original position in the file of the frame
  72. "scene",
  73. "concatdec_select", ///< frame is within the interval set by the concat demuxer
  74. NULL
  75. };
  76. enum var_name {
  77. VAR_TB,
  78. VAR_PTS,
  79. VAR_START_PTS,
  80. VAR_PREV_PTS,
  81. VAR_PREV_SELECTED_PTS,
  82. VAR_T,
  83. VAR_START_T,
  84. VAR_PREV_T,
  85. VAR_PREV_SELECTED_T,
  86. VAR_PICT_TYPE,
  87. VAR_I,
  88. VAR_P,
  89. VAR_B,
  90. VAR_S,
  91. VAR_SI,
  92. VAR_SP,
  93. VAR_BI,
  94. VAR_PICT_TYPE_I,
  95. VAR_PICT_TYPE_P,
  96. VAR_PICT_TYPE_B,
  97. VAR_PICT_TYPE_S,
  98. VAR_PICT_TYPE_SI,
  99. VAR_PICT_TYPE_SP,
  100. VAR_PICT_TYPE_BI,
  101. VAR_INTERLACE_TYPE,
  102. VAR_INTERLACE_TYPE_P,
  103. VAR_INTERLACE_TYPE_T,
  104. VAR_INTERLACE_TYPE_B,
  105. VAR_CONSUMED_SAMPLES_N,
  106. VAR_SAMPLES_N,
  107. VAR_SAMPLE_RATE,
  108. VAR_N,
  109. VAR_SELECTED_N,
  110. VAR_PREV_SELECTED_N,
  111. VAR_KEY,
  112. VAR_POS,
  113. VAR_SCENE,
  114. VAR_CONCATDEC_SELECT,
  115. VAR_VARS_NB
  116. };
  117. typedef struct SelectContext {
  118. const AVClass *class;
  119. char *expr_str;
  120. AVExpr *expr;
  121. double var_values[VAR_VARS_NB];
  122. int do_scene_detect; ///< 1 if the expression requires scene detection variables, 0 otherwise
  123. ff_scene_sad_fn sad; ///< Sum of the absolute difference function (scene detect only)
  124. double prev_mafd; ///< previous MAFD (scene detect only)
  125. AVFrame *prev_picref; ///< previous frame (scene detect only)
  126. double select;
  127. int select_out; ///< mark the selected output pad index
  128. int nb_outputs;
  129. } SelectContext;
  130. #define OFFSET(x) offsetof(SelectContext, x)
  131. #define DEFINE_OPTIONS(filt_name, FLAGS) \
  132. static const AVOption filt_name##_options[] = { \
  133. { "expr", "set an expression to use for selecting frames", OFFSET(expr_str), AV_OPT_TYPE_STRING, { .str = "1" }, .flags=FLAGS }, \
  134. { "e", "set an expression to use for selecting frames", OFFSET(expr_str), AV_OPT_TYPE_STRING, { .str = "1" }, .flags=FLAGS }, \
  135. { "outputs", "set the number of outputs", OFFSET(nb_outputs), AV_OPT_TYPE_INT, {.i64 = 1}, 1, INT_MAX, .flags=FLAGS }, \
  136. { "n", "set the number of outputs", OFFSET(nb_outputs), AV_OPT_TYPE_INT, {.i64 = 1}, 1, INT_MAX, .flags=FLAGS }, \
  137. { NULL } \
  138. }
  139. static int request_frame(AVFilterLink *outlink);
  140. static av_cold int init(AVFilterContext *ctx)
  141. {
  142. SelectContext *select = ctx->priv;
  143. int i, ret;
  144. if ((ret = av_expr_parse(&select->expr, select->expr_str,
  145. var_names, NULL, NULL, NULL, NULL, 0, ctx)) < 0) {
  146. av_log(ctx, AV_LOG_ERROR, "Error while parsing expression '%s'\n",
  147. select->expr_str);
  148. return ret;
  149. }
  150. select->do_scene_detect = !!strstr(select->expr_str, "scene");
  151. for (i = 0; i < select->nb_outputs; i++) {
  152. AVFilterPad pad = { 0 };
  153. pad.name = av_asprintf("output%d", i);
  154. if (!pad.name)
  155. return AVERROR(ENOMEM);
  156. pad.type = ctx->filter->inputs[0].type;
  157. pad.request_frame = request_frame;
  158. if ((ret = ff_insert_outpad(ctx, i, &pad)) < 0) {
  159. av_freep(&pad.name);
  160. return ret;
  161. }
  162. }
  163. return 0;
  164. }
  165. #define INTERLACE_TYPE_P 0
  166. #define INTERLACE_TYPE_T 1
  167. #define INTERLACE_TYPE_B 2
  168. static int config_input(AVFilterLink *inlink)
  169. {
  170. SelectContext *select = inlink->dst->priv;
  171. select->var_values[VAR_N] = 0.0;
  172. select->var_values[VAR_SELECTED_N] = 0.0;
  173. select->var_values[VAR_TB] = av_q2d(inlink->time_base);
  174. select->var_values[VAR_PREV_PTS] = NAN;
  175. select->var_values[VAR_PREV_SELECTED_PTS] = NAN;
  176. select->var_values[VAR_PREV_SELECTED_T] = NAN;
  177. select->var_values[VAR_PREV_T] = NAN;
  178. select->var_values[VAR_START_PTS] = NAN;
  179. select->var_values[VAR_START_T] = NAN;
  180. select->var_values[VAR_I] = AV_PICTURE_TYPE_I;
  181. select->var_values[VAR_P] = AV_PICTURE_TYPE_P;
  182. select->var_values[VAR_B] = AV_PICTURE_TYPE_B;
  183. select->var_values[VAR_SI] = AV_PICTURE_TYPE_SI;
  184. select->var_values[VAR_SP] = AV_PICTURE_TYPE_SP;
  185. select->var_values[VAR_BI] = AV_PICTURE_TYPE_BI;
  186. select->var_values[VAR_PICT_TYPE_I] = AV_PICTURE_TYPE_I;
  187. select->var_values[VAR_PICT_TYPE_P] = AV_PICTURE_TYPE_P;
  188. select->var_values[VAR_PICT_TYPE_B] = AV_PICTURE_TYPE_B;
  189. select->var_values[VAR_PICT_TYPE_SI] = AV_PICTURE_TYPE_SI;
  190. select->var_values[VAR_PICT_TYPE_SP] = AV_PICTURE_TYPE_SP;
  191. select->var_values[VAR_PICT_TYPE_BI] = AV_PICTURE_TYPE_BI;
  192. select->var_values[VAR_INTERLACE_TYPE_P] = INTERLACE_TYPE_P;
  193. select->var_values[VAR_INTERLACE_TYPE_T] = INTERLACE_TYPE_T;
  194. select->var_values[VAR_INTERLACE_TYPE_B] = INTERLACE_TYPE_B;
  195. select->var_values[VAR_PICT_TYPE] = NAN;
  196. select->var_values[VAR_INTERLACE_TYPE] = NAN;
  197. select->var_values[VAR_SCENE] = NAN;
  198. select->var_values[VAR_CONSUMED_SAMPLES_N] = NAN;
  199. select->var_values[VAR_SAMPLES_N] = NAN;
  200. select->var_values[VAR_SAMPLE_RATE] =
  201. inlink->type == AVMEDIA_TYPE_AUDIO ? inlink->sample_rate : NAN;
  202. if (CONFIG_SELECT_FILTER && select->do_scene_detect) {
  203. select->sad = ff_scene_sad_get_fn(8);
  204. if (!select->sad)
  205. return AVERROR(EINVAL);
  206. }
  207. return 0;
  208. }
  209. static double get_scene_score(AVFilterContext *ctx, AVFrame *frame)
  210. {
  211. double ret = 0;
  212. SelectContext *select = ctx->priv;
  213. AVFrame *prev_picref = select->prev_picref;
  214. if (prev_picref &&
  215. frame->height == prev_picref->height &&
  216. frame->width == prev_picref->width) {
  217. uint64_t sad;
  218. double mafd, diff;
  219. select->sad(prev_picref->data[0], prev_picref->linesize[0], frame->data[0], frame->linesize[0], frame->width * 3, frame->height, &sad);
  220. emms_c();
  221. mafd = (double)sad / (frame->width * 3 * frame->height);
  222. diff = fabs(mafd - select->prev_mafd);
  223. ret = av_clipf(FFMIN(mafd, diff) / 100., 0, 1);
  224. select->prev_mafd = mafd;
  225. av_frame_free(&prev_picref);
  226. }
  227. select->prev_picref = av_frame_clone(frame);
  228. return ret;
  229. }
  230. static double get_concatdec_select(AVFrame *frame, int64_t pts)
  231. {
  232. AVDictionary *metadata = frame->metadata;
  233. AVDictionaryEntry *start_time_entry = av_dict_get(metadata, "lavf.concatdec.start_time", NULL, 0);
  234. AVDictionaryEntry *duration_entry = av_dict_get(metadata, "lavf.concatdec.duration", NULL, 0);
  235. if (start_time_entry) {
  236. int64_t start_time = strtoll(start_time_entry->value, NULL, 10);
  237. if (pts >= start_time) {
  238. if (duration_entry) {
  239. int64_t duration = strtoll(duration_entry->value, NULL, 10);
  240. if (pts < start_time + duration)
  241. return -1;
  242. else
  243. return 0;
  244. }
  245. return -1;
  246. }
  247. return 0;
  248. }
  249. return NAN;
  250. }
  251. #define D2TS(d) (isnan(d) ? AV_NOPTS_VALUE : (int64_t)(d))
  252. #define TS2D(ts) ((ts) == AV_NOPTS_VALUE ? NAN : (double)(ts))
  253. static void select_frame(AVFilterContext *ctx, AVFrame *frame)
  254. {
  255. SelectContext *select = ctx->priv;
  256. AVFilterLink *inlink = ctx->inputs[0];
  257. double res;
  258. if (isnan(select->var_values[VAR_START_PTS]))
  259. select->var_values[VAR_START_PTS] = TS2D(frame->pts);
  260. if (isnan(select->var_values[VAR_START_T]))
  261. select->var_values[VAR_START_T] = TS2D(frame->pts) * av_q2d(inlink->time_base);
  262. select->var_values[VAR_N ] = inlink->frame_count_out;
  263. select->var_values[VAR_PTS] = TS2D(frame->pts);
  264. select->var_values[VAR_T ] = TS2D(frame->pts) * av_q2d(inlink->time_base);
  265. select->var_values[VAR_POS] = frame->pkt_pos == -1 ? NAN : frame->pkt_pos;
  266. select->var_values[VAR_KEY] = frame->key_frame;
  267. select->var_values[VAR_CONCATDEC_SELECT] = get_concatdec_select(frame, av_rescale_q(frame->pts, inlink->time_base, AV_TIME_BASE_Q));
  268. switch (inlink->type) {
  269. case AVMEDIA_TYPE_AUDIO:
  270. select->var_values[VAR_SAMPLES_N] = frame->nb_samples;
  271. break;
  272. case AVMEDIA_TYPE_VIDEO:
  273. select->var_values[VAR_INTERLACE_TYPE] =
  274. !frame->interlaced_frame ? INTERLACE_TYPE_P :
  275. frame->top_field_first ? INTERLACE_TYPE_T : INTERLACE_TYPE_B;
  276. select->var_values[VAR_PICT_TYPE] = frame->pict_type;
  277. if (select->do_scene_detect) {
  278. char buf[32];
  279. select->var_values[VAR_SCENE] = get_scene_score(ctx, frame);
  280. // TODO: document metadata
  281. snprintf(buf, sizeof(buf), "%f", select->var_values[VAR_SCENE]);
  282. av_dict_set(&frame->metadata, "lavfi.scene_score", buf, 0);
  283. }
  284. break;
  285. }
  286. select->select = res = av_expr_eval(select->expr, select->var_values, NULL);
  287. av_log(inlink->dst, AV_LOG_DEBUG,
  288. "n:%f pts:%f t:%f key:%d",
  289. select->var_values[VAR_N],
  290. select->var_values[VAR_PTS],
  291. select->var_values[VAR_T],
  292. frame->key_frame);
  293. switch (inlink->type) {
  294. case AVMEDIA_TYPE_VIDEO:
  295. av_log(inlink->dst, AV_LOG_DEBUG, " interlace_type:%c pict_type:%c scene:%f",
  296. (!frame->interlaced_frame) ? 'P' :
  297. frame->top_field_first ? 'T' : 'B',
  298. av_get_picture_type_char(frame->pict_type),
  299. select->var_values[VAR_SCENE]);
  300. break;
  301. case AVMEDIA_TYPE_AUDIO:
  302. av_log(inlink->dst, AV_LOG_DEBUG, " samples_n:%d consumed_samples_n:%f",
  303. frame->nb_samples,
  304. select->var_values[VAR_CONSUMED_SAMPLES_N]);
  305. break;
  306. }
  307. if (res == 0) {
  308. select->select_out = -1; /* drop */
  309. } else if (isnan(res) || res < 0) {
  310. select->select_out = 0; /* first output */
  311. } else {
  312. select->select_out = FFMIN(ceilf(res)-1, select->nb_outputs-1); /* other outputs */
  313. }
  314. av_log(inlink->dst, AV_LOG_DEBUG, " -> select:%f select_out:%d\n", res, select->select_out);
  315. if (res) {
  316. select->var_values[VAR_PREV_SELECTED_N] = select->var_values[VAR_N];
  317. select->var_values[VAR_PREV_SELECTED_PTS] = select->var_values[VAR_PTS];
  318. select->var_values[VAR_PREV_SELECTED_T] = select->var_values[VAR_T];
  319. select->var_values[VAR_SELECTED_N] += 1.0;
  320. if (inlink->type == AVMEDIA_TYPE_AUDIO)
  321. select->var_values[VAR_CONSUMED_SAMPLES_N] += frame->nb_samples;
  322. }
  323. select->var_values[VAR_PREV_PTS] = select->var_values[VAR_PTS];
  324. select->var_values[VAR_PREV_T] = select->var_values[VAR_T];
  325. }
  326. static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
  327. {
  328. AVFilterContext *ctx = inlink->dst;
  329. SelectContext *select = ctx->priv;
  330. select_frame(ctx, frame);
  331. if (select->select)
  332. return ff_filter_frame(ctx->outputs[select->select_out], frame);
  333. av_frame_free(&frame);
  334. return 0;
  335. }
  336. static int request_frame(AVFilterLink *outlink)
  337. {
  338. AVFilterLink *inlink = outlink->src->inputs[0];
  339. int ret = ff_request_frame(inlink);
  340. return ret;
  341. }
  342. static av_cold void uninit(AVFilterContext *ctx)
  343. {
  344. SelectContext *select = ctx->priv;
  345. int i;
  346. av_expr_free(select->expr);
  347. select->expr = NULL;
  348. for (i = 0; i < ctx->nb_outputs; i++)
  349. av_freep(&ctx->output_pads[i].name);
  350. if (select->do_scene_detect) {
  351. av_frame_free(&select->prev_picref);
  352. }
  353. }
  354. #if CONFIG_ASELECT_FILTER
  355. DEFINE_OPTIONS(aselect, AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM);
  356. AVFILTER_DEFINE_CLASS(aselect);
  357. static av_cold int aselect_init(AVFilterContext *ctx)
  358. {
  359. SelectContext *select = ctx->priv;
  360. int ret;
  361. if ((ret = init(ctx)) < 0)
  362. return ret;
  363. if (select->do_scene_detect) {
  364. av_log(ctx, AV_LOG_ERROR, "Scene detection is ignored in aselect filter\n");
  365. return AVERROR(EINVAL);
  366. }
  367. return 0;
  368. }
  369. static const AVFilterPad avfilter_af_aselect_inputs[] = {
  370. {
  371. .name = "default",
  372. .type = AVMEDIA_TYPE_AUDIO,
  373. .config_props = config_input,
  374. .filter_frame = filter_frame,
  375. },
  376. { NULL }
  377. };
  378. AVFilter ff_af_aselect = {
  379. .name = "aselect",
  380. .description = NULL_IF_CONFIG_SMALL("Select audio frames to pass in output."),
  381. .init = aselect_init,
  382. .uninit = uninit,
  383. .priv_size = sizeof(SelectContext),
  384. .inputs = avfilter_af_aselect_inputs,
  385. .priv_class = &aselect_class,
  386. .flags = AVFILTER_FLAG_DYNAMIC_OUTPUTS,
  387. };
  388. #endif /* CONFIG_ASELECT_FILTER */
  389. #if CONFIG_SELECT_FILTER
  390. static int query_formats(AVFilterContext *ctx)
  391. {
  392. SelectContext *select = ctx->priv;
  393. if (!select->do_scene_detect) {
  394. return ff_default_query_formats(ctx);
  395. } else {
  396. int ret;
  397. static const enum AVPixelFormat pix_fmts[] = {
  398. AV_PIX_FMT_RGB24, AV_PIX_FMT_BGR24,
  399. AV_PIX_FMT_NONE
  400. };
  401. AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
  402. if (!fmts_list)
  403. return AVERROR(ENOMEM);
  404. ret = ff_set_common_formats(ctx, fmts_list);
  405. if (ret < 0)
  406. return ret;
  407. }
  408. return 0;
  409. }
  410. DEFINE_OPTIONS(select, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM);
  411. AVFILTER_DEFINE_CLASS(select);
  412. static av_cold int select_init(AVFilterContext *ctx)
  413. {
  414. int ret;
  415. if ((ret = init(ctx)) < 0)
  416. return ret;
  417. return 0;
  418. }
  419. static const AVFilterPad avfilter_vf_select_inputs[] = {
  420. {
  421. .name = "default",
  422. .type = AVMEDIA_TYPE_VIDEO,
  423. .config_props = config_input,
  424. .filter_frame = filter_frame,
  425. },
  426. { NULL }
  427. };
  428. AVFilter ff_vf_select = {
  429. .name = "select",
  430. .description = NULL_IF_CONFIG_SMALL("Select video frames to pass in output."),
  431. .init = select_init,
  432. .uninit = uninit,
  433. .query_formats = query_formats,
  434. .priv_size = sizeof(SelectContext),
  435. .priv_class = &select_class,
  436. .inputs = avfilter_vf_select_inputs,
  437. .flags = AVFILTER_FLAG_DYNAMIC_OUTPUTS,
  438. };
  439. #endif /* CONFIG_SELECT_FILTER */