f_select.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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 "libavutil/pixelutils.h"
  30. #include "avfilter.h"
  31. #include "audio.h"
  32. #include "formats.h"
  33. #include "internal.h"
  34. #include "video.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. av_pixelutils_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. ff_insert_outpad(ctx, i, &pad);
  159. }
  160. return 0;
  161. }
  162. #define INTERLACE_TYPE_P 0
  163. #define INTERLACE_TYPE_T 1
  164. #define INTERLACE_TYPE_B 2
  165. static int config_input(AVFilterLink *inlink)
  166. {
  167. SelectContext *select = inlink->dst->priv;
  168. select->var_values[VAR_N] = 0.0;
  169. select->var_values[VAR_SELECTED_N] = 0.0;
  170. select->var_values[VAR_TB] = av_q2d(inlink->time_base);
  171. select->var_values[VAR_PREV_PTS] = NAN;
  172. select->var_values[VAR_PREV_SELECTED_PTS] = NAN;
  173. select->var_values[VAR_PREV_SELECTED_T] = NAN;
  174. select->var_values[VAR_PREV_T] = NAN;
  175. select->var_values[VAR_START_PTS] = NAN;
  176. select->var_values[VAR_START_T] = NAN;
  177. select->var_values[VAR_I] = AV_PICTURE_TYPE_I;
  178. select->var_values[VAR_P] = AV_PICTURE_TYPE_P;
  179. select->var_values[VAR_B] = AV_PICTURE_TYPE_B;
  180. select->var_values[VAR_SI] = AV_PICTURE_TYPE_SI;
  181. select->var_values[VAR_SP] = AV_PICTURE_TYPE_SP;
  182. select->var_values[VAR_BI] = AV_PICTURE_TYPE_BI;
  183. select->var_values[VAR_PICT_TYPE_I] = AV_PICTURE_TYPE_I;
  184. select->var_values[VAR_PICT_TYPE_P] = AV_PICTURE_TYPE_P;
  185. select->var_values[VAR_PICT_TYPE_B] = AV_PICTURE_TYPE_B;
  186. select->var_values[VAR_PICT_TYPE_SI] = AV_PICTURE_TYPE_SI;
  187. select->var_values[VAR_PICT_TYPE_SP] = AV_PICTURE_TYPE_SP;
  188. select->var_values[VAR_PICT_TYPE_BI] = AV_PICTURE_TYPE_BI;
  189. select->var_values[VAR_INTERLACE_TYPE_P] = INTERLACE_TYPE_P;
  190. select->var_values[VAR_INTERLACE_TYPE_T] = INTERLACE_TYPE_T;
  191. select->var_values[VAR_INTERLACE_TYPE_B] = INTERLACE_TYPE_B;
  192. select->var_values[VAR_PICT_TYPE] = NAN;
  193. select->var_values[VAR_INTERLACE_TYPE] = NAN;
  194. select->var_values[VAR_SCENE] = NAN;
  195. select->var_values[VAR_CONSUMED_SAMPLES_N] = NAN;
  196. select->var_values[VAR_SAMPLES_N] = NAN;
  197. select->var_values[VAR_SAMPLE_RATE] =
  198. inlink->type == AVMEDIA_TYPE_AUDIO ? inlink->sample_rate : NAN;
  199. if (select->do_scene_detect) {
  200. select->sad = av_pixelutils_get_sad_fn(3, 3, 2, select); // 8x8 both sources aligned
  201. if (!select->sad)
  202. return AVERROR(EINVAL);
  203. }
  204. return 0;
  205. }
  206. static double get_scene_score(AVFilterContext *ctx, AVFrame *frame)
  207. {
  208. double ret = 0;
  209. SelectContext *select = ctx->priv;
  210. AVFrame *prev_picref = select->prev_picref;
  211. if (prev_picref &&
  212. frame->height == prev_picref->height &&
  213. frame->width == prev_picref->width) {
  214. int x, y, nb_sad = 0;
  215. int64_t sad = 0;
  216. double mafd, diff;
  217. uint8_t *p1 = frame->data[0];
  218. uint8_t *p2 = prev_picref->data[0];
  219. const int p1_linesize = frame->linesize[0];
  220. const int p2_linesize = prev_picref->linesize[0];
  221. for (y = 0; y < frame->height - 7; y += 8) {
  222. for (x = 0; x < frame->width*3 - 7; x += 8) {
  223. sad += select->sad(p1 + x, p1_linesize, p2 + x, p2_linesize);
  224. nb_sad += 8 * 8;
  225. }
  226. p1 += 8 * p1_linesize;
  227. p2 += 8 * p2_linesize;
  228. }
  229. emms_c();
  230. mafd = nb_sad ? (double)sad / nb_sad : 0;
  231. diff = fabs(mafd - select->prev_mafd);
  232. ret = av_clipf(FFMIN(mafd, diff) / 100., 0, 1);
  233. select->prev_mafd = mafd;
  234. av_frame_free(&prev_picref);
  235. }
  236. select->prev_picref = av_frame_clone(frame);
  237. return ret;
  238. }
  239. static double get_concatdec_select(AVFrame *frame, int64_t pts)
  240. {
  241. AVDictionary *metadata = av_frame_get_metadata(frame);
  242. AVDictionaryEntry *start_time_entry = av_dict_get(metadata, "lavf.concatdec.start_time", NULL, 0);
  243. AVDictionaryEntry *duration_entry = av_dict_get(metadata, "lavf.concatdec.duration", NULL, 0);
  244. if (start_time_entry) {
  245. int64_t start_time = strtoll(start_time_entry->value, NULL, 10);
  246. if (pts >= start_time) {
  247. if (duration_entry) {
  248. int64_t duration = strtoll(duration_entry->value, NULL, 10);
  249. if (pts < start_time + duration)
  250. return -1;
  251. else
  252. return 0;
  253. }
  254. return -1;
  255. }
  256. return 0;
  257. }
  258. return NAN;
  259. }
  260. #define D2TS(d) (isnan(d) ? AV_NOPTS_VALUE : (int64_t)(d))
  261. #define TS2D(ts) ((ts) == AV_NOPTS_VALUE ? NAN : (double)(ts))
  262. static void select_frame(AVFilterContext *ctx, AVFrame *frame)
  263. {
  264. SelectContext *select = ctx->priv;
  265. AVFilterLink *inlink = ctx->inputs[0];
  266. double res;
  267. if (isnan(select->var_values[VAR_START_PTS]))
  268. select->var_values[VAR_START_PTS] = TS2D(frame->pts);
  269. if (isnan(select->var_values[VAR_START_T]))
  270. select->var_values[VAR_START_T] = TS2D(frame->pts) * av_q2d(inlink->time_base);
  271. select->var_values[VAR_N ] = inlink->frame_count;
  272. select->var_values[VAR_PTS] = TS2D(frame->pts);
  273. select->var_values[VAR_T ] = TS2D(frame->pts) * av_q2d(inlink->time_base);
  274. select->var_values[VAR_POS] = av_frame_get_pkt_pos(frame) == -1 ? NAN : av_frame_get_pkt_pos(frame);
  275. select->var_values[VAR_KEY] = frame->key_frame;
  276. select->var_values[VAR_CONCATDEC_SELECT] = get_concatdec_select(frame, av_rescale_q(frame->pts, inlink->time_base, AV_TIME_BASE_Q));
  277. switch (inlink->type) {
  278. case AVMEDIA_TYPE_AUDIO:
  279. select->var_values[VAR_SAMPLES_N] = frame->nb_samples;
  280. break;
  281. case AVMEDIA_TYPE_VIDEO:
  282. select->var_values[VAR_INTERLACE_TYPE] =
  283. !frame->interlaced_frame ? INTERLACE_TYPE_P :
  284. frame->top_field_first ? INTERLACE_TYPE_T : INTERLACE_TYPE_B;
  285. select->var_values[VAR_PICT_TYPE] = frame->pict_type;
  286. if (select->do_scene_detect) {
  287. char buf[32];
  288. select->var_values[VAR_SCENE] = get_scene_score(ctx, frame);
  289. // TODO: document metadata
  290. snprintf(buf, sizeof(buf), "%f", select->var_values[VAR_SCENE]);
  291. av_dict_set(avpriv_frame_get_metadatap(frame), "lavfi.scene_score", buf, 0);
  292. }
  293. break;
  294. }
  295. select->select = res = av_expr_eval(select->expr, select->var_values, NULL);
  296. av_log(inlink->dst, AV_LOG_DEBUG,
  297. "n:%f pts:%f t:%f key:%d",
  298. select->var_values[VAR_N],
  299. select->var_values[VAR_PTS],
  300. select->var_values[VAR_T],
  301. frame->key_frame);
  302. switch (inlink->type) {
  303. case AVMEDIA_TYPE_VIDEO:
  304. av_log(inlink->dst, AV_LOG_DEBUG, " interlace_type:%c pict_type:%c scene:%f",
  305. (!frame->interlaced_frame) ? 'P' :
  306. frame->top_field_first ? 'T' : 'B',
  307. av_get_picture_type_char(frame->pict_type),
  308. select->var_values[VAR_SCENE]);
  309. break;
  310. case AVMEDIA_TYPE_AUDIO:
  311. av_log(inlink->dst, AV_LOG_DEBUG, " samples_n:%d consumed_samples_n:%f",
  312. frame->nb_samples,
  313. select->var_values[VAR_CONSUMED_SAMPLES_N]);
  314. break;
  315. }
  316. if (res == 0) {
  317. select->select_out = -1; /* drop */
  318. } else if (isnan(res) || res < 0) {
  319. select->select_out = 0; /* first output */
  320. } else {
  321. select->select_out = FFMIN(ceilf(res)-1, select->nb_outputs-1); /* other outputs */
  322. }
  323. av_log(inlink->dst, AV_LOG_DEBUG, " -> select:%f select_out:%d\n", res, select->select_out);
  324. if (res) {
  325. select->var_values[VAR_PREV_SELECTED_N] = select->var_values[VAR_N];
  326. select->var_values[VAR_PREV_SELECTED_PTS] = select->var_values[VAR_PTS];
  327. select->var_values[VAR_PREV_SELECTED_T] = select->var_values[VAR_T];
  328. select->var_values[VAR_SELECTED_N] += 1.0;
  329. if (inlink->type == AVMEDIA_TYPE_AUDIO)
  330. select->var_values[VAR_CONSUMED_SAMPLES_N] += frame->nb_samples;
  331. }
  332. select->var_values[VAR_PREV_PTS] = select->var_values[VAR_PTS];
  333. select->var_values[VAR_PREV_T] = select->var_values[VAR_T];
  334. }
  335. static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
  336. {
  337. AVFilterContext *ctx = inlink->dst;
  338. SelectContext *select = ctx->priv;
  339. select_frame(ctx, frame);
  340. if (select->select)
  341. return ff_filter_frame(ctx->outputs[select->select_out], frame);
  342. av_frame_free(&frame);
  343. return 0;
  344. }
  345. static int request_frame(AVFilterLink *outlink)
  346. {
  347. AVFilterLink *inlink = outlink->src->inputs[0];
  348. int ret = ff_request_frame(inlink);
  349. return ret;
  350. }
  351. static av_cold void uninit(AVFilterContext *ctx)
  352. {
  353. SelectContext *select = ctx->priv;
  354. int i;
  355. av_expr_free(select->expr);
  356. select->expr = NULL;
  357. for (i = 0; i < ctx->nb_outputs; i++)
  358. av_freep(&ctx->output_pads[i].name);
  359. if (select->do_scene_detect) {
  360. av_frame_free(&select->prev_picref);
  361. }
  362. }
  363. static int query_formats(AVFilterContext *ctx)
  364. {
  365. SelectContext *select = ctx->priv;
  366. if (!select->do_scene_detect) {
  367. return ff_default_query_formats(ctx);
  368. } else {
  369. int ret;
  370. static const enum AVPixelFormat pix_fmts[] = {
  371. AV_PIX_FMT_RGB24, AV_PIX_FMT_BGR24,
  372. AV_PIX_FMT_NONE
  373. };
  374. AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
  375. if (!fmts_list)
  376. return AVERROR(ENOMEM);
  377. ret = ff_set_common_formats(ctx, fmts_list);
  378. if (ret < 0)
  379. return ret;
  380. }
  381. return 0;
  382. }
  383. #if CONFIG_ASELECT_FILTER
  384. DEFINE_OPTIONS(aselect, AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM);
  385. AVFILTER_DEFINE_CLASS(aselect);
  386. static av_cold int aselect_init(AVFilterContext *ctx)
  387. {
  388. SelectContext *select = ctx->priv;
  389. int ret;
  390. if ((ret = init(ctx)) < 0)
  391. return ret;
  392. if (select->do_scene_detect) {
  393. av_log(ctx, AV_LOG_ERROR, "Scene detection is ignored in aselect filter\n");
  394. return AVERROR(EINVAL);
  395. }
  396. return 0;
  397. }
  398. static const AVFilterPad avfilter_af_aselect_inputs[] = {
  399. {
  400. .name = "default",
  401. .type = AVMEDIA_TYPE_AUDIO,
  402. .config_props = config_input,
  403. .filter_frame = filter_frame,
  404. },
  405. { NULL }
  406. };
  407. AVFilter ff_af_aselect = {
  408. .name = "aselect",
  409. .description = NULL_IF_CONFIG_SMALL("Select audio frames to pass in output."),
  410. .init = aselect_init,
  411. .uninit = uninit,
  412. .priv_size = sizeof(SelectContext),
  413. .inputs = avfilter_af_aselect_inputs,
  414. .priv_class = &aselect_class,
  415. .flags = AVFILTER_FLAG_DYNAMIC_OUTPUTS,
  416. };
  417. #endif /* CONFIG_ASELECT_FILTER */
  418. #if CONFIG_SELECT_FILTER
  419. DEFINE_OPTIONS(select, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM);
  420. AVFILTER_DEFINE_CLASS(select);
  421. static av_cold int select_init(AVFilterContext *ctx)
  422. {
  423. int ret;
  424. if ((ret = init(ctx)) < 0)
  425. return ret;
  426. return 0;
  427. }
  428. static const AVFilterPad avfilter_vf_select_inputs[] = {
  429. {
  430. .name = "default",
  431. .type = AVMEDIA_TYPE_VIDEO,
  432. .config_props = config_input,
  433. .filter_frame = filter_frame,
  434. },
  435. { NULL }
  436. };
  437. AVFilter ff_vf_select = {
  438. .name = "select",
  439. .description = NULL_IF_CONFIG_SMALL("Select video frames to pass in output."),
  440. .init = select_init,
  441. .uninit = uninit,
  442. .query_formats = query_formats,
  443. .priv_size = sizeof(SelectContext),
  444. .priv_class = &select_class,
  445. .inputs = avfilter_vf_select_inputs,
  446. .flags = AVFILTER_FLAG_DYNAMIC_OUTPUTS,
  447. };
  448. #endif /* CONFIG_SELECT_FILTER */