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.

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