You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

554 lines
18KB

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