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.

484 lines
16KB

  1. /*
  2. * Copyright (c) 2011 Roger Pau Monné <roger.pau@entel.upc.edu>
  3. * Copyright (c) 2011 Stefano Sabatini
  4. * Copyright (c) 2013 Paul B Mahol
  5. *
  6. * This file is part of FFmpeg.
  7. *
  8. * FFmpeg is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * FFmpeg is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public
  19. * License along with FFmpeg; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. /**
  23. * @file
  24. * Caculate the PSNR between two input videos.
  25. */
  26. #include "libavutil/avstring.h"
  27. #include "libavutil/opt.h"
  28. #include "libavutil/pixdesc.h"
  29. #include "avfilter.h"
  30. #include "drawutils.h"
  31. #include "formats.h"
  32. #include "framesync.h"
  33. #include "internal.h"
  34. #include "psnr.h"
  35. #include "video.h"
  36. typedef struct PSNRContext {
  37. const AVClass *class;
  38. FFFrameSync fs;
  39. double mse, min_mse, max_mse, mse_comp[4];
  40. uint64_t nb_frames;
  41. FILE *stats_file;
  42. char *stats_file_str;
  43. int stats_version;
  44. int stats_header_written;
  45. int stats_add_max;
  46. int max[4], average_max;
  47. int is_rgb;
  48. uint8_t rgba_map[4];
  49. char comps[4];
  50. int nb_components;
  51. int nb_threads;
  52. int planewidth[4];
  53. int planeheight[4];
  54. double planeweight[4];
  55. uint64_t **score;
  56. PSNRDSPContext dsp;
  57. } PSNRContext;
  58. #define OFFSET(x) offsetof(PSNRContext, x)
  59. #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
  60. static const AVOption psnr_options[] = {
  61. {"stats_file", "Set file where to store per-frame difference information", OFFSET(stats_file_str), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, FLAGS },
  62. {"f", "Set file where to store per-frame difference information", OFFSET(stats_file_str), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, FLAGS },
  63. {"stats_version", "Set the format version for the stats file.", OFFSET(stats_version), AV_OPT_TYPE_INT, {.i64=1}, 1, 2, FLAGS },
  64. {"output_max", "Add raw stats (max values) to the output log.", OFFSET(stats_add_max), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS},
  65. { NULL }
  66. };
  67. FRAMESYNC_DEFINE_CLASS(psnr, PSNRContext, fs);
  68. static inline unsigned pow_2(unsigned base)
  69. {
  70. return base*base;
  71. }
  72. static inline double get_psnr(double mse, uint64_t nb_frames, int max)
  73. {
  74. return 10.0 * log10(pow_2(max) / (mse / nb_frames));
  75. }
  76. static uint64_t sse_line_8bit(const uint8_t *main_line, const uint8_t *ref_line, int outw)
  77. {
  78. int j;
  79. unsigned m2 = 0;
  80. for (j = 0; j < outw; j++)
  81. m2 += pow_2(main_line[j] - ref_line[j]);
  82. return m2;
  83. }
  84. static uint64_t sse_line_16bit(const uint8_t *_main_line, const uint8_t *_ref_line, int outw)
  85. {
  86. int j;
  87. uint64_t m2 = 0;
  88. const uint16_t *main_line = (const uint16_t *) _main_line;
  89. const uint16_t *ref_line = (const uint16_t *) _ref_line;
  90. for (j = 0; j < outw; j++)
  91. m2 += pow_2(main_line[j] - ref_line[j]);
  92. return m2;
  93. }
  94. typedef struct ThreadData {
  95. const uint8_t *main_data[4];
  96. const uint8_t *ref_data[4];
  97. int main_linesize[4];
  98. int ref_linesize[4];
  99. int planewidth[4];
  100. int planeheight[4];
  101. uint64_t **score;
  102. int nb_components;
  103. PSNRDSPContext *dsp;
  104. } ThreadData;
  105. static
  106. int compute_images_mse(AVFilterContext *ctx, void *arg,
  107. int jobnr, int nb_jobs)
  108. {
  109. ThreadData *td = arg;
  110. uint64_t *score = td->score[jobnr];
  111. for (int c = 0; c < td->nb_components; c++) {
  112. const int outw = td->planewidth[c];
  113. const int outh = td->planeheight[c];
  114. const int slice_start = (outh * jobnr) / nb_jobs;
  115. const int slice_end = (outh * (jobnr+1)) / nb_jobs;
  116. const int ref_linesize = td->ref_linesize[c];
  117. const int main_linesize = td->main_linesize[c];
  118. const uint8_t *main_line = td->main_data[c] + main_linesize * slice_start;
  119. const uint8_t *ref_line = td->ref_data[c] + ref_linesize * slice_start;
  120. uint64_t m = 0;
  121. for (int i = slice_start; i < slice_end; i++) {
  122. m += td->dsp->sse_line(main_line, ref_line, outw);
  123. ref_line += ref_linesize;
  124. main_line += main_linesize;
  125. }
  126. score[c] = m;
  127. }
  128. return 0;
  129. }
  130. static void set_meta(AVDictionary **metadata, const char *key, char comp, float d)
  131. {
  132. char value[128];
  133. snprintf(value, sizeof(value), "%f", d);
  134. if (comp) {
  135. char key2[128];
  136. snprintf(key2, sizeof(key2), "%s%c", key, comp);
  137. av_dict_set(metadata, key2, value, 0);
  138. } else {
  139. av_dict_set(metadata, key, value, 0);
  140. }
  141. }
  142. static int do_psnr(FFFrameSync *fs)
  143. {
  144. AVFilterContext *ctx = fs->parent;
  145. PSNRContext *s = ctx->priv;
  146. AVFrame *master, *ref;
  147. double comp_mse[4], mse = 0.;
  148. uint64_t comp_sum[4] = { 0 };
  149. AVDictionary **metadata;
  150. ThreadData td;
  151. int ret;
  152. ret = ff_framesync_dualinput_get(fs, &master, &ref);
  153. if (ret < 0)
  154. return ret;
  155. if (ctx->is_disabled || !ref)
  156. return ff_filter_frame(ctx->outputs[0], master);
  157. metadata = &master->metadata;
  158. td.nb_components = s->nb_components;
  159. td.dsp = &s->dsp;
  160. td.score = s->score;
  161. for (int c = 0; c < s->nb_components; c++) {
  162. td.main_data[c] = master->data[c];
  163. td.ref_data[c] = ref->data[c];
  164. td.main_linesize[c] = master->linesize[c];
  165. td.ref_linesize[c] = ref->linesize[c];
  166. td.planewidth[c] = s->planewidth[c];
  167. td.planeheight[c] = s->planeheight[c];
  168. }
  169. ctx->internal->execute(ctx, compute_images_mse, &td, NULL, FFMIN(s->planeheight[1], s->nb_threads));
  170. for (int j = 0; j < s->nb_threads; j++) {
  171. for (int c = 0; c < s->nb_components; c++)
  172. comp_sum[c] += s->score[j][c];
  173. }
  174. for (int c = 0; c < s->nb_components; c++)
  175. comp_mse[c] = comp_sum[c] / ((double)s->planewidth[c] * s->planeheight[c]);
  176. for (int c = 0; c < s->nb_components; c++)
  177. mse += comp_mse[c] * s->planeweight[c];
  178. s->min_mse = FFMIN(s->min_mse, mse);
  179. s->max_mse = FFMAX(s->max_mse, mse);
  180. s->mse += mse;
  181. for (int j = 0; j < s->nb_components; j++)
  182. s->mse_comp[j] += comp_mse[j];
  183. s->nb_frames++;
  184. for (int j = 0; j < s->nb_components; j++) {
  185. int c = s->is_rgb ? s->rgba_map[j] : j;
  186. set_meta(metadata, "lavfi.psnr.mse.", s->comps[j], comp_mse[c]);
  187. set_meta(metadata, "lavfi.psnr.psnr.", s->comps[j], get_psnr(comp_mse[c], 1, s->max[c]));
  188. }
  189. set_meta(metadata, "lavfi.psnr.mse_avg", 0, mse);
  190. set_meta(metadata, "lavfi.psnr.psnr_avg", 0, get_psnr(mse, 1, s->average_max));
  191. if (s->stats_file) {
  192. if (s->stats_version == 2 && !s->stats_header_written) {
  193. fprintf(s->stats_file, "psnr_log_version:2 fields:n");
  194. fprintf(s->stats_file, ",mse_avg");
  195. for (int j = 0; j < s->nb_components; j++) {
  196. fprintf(s->stats_file, ",mse_%c", s->comps[j]);
  197. }
  198. fprintf(s->stats_file, ",psnr_avg");
  199. for (int j = 0; j < s->nb_components; j++) {
  200. fprintf(s->stats_file, ",psnr_%c", s->comps[j]);
  201. }
  202. if (s->stats_add_max) {
  203. fprintf(s->stats_file, ",max_avg");
  204. for (int j = 0; j < s->nb_components; j++) {
  205. fprintf(s->stats_file, ",max_%c", s->comps[j]);
  206. }
  207. }
  208. fprintf(s->stats_file, "\n");
  209. s->stats_header_written = 1;
  210. }
  211. fprintf(s->stats_file, "n:%"PRId64" mse_avg:%0.2f ", s->nb_frames, mse);
  212. for (int j = 0; j < s->nb_components; j++) {
  213. int c = s->is_rgb ? s->rgba_map[j] : j;
  214. fprintf(s->stats_file, "mse_%c:%0.2f ", s->comps[j], comp_mse[c]);
  215. }
  216. fprintf(s->stats_file, "psnr_avg:%0.2f ", get_psnr(mse, 1, s->average_max));
  217. for (int j = 0; j < s->nb_components; j++) {
  218. int c = s->is_rgb ? s->rgba_map[j] : j;
  219. fprintf(s->stats_file, "psnr_%c:%0.2f ", s->comps[j],
  220. get_psnr(comp_mse[c], 1, s->max[c]));
  221. }
  222. if (s->stats_version == 2 && s->stats_add_max) {
  223. fprintf(s->stats_file, "max_avg:%d ", s->average_max);
  224. for (int j = 0; j < s->nb_components; j++) {
  225. int c = s->is_rgb ? s->rgba_map[j] : j;
  226. fprintf(s->stats_file, "max_%c:%d ", s->comps[j], s->max[c]);
  227. }
  228. }
  229. fprintf(s->stats_file, "\n");
  230. }
  231. return ff_filter_frame(ctx->outputs[0], master);
  232. }
  233. static av_cold int init(AVFilterContext *ctx)
  234. {
  235. PSNRContext *s = ctx->priv;
  236. s->min_mse = +INFINITY;
  237. s->max_mse = -INFINITY;
  238. if (s->stats_file_str) {
  239. if (s->stats_version < 2 && s->stats_add_max) {
  240. av_log(ctx, AV_LOG_ERROR,
  241. "stats_add_max was specified but stats_version < 2.\n" );
  242. return AVERROR(EINVAL);
  243. }
  244. if (!strcmp(s->stats_file_str, "-")) {
  245. s->stats_file = stdout;
  246. } else {
  247. s->stats_file = fopen(s->stats_file_str, "w");
  248. if (!s->stats_file) {
  249. int err = AVERROR(errno);
  250. char buf[128];
  251. av_strerror(err, buf, sizeof(buf));
  252. av_log(ctx, AV_LOG_ERROR, "Could not open stats file %s: %s\n",
  253. s->stats_file_str, buf);
  254. return err;
  255. }
  256. }
  257. }
  258. s->fs.on_event = do_psnr;
  259. return 0;
  260. }
  261. static int query_formats(AVFilterContext *ctx)
  262. {
  263. static const enum AVPixelFormat pix_fmts[] = {
  264. AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY9, AV_PIX_FMT_GRAY10, AV_PIX_FMT_GRAY12, AV_PIX_FMT_GRAY14, AV_PIX_FMT_GRAY16,
  265. #define PF_NOALPHA(suf) AV_PIX_FMT_YUV420##suf, AV_PIX_FMT_YUV422##suf, AV_PIX_FMT_YUV444##suf
  266. #define PF_ALPHA(suf) AV_PIX_FMT_YUVA420##suf, AV_PIX_FMT_YUVA422##suf, AV_PIX_FMT_YUVA444##suf
  267. #define PF(suf) PF_NOALPHA(suf), PF_ALPHA(suf)
  268. PF(P), PF(P9), PF(P10), PF_NOALPHA(P12), PF_NOALPHA(P14), PF(P16),
  269. AV_PIX_FMT_YUV440P, AV_PIX_FMT_YUV411P, AV_PIX_FMT_YUV410P,
  270. AV_PIX_FMT_YUVJ411P, AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P,
  271. AV_PIX_FMT_YUVJ440P, AV_PIX_FMT_YUVJ444P,
  272. AV_PIX_FMT_GBRP, AV_PIX_FMT_GBRP9, AV_PIX_FMT_GBRP10,
  273. AV_PIX_FMT_GBRP12, AV_PIX_FMT_GBRP14, AV_PIX_FMT_GBRP16,
  274. AV_PIX_FMT_GBRAP, AV_PIX_FMT_GBRAP10, AV_PIX_FMT_GBRAP12, AV_PIX_FMT_GBRAP16,
  275. AV_PIX_FMT_NONE
  276. };
  277. AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
  278. if (!fmts_list)
  279. return AVERROR(ENOMEM);
  280. return ff_set_common_formats(ctx, fmts_list);
  281. }
  282. static int config_input_ref(AVFilterLink *inlink)
  283. {
  284. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
  285. AVFilterContext *ctx = inlink->dst;
  286. PSNRContext *s = ctx->priv;
  287. double average_max;
  288. unsigned sum;
  289. int j;
  290. s->nb_threads = ff_filter_get_nb_threads(ctx);
  291. s->nb_components = desc->nb_components;
  292. if (ctx->inputs[0]->w != ctx->inputs[1]->w ||
  293. ctx->inputs[0]->h != ctx->inputs[1]->h) {
  294. av_log(ctx, AV_LOG_ERROR, "Width and height of input videos must be same.\n");
  295. return AVERROR(EINVAL);
  296. }
  297. if (ctx->inputs[0]->format != ctx->inputs[1]->format) {
  298. av_log(ctx, AV_LOG_ERROR, "Inputs must be of same pixel format.\n");
  299. return AVERROR(EINVAL);
  300. }
  301. s->max[0] = (1 << desc->comp[0].depth) - 1;
  302. s->max[1] = (1 << desc->comp[1].depth) - 1;
  303. s->max[2] = (1 << desc->comp[2].depth) - 1;
  304. s->max[3] = (1 << desc->comp[3].depth) - 1;
  305. s->is_rgb = ff_fill_rgba_map(s->rgba_map, inlink->format) >= 0;
  306. s->comps[0] = s->is_rgb ? 'r' : 'y' ;
  307. s->comps[1] = s->is_rgb ? 'g' : 'u' ;
  308. s->comps[2] = s->is_rgb ? 'b' : 'v' ;
  309. s->comps[3] = 'a';
  310. s->planeheight[1] = s->planeheight[2] = AV_CEIL_RSHIFT(inlink->h, desc->log2_chroma_h);
  311. s->planeheight[0] = s->planeheight[3] = inlink->h;
  312. s->planewidth[1] = s->planewidth[2] = AV_CEIL_RSHIFT(inlink->w, desc->log2_chroma_w);
  313. s->planewidth[0] = s->planewidth[3] = inlink->w;
  314. sum = 0;
  315. for (j = 0; j < s->nb_components; j++)
  316. sum += s->planeheight[j] * s->planewidth[j];
  317. average_max = 0;
  318. for (j = 0; j < s->nb_components; j++) {
  319. s->planeweight[j] = (double) s->planeheight[j] * s->planewidth[j] / sum;
  320. average_max += s->max[j] * s->planeweight[j];
  321. }
  322. s->average_max = lrint(average_max);
  323. s->dsp.sse_line = desc->comp[0].depth > 8 ? sse_line_16bit : sse_line_8bit;
  324. if (ARCH_X86)
  325. ff_psnr_init_x86(&s->dsp, desc->comp[0].depth);
  326. s->score = av_calloc(s->nb_threads, sizeof(*s->score));
  327. if (!s->score)
  328. return AVERROR(ENOMEM);
  329. for (int t = 0; t < s->nb_threads && s->score; t++) {
  330. s->score[t] = av_calloc(s->nb_components, sizeof(*s->score[0]));
  331. if (!s->score[t])
  332. return AVERROR(ENOMEM);
  333. }
  334. return 0;
  335. }
  336. static int config_output(AVFilterLink *outlink)
  337. {
  338. AVFilterContext *ctx = outlink->src;
  339. PSNRContext *s = ctx->priv;
  340. AVFilterLink *mainlink = ctx->inputs[0];
  341. int ret;
  342. ret = ff_framesync_init_dualinput(&s->fs, ctx);
  343. if (ret < 0)
  344. return ret;
  345. outlink->w = mainlink->w;
  346. outlink->h = mainlink->h;
  347. outlink->time_base = mainlink->time_base;
  348. outlink->sample_aspect_ratio = mainlink->sample_aspect_ratio;
  349. outlink->frame_rate = mainlink->frame_rate;
  350. if ((ret = ff_framesync_configure(&s->fs)) < 0)
  351. return ret;
  352. outlink->time_base = s->fs.time_base;
  353. if (av_cmp_q(mainlink->time_base, outlink->time_base) ||
  354. av_cmp_q(ctx->inputs[1]->time_base, outlink->time_base))
  355. av_log(ctx, AV_LOG_WARNING, "not matching timebases found between first input: %d/%d and second input %d/%d, results may be incorrect!\n",
  356. mainlink->time_base.num, mainlink->time_base.den,
  357. ctx->inputs[1]->time_base.num, ctx->inputs[1]->time_base.den);
  358. return 0;
  359. }
  360. static int activate(AVFilterContext *ctx)
  361. {
  362. PSNRContext *s = ctx->priv;
  363. return ff_framesync_activate(&s->fs);
  364. }
  365. static av_cold void uninit(AVFilterContext *ctx)
  366. {
  367. PSNRContext *s = ctx->priv;
  368. if (s->nb_frames > 0) {
  369. int j;
  370. char buf[256];
  371. buf[0] = 0;
  372. for (j = 0; j < s->nb_components; j++) {
  373. int c = s->is_rgb ? s->rgba_map[j] : j;
  374. av_strlcatf(buf, sizeof(buf), " %c:%f", s->comps[j],
  375. get_psnr(s->mse_comp[c], s->nb_frames, s->max[c]));
  376. }
  377. av_log(ctx, AV_LOG_INFO, "PSNR%s average:%f min:%f max:%f\n",
  378. buf,
  379. get_psnr(s->mse, s->nb_frames, s->average_max),
  380. get_psnr(s->max_mse, 1, s->average_max),
  381. get_psnr(s->min_mse, 1, s->average_max));
  382. }
  383. ff_framesync_uninit(&s->fs);
  384. for (int t = 0; t < s->nb_threads && s->score; t++)
  385. av_freep(&s->score[t]);
  386. av_freep(&s->score);
  387. if (s->stats_file && s->stats_file != stdout)
  388. fclose(s->stats_file);
  389. }
  390. static const AVFilterPad psnr_inputs[] = {
  391. {
  392. .name = "main",
  393. .type = AVMEDIA_TYPE_VIDEO,
  394. },{
  395. .name = "reference",
  396. .type = AVMEDIA_TYPE_VIDEO,
  397. .config_props = config_input_ref,
  398. },
  399. { NULL }
  400. };
  401. static const AVFilterPad psnr_outputs[] = {
  402. {
  403. .name = "default",
  404. .type = AVMEDIA_TYPE_VIDEO,
  405. .config_props = config_output,
  406. },
  407. { NULL }
  408. };
  409. AVFilter ff_vf_psnr = {
  410. .name = "psnr",
  411. .description = NULL_IF_CONFIG_SMALL("Calculate the PSNR between two video streams."),
  412. .preinit = psnr_framesync_preinit,
  413. .init = init,
  414. .uninit = uninit,
  415. .query_formats = query_formats,
  416. .activate = activate,
  417. .priv_size = sizeof(PSNRContext),
  418. .priv_class = &psnr_class,
  419. .inputs = psnr_inputs,
  420. .outputs = psnr_outputs,
  421. .flags = AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL | AVFILTER_FLAG_SLICE_THREADS,
  422. };