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.

536 lines
17KB

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