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.

769 lines
27KB

  1. /*
  2. * Copyright (c) 2017 Gerion Entrup
  3. *
  4. * This file is part of FFmpeg.
  5. *
  6. * FFmpeg is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (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
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License along
  17. * with FFmpeg; if not, write to the Free Software Foundation, Inc.,
  18. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  19. */
  20. /**
  21. * @file
  22. * MPEG-7 video signature calculation and lookup filter
  23. * @see http://epubs.surrey.ac.uk/531590/1/MPEG-7%20Video%20Signature%20Author%27s%20Copy.pdf
  24. */
  25. #include <float.h>
  26. #include "libavcodec/put_bits.h"
  27. #include "libavformat/avformat.h"
  28. #include "libavutil/opt.h"
  29. #include "libavutil/avstring.h"
  30. #include "libavutil/intreadwrite.h"
  31. #include "libavutil/timestamp.h"
  32. #include "avfilter.h"
  33. #include "internal.h"
  34. #include "signature.h"
  35. #include "signature_lookup.c"
  36. #define OFFSET(x) offsetof(SignatureContext, x)
  37. #define FLAGS AV_OPT_FLAG_FILTERING_PARAM | AV_OPT_FLAG_VIDEO_PARAM
  38. #define BLOCK_LCM (int64_t) 476985600
  39. static const AVOption signature_options[] = {
  40. { "detectmode", "set the detectmode",
  41. OFFSET(mode), AV_OPT_TYPE_INT, {.i64 = MODE_OFF}, 0, NB_LOOKUP_MODE-1, FLAGS, "mode" },
  42. { "off", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MODE_OFF}, 0, 0, .flags = FLAGS, "mode" },
  43. { "full", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MODE_FULL}, 0, 0, .flags = FLAGS, "mode" },
  44. { "fast", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MODE_FAST}, 0, 0, .flags = FLAGS, "mode" },
  45. { "nb_inputs", "number of inputs",
  46. OFFSET(nb_inputs), AV_OPT_TYPE_INT, {.i64 = 1}, 1, INT_MAX, FLAGS },
  47. { "filename", "filename for output files",
  48. OFFSET(filename), AV_OPT_TYPE_STRING, {.str = ""}, 0, NB_FORMATS-1, FLAGS },
  49. { "format", "set output format",
  50. OFFSET(format), AV_OPT_TYPE_INT, {.i64 = FORMAT_BINARY}, 0, 1, FLAGS , "format" },
  51. { "binary", 0, 0, AV_OPT_TYPE_CONST, {.i64=FORMAT_BINARY}, 0, 0, FLAGS, "format" },
  52. { "xml", 0, 0, AV_OPT_TYPE_CONST, {.i64=FORMAT_XML}, 0, 0, FLAGS, "format" },
  53. { "th_d", "threshold to detect one word as similar",
  54. OFFSET(thworddist), AV_OPT_TYPE_INT, {.i64 = 9000}, 1, INT_MAX, FLAGS },
  55. { "th_dc", "threshold to detect all words as similar",
  56. OFFSET(thcomposdist), AV_OPT_TYPE_INT, {.i64 = 60000}, 1, INT_MAX, FLAGS },
  57. { "th_xh", "threshold to detect frames as similar",
  58. OFFSET(thl1), AV_OPT_TYPE_INT, {.i64 = 116}, 1, INT_MAX, FLAGS },
  59. { "th_di", "minimum length of matching sequence in frames",
  60. OFFSET(thdi), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, FLAGS },
  61. { "th_it", "threshold for relation of good to all frames",
  62. OFFSET(thit), AV_OPT_TYPE_DOUBLE, {.dbl = 0.5}, 0.0, 1.0, FLAGS },
  63. { NULL }
  64. };
  65. AVFILTER_DEFINE_CLASS(signature);
  66. static int query_formats(AVFilterContext *ctx)
  67. {
  68. /* all formats with a separate gray value */
  69. static const enum AVPixelFormat pix_fmts[] = {
  70. AV_PIX_FMT_GRAY8,
  71. AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P,
  72. AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P,
  73. AV_PIX_FMT_YUV440P, AV_PIX_FMT_YUV444P,
  74. AV_PIX_FMT_YUVJ411P, AV_PIX_FMT_YUVJ420P,
  75. AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ444P,
  76. AV_PIX_FMT_YUVJ440P,
  77. AV_PIX_FMT_NV12, AV_PIX_FMT_NV21,
  78. AV_PIX_FMT_NONE
  79. };
  80. return ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
  81. }
  82. static int config_input(AVFilterLink *inlink)
  83. {
  84. AVFilterContext *ctx = inlink->dst;
  85. SignatureContext *sic = ctx->priv;
  86. StreamContext *sc = &(sic->streamcontexts[FF_INLINK_IDX(inlink)]);
  87. sc->time_base = inlink->time_base;
  88. /* test for overflow */
  89. sc->divide = (((uint64_t) inlink->w/32) * (inlink->w/32 + 1) * (inlink->h/32 * inlink->h/32 + 1) > INT64_MAX / (BLOCK_LCM * 255));
  90. if (sc->divide) {
  91. av_log(ctx, AV_LOG_WARNING, "Input dimension too high for precise calculation, numbers will be rounded.\n");
  92. }
  93. sc->w = inlink->w;
  94. sc->h = inlink->h;
  95. return 0;
  96. }
  97. static int get_block_size(const Block *b)
  98. {
  99. return (b->to.y - b->up.y + 1) * (b->to.x - b->up.x + 1);
  100. }
  101. static uint64_t get_block_sum(StreamContext *sc, uint64_t intpic[32][32], const Block *b)
  102. {
  103. uint64_t sum = 0;
  104. int x0, y0, x1, y1;
  105. x0 = b->up.x;
  106. y0 = b->up.y;
  107. x1 = b->to.x;
  108. y1 = b->to.y;
  109. if (x0-1 >= 0 && y0-1 >= 0) {
  110. sum = intpic[y1][x1] + intpic[y0-1][x0-1] - intpic[y1][x0-1] - intpic[y0-1][x1];
  111. } else if (x0-1 >= 0) {
  112. sum = intpic[y1][x1] - intpic[y1][x0-1];
  113. } else if (y0-1 >= 0) {
  114. sum = intpic[y1][x1] - intpic[y0-1][x1];
  115. } else {
  116. sum = intpic[y1][x1];
  117. }
  118. return sum;
  119. }
  120. static int cmp(const uint64_t *a, const uint64_t *b)
  121. {
  122. return *a < *b ? -1 : ( *a > *b ? 1 : 0 );
  123. }
  124. /**
  125. * sets the bit at position pos to 1 in data
  126. */
  127. static void set_bit(uint8_t* data, size_t pos)
  128. {
  129. uint8_t mask = 1 << 7-(pos%8);
  130. data[pos/8] |= mask;
  131. }
  132. static int filter_frame(AVFilterLink *inlink, AVFrame *picref)
  133. {
  134. AVFilterContext *ctx = inlink->dst;
  135. SignatureContext *sic = ctx->priv;
  136. StreamContext *sc = &(sic->streamcontexts[FF_INLINK_IDX(inlink)]);
  137. FineSignature* fs;
  138. static const uint8_t pot3[5] = { 3*3*3*3, 3*3*3, 3*3, 3, 1 };
  139. /* indexes of words : 210,217,219,274,334 44,175,233,270,273 57,70,103,237,269 100,285,295,337,354 101,102,111,275,296
  140. s2usw = sorted to unsorted wordvec: 44 is at index 5, 57 at index 10...
  141. */
  142. static const unsigned int wordvec[25] = {44,57,70,100,101,102,103,111,175,210,217,219,233,237,269,270,273,274,275,285,295,296,334,337,354};
  143. static const uint8_t s2usw[25] = { 5,10,11, 15, 20, 21, 12, 22, 6, 0, 1, 2, 7, 13, 14, 8, 9, 3, 23, 16, 17, 24, 4, 18, 19};
  144. uint8_t wordt2b[5] = { 0, 0, 0, 0, 0 }; /* word ternary to binary */
  145. uint64_t intpic[32][32];
  146. uint64_t rowcount;
  147. uint8_t *p = picref->data[0];
  148. int inti, intj;
  149. int *intjlut;
  150. uint64_t conflist[DIFFELEM_SIZE];
  151. int f = 0, g = 0, w = 0;
  152. int32_t dh1 = 1, dh2 = 1, dw1 = 1, dw2 = 1, a, b;
  153. int64_t denom;
  154. int i, j, k, ternary;
  155. uint64_t blocksum;
  156. int blocksize;
  157. int64_t th; /* threshold */
  158. int64_t sum;
  159. int64_t precfactor = (sc->divide) ? 65536 : BLOCK_LCM;
  160. /* initialize fs */
  161. if (sc->curfinesig) {
  162. fs = av_mallocz(sizeof(FineSignature));
  163. if (!fs)
  164. return AVERROR(ENOMEM);
  165. sc->curfinesig->next = fs;
  166. fs->prev = sc->curfinesig;
  167. sc->curfinesig = fs;
  168. } else {
  169. fs = sc->curfinesig = sc->finesiglist;
  170. sc->curcoarsesig1->first = fs;
  171. }
  172. fs->pts = picref->pts;
  173. fs->index = sc->lastindex++;
  174. memset(intpic, 0, sizeof(uint64_t)*32*32);
  175. intjlut = av_malloc_array(inlink->w, sizeof(int));
  176. if (!intjlut)
  177. return AVERROR(ENOMEM);
  178. for (i = 0; i < inlink->w; i++) {
  179. intjlut[i] = (i*32)/inlink->w;
  180. }
  181. for (i = 0; i < inlink->h; i++) {
  182. inti = (i*32)/inlink->h;
  183. for (j = 0; j < inlink->w; j++) {
  184. intj = intjlut[j];
  185. intpic[inti][intj] += p[j];
  186. }
  187. p += picref->linesize[0];
  188. }
  189. av_freep(&intjlut);
  190. /* The following calculates a summed area table (intpic) and brings the numbers
  191. * in intpic to the same denominator.
  192. * So you only have to handle the numinator in the following sections.
  193. */
  194. dh1 = inlink->h / 32;
  195. if (inlink->h % 32)
  196. dh2 = dh1 + 1;
  197. dw1 = inlink->w / 32;
  198. if (inlink->w % 32)
  199. dw2 = dw1 + 1;
  200. denom = (sc->divide) ? dh1 * dh2 * dw1 * dw2 : 1;
  201. for (i = 0; i < 32; i++) {
  202. rowcount = 0;
  203. a = 1;
  204. if (dh2 > 1) {
  205. a = ((inlink->h*(i+1))%32 == 0) ? (inlink->h*(i+1))/32 - 1 : (inlink->h*(i+1))/32;
  206. a -= ((inlink->h*i)%32 == 0) ? (inlink->h*i)/32 - 1 : (inlink->h*i)/32;
  207. a = (a == dh1)? dh2 : dh1;
  208. }
  209. for (j = 0; j < 32; j++) {
  210. b = 1;
  211. if (dw2 > 1) {
  212. b = ((inlink->w*(j+1))%32 == 0) ? (inlink->w*(j+1))/32 - 1 : (inlink->w*(j+1))/32;
  213. b -= ((inlink->w*j)%32 == 0) ? (inlink->w*j)/32 - 1 : (inlink->w*j)/32;
  214. b = (b == dw1)? dw2 : dw1;
  215. }
  216. rowcount += intpic[i][j] * a * b * precfactor / denom;
  217. if (i > 0) {
  218. intpic[i][j] = intpic[i-1][j] + rowcount;
  219. } else {
  220. intpic[i][j] = rowcount;
  221. }
  222. }
  223. }
  224. denom = (sc->divide) ? 1 : dh1 * dh2 * dw1 * dw2;
  225. for (i = 0; i < ELEMENT_COUNT; i++) {
  226. const ElemCat* elemcat = elements[i];
  227. int64_t* elemsignature;
  228. uint64_t* sortsignature;
  229. elemsignature = av_malloc_array(elemcat->elem_count, sizeof(int64_t));
  230. if (!elemsignature)
  231. return AVERROR(ENOMEM);
  232. sortsignature = av_malloc_array(elemcat->elem_count, sizeof(int64_t));
  233. if (!sortsignature)
  234. return AVERROR(ENOMEM);
  235. for (j = 0; j < elemcat->elem_count; j++) {
  236. blocksum = 0;
  237. blocksize = 0;
  238. for (k = 0; k < elemcat->left_count; k++) {
  239. blocksum += get_block_sum(sc, intpic, &elemcat->blocks[j*elemcat->block_count+k]);
  240. blocksize += get_block_size(&elemcat->blocks[j*elemcat->block_count+k]);
  241. }
  242. sum = blocksum / blocksize;
  243. if (elemcat->av_elem) {
  244. sum -= 128 * precfactor * denom;
  245. } else {
  246. blocksum = 0;
  247. blocksize = 0;
  248. for (; k < elemcat->block_count; k++) {
  249. blocksum += get_block_sum(sc, intpic, &elemcat->blocks[j*elemcat->block_count+k]);
  250. blocksize += get_block_size(&elemcat->blocks[j*elemcat->block_count+k]);
  251. }
  252. sum -= blocksum / blocksize;
  253. conflist[g++] = FFABS(sum * 8 / (precfactor * denom));
  254. }
  255. elemsignature[j] = sum;
  256. sortsignature[j] = FFABS(sum);
  257. }
  258. /* get threshold */
  259. qsort(sortsignature, elemcat->elem_count, sizeof(uint64_t), (void*) cmp);
  260. th = sortsignature[(int) (elemcat->elem_count*0.333)];
  261. /* ternarize */
  262. for (j = 0; j < elemcat->elem_count; j++) {
  263. if (elemsignature[j] < -th) {
  264. ternary = 0;
  265. } else if (elemsignature[j] <= th) {
  266. ternary = 1;
  267. } else {
  268. ternary = 2;
  269. }
  270. fs->framesig[f/5] += ternary * pot3[f%5];
  271. if (f == wordvec[w]) {
  272. fs->words[s2usw[w]/5] += ternary * pot3[wordt2b[s2usw[w]/5]++];
  273. if (w < 24)
  274. w++;
  275. }
  276. f++;
  277. }
  278. av_freep(&elemsignature);
  279. av_freep(&sortsignature);
  280. }
  281. /* confidence */
  282. qsort(conflist, DIFFELEM_SIZE, sizeof(uint64_t), (void*) cmp);
  283. fs->confidence = FFMIN(conflist[DIFFELEM_SIZE/2], 255);
  284. /* coarsesignature */
  285. if (sc->coarsecount == 0) {
  286. if (sc->curcoarsesig2) {
  287. sc->curcoarsesig1 = av_mallocz(sizeof(CoarseSignature));
  288. if (!sc->curcoarsesig1)
  289. return AVERROR(ENOMEM);
  290. sc->curcoarsesig1->first = fs;
  291. sc->curcoarsesig2->next = sc->curcoarsesig1;
  292. sc->coarseend = sc->curcoarsesig1;
  293. }
  294. }
  295. if (sc->coarsecount == 45) {
  296. sc->midcoarse = 1;
  297. sc->curcoarsesig2 = av_mallocz(sizeof(CoarseSignature));
  298. if (!sc->curcoarsesig2)
  299. return AVERROR(ENOMEM);
  300. sc->curcoarsesig2->first = fs;
  301. sc->curcoarsesig1->next = sc->curcoarsesig2;
  302. sc->coarseend = sc->curcoarsesig2;
  303. }
  304. for (i = 0; i < 5; i++) {
  305. set_bit(sc->curcoarsesig1->data[i], fs->words[i]);
  306. }
  307. /* assuming the actual frame is the last */
  308. sc->curcoarsesig1->last = fs;
  309. if (sc->midcoarse) {
  310. for (i = 0; i < 5; i++) {
  311. set_bit(sc->curcoarsesig2->data[i], fs->words[i]);
  312. }
  313. sc->curcoarsesig2->last = fs;
  314. }
  315. sc->coarsecount = (sc->coarsecount+1)%90;
  316. /* debug printing finesignature */
  317. if (av_log_get_level() == AV_LOG_DEBUG) {
  318. av_log(ctx, AV_LOG_DEBUG, "input %d, confidence: %d\n", FF_INLINK_IDX(inlink), fs->confidence);
  319. av_log(ctx, AV_LOG_DEBUG, "words:");
  320. for (i = 0; i < 5; i++) {
  321. av_log(ctx, AV_LOG_DEBUG, " %d:", fs->words[i] );
  322. av_log(ctx, AV_LOG_DEBUG, " %d", fs->words[i] / pot3[0] );
  323. for (j = 1; j < 5; j++)
  324. av_log(ctx, AV_LOG_DEBUG, ",%d", fs->words[i] % pot3[j-1] / pot3[j] );
  325. av_log(ctx, AV_LOG_DEBUG, ";");
  326. }
  327. av_log(ctx, AV_LOG_DEBUG, "\n");
  328. av_log(ctx, AV_LOG_DEBUG, "framesignature:");
  329. for (i = 0; i < SIGELEM_SIZE/5; i++) {
  330. av_log(ctx, AV_LOG_DEBUG, " %d", fs->framesig[i] / pot3[0] );
  331. for (j = 1; j < 5; j++)
  332. av_log(ctx, AV_LOG_DEBUG, ",%d", fs->framesig[i] % pot3[j-1] / pot3[j] );
  333. }
  334. av_log(ctx, AV_LOG_DEBUG, "\n");
  335. }
  336. if (FF_INLINK_IDX(inlink) == 0)
  337. return ff_filter_frame(inlink->dst->outputs[0], picref);
  338. return 1;
  339. }
  340. static int xml_export(AVFilterContext *ctx, StreamContext *sc, const char* filename)
  341. {
  342. FineSignature* fs;
  343. CoarseSignature* cs;
  344. int i, j;
  345. FILE* f;
  346. unsigned int pot3[5] = { 3*3*3*3, 3*3*3, 3*3, 3, 1 };
  347. f = fopen(filename, "w");
  348. if (!f) {
  349. int err = AVERROR(EINVAL);
  350. char buf[128];
  351. av_strerror(err, buf, sizeof(buf));
  352. av_log(ctx, AV_LOG_ERROR, "cannot open xml file %s: %s\n", filename, buf);
  353. return err;
  354. }
  355. /* header */
  356. fprintf(f, "<?xml version='1.0' encoding='ASCII' ?>\n");
  357. fprintf(f, "<Mpeg7 xmlns=\"urn:mpeg:mpeg7:schema:2001\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"urn:mpeg:mpeg7:schema:2001 schema/Mpeg7-2001.xsd\">\n");
  358. fprintf(f, " <DescriptionUnit xsi:type=\"DescriptorCollectionType\">\n");
  359. fprintf(f, " <Descriptor xsi:type=\"VideoSignatureType\">\n");
  360. fprintf(f, " <VideoSignatureRegion>\n");
  361. fprintf(f, " <VideoSignatureSpatialRegion>\n");
  362. fprintf(f, " <Pixel>0 0 </Pixel>\n");
  363. fprintf(f, " <Pixel>%d %d </Pixel>\n", sc->w - 1, sc->h - 1);
  364. fprintf(f, " </VideoSignatureSpatialRegion>\n");
  365. fprintf(f, " <StartFrameOfSpatialRegion>0</StartFrameOfSpatialRegion>\n");
  366. /* hoping num is 1, other values are vague */
  367. fprintf(f, " <MediaTimeUnit>%d</MediaTimeUnit>\n", sc->time_base.den / sc->time_base.num);
  368. fprintf(f, " <MediaTimeOfSpatialRegion>\n");
  369. fprintf(f, " <StartMediaTimeOfSpatialRegion>0</StartMediaTimeOfSpatialRegion>\n");
  370. fprintf(f, " <EndMediaTimeOfSpatialRegion>%" PRIu64 "</EndMediaTimeOfSpatialRegion>\n", sc->coarseend->last->pts);
  371. fprintf(f, " </MediaTimeOfSpatialRegion>\n");
  372. /* coarsesignatures */
  373. for (cs = sc->coarsesiglist; cs; cs = cs->next) {
  374. fprintf(f, " <VSVideoSegment>\n");
  375. fprintf(f, " <StartFrameOfSegment>%" PRIu32 "</StartFrameOfSegment>\n", cs->first->index);
  376. fprintf(f, " <EndFrameOfSegment>%" PRIu32 "</EndFrameOfSegment>\n", cs->last->index);
  377. fprintf(f, " <MediaTimeOfSegment>\n");
  378. fprintf(f, " <StartMediaTimeOfSegment>%" PRIu64 "</StartMediaTimeOfSegment>\n", cs->first->pts);
  379. fprintf(f, " <EndMediaTimeOfSegment>%" PRIu64 "</EndMediaTimeOfSegment>\n", cs->last->pts);
  380. fprintf(f, " </MediaTimeOfSegment>\n");
  381. for (i = 0; i < 5; i++) {
  382. fprintf(f, " <BagOfWords>");
  383. for (j = 0; j < 31; j++) {
  384. uint8_t n = cs->data[i][j];
  385. if (j < 30) {
  386. fprintf(f, "%d %d %d %d %d %d %d %d ", (n & 0x80) >> 7,
  387. (n & 0x40) >> 6,
  388. (n & 0x20) >> 5,
  389. (n & 0x10) >> 4,
  390. (n & 0x08) >> 3,
  391. (n & 0x04) >> 2,
  392. (n & 0x02) >> 1,
  393. (n & 0x01));
  394. } else {
  395. /* print only 3 bit in last byte */
  396. fprintf(f, "%d %d %d ", (n & 0x80) >> 7,
  397. (n & 0x40) >> 6,
  398. (n & 0x20) >> 5);
  399. }
  400. }
  401. fprintf(f, "</BagOfWords>\n");
  402. }
  403. fprintf(f, " </VSVideoSegment>\n");
  404. }
  405. /* finesignatures */
  406. for (fs = sc->finesiglist; fs; fs = fs->next) {
  407. fprintf(f, " <VideoFrame>\n");
  408. fprintf(f, " <MediaTimeOfFrame>%" PRIu64 "</MediaTimeOfFrame>\n", fs->pts);
  409. /* confidence */
  410. fprintf(f, " <FrameConfidence>%d</FrameConfidence>\n", fs->confidence);
  411. /* words */
  412. fprintf(f, " <Word>");
  413. for (i = 0; i < 5; i++) {
  414. fprintf(f, "%d ", fs->words[i]);
  415. if (i < 4) {
  416. fprintf(f, " ");
  417. }
  418. }
  419. fprintf(f, "</Word>\n");
  420. /* framesignature */
  421. fprintf(f, " <FrameSignature>");
  422. for (i = 0; i< SIGELEM_SIZE/5; i++) {
  423. if (i > 0) {
  424. fprintf(f, " ");
  425. }
  426. fprintf(f, "%d ", fs->framesig[i] / pot3[0]);
  427. for (j = 1; j < 5; j++)
  428. fprintf(f, " %d ", fs->framesig[i] % pot3[j-1] / pot3[j] );
  429. }
  430. fprintf(f, "</FrameSignature>\n");
  431. fprintf(f, " </VideoFrame>\n");
  432. }
  433. fprintf(f, " </VideoSignatureRegion>\n");
  434. fprintf(f, " </Descriptor>\n");
  435. fprintf(f, " </DescriptionUnit>\n");
  436. fprintf(f, "</Mpeg7>\n");
  437. fclose(f);
  438. return 0;
  439. }
  440. static int binary_export(AVFilterContext *ctx, StreamContext *sc, const char* filename)
  441. {
  442. FILE* f;
  443. FineSignature* fs;
  444. CoarseSignature* cs;
  445. uint32_t numofsegments = (sc->lastindex + 44)/45;
  446. int i, j;
  447. PutBitContext buf;
  448. /* buffer + header + coarsesignatures + finesignature */
  449. int len = (512 + 6 * 32 + 3*16 + 2 +
  450. numofsegments * (4*32 + 1 + 5*243) +
  451. sc->lastindex * (2 + 32 + 6*8 + 608)) / 8;
  452. uint8_t* buffer = av_malloc_array(len, sizeof(uint8_t));
  453. if (!buffer)
  454. return AVERROR(ENOMEM);
  455. f = fopen(filename, "wb");
  456. if (!f) {
  457. int err = AVERROR(EINVAL);
  458. char buf[128];
  459. av_strerror(err, buf, sizeof(buf));
  460. av_log(ctx, AV_LOG_ERROR, "cannot open file %s: %s\n", filename, buf);
  461. return err;
  462. }
  463. init_put_bits(&buf, buffer, len);
  464. put_bits32(&buf, 1); /* NumOfSpatial Regions, only 1 supported */
  465. put_bits(&buf, 1, 1); /* SpatialLocationFlag, always the whole image */
  466. put_bits32(&buf, 0); /* PixelX,1 PixelY,1, 0,0 */
  467. put_bits(&buf, 16, sc->w-1 & 0xFFFF); /* PixelX,2 */
  468. put_bits(&buf, 16, sc->h-1 & 0xFFFF); /* PixelY,2 */
  469. put_bits32(&buf, 0); /* StartFrameOfSpatialRegion */
  470. put_bits32(&buf, sc->lastindex); /* NumOfFrames */
  471. /* hoping num is 1, other values are vague */
  472. /* den/num might be greater than 16 bit, so cutting it */
  473. put_bits(&buf, 16, 0xFFFF & (sc->time_base.den / sc->time_base.num)); /* MediaTimeUnit */
  474. put_bits(&buf, 1, 1); /* MediaTimeFlagOfSpatialRegion */
  475. put_bits32(&buf, 0); /* StartMediaTimeOfSpatialRegion */
  476. put_bits32(&buf, 0xFFFFFFFF & sc->coarseend->last->pts); /* EndMediaTimeOfSpatialRegion */
  477. put_bits32(&buf, numofsegments); /* NumOfSegments */
  478. /* coarsesignatures */
  479. for (cs = sc->coarsesiglist; cs; cs = cs->next) {
  480. put_bits32(&buf, cs->first->index); /* StartFrameOfSegment */
  481. put_bits32(&buf, cs->last->index); /* EndFrameOfSegment */
  482. put_bits(&buf, 1, 1); /* MediaTimeFlagOfSegment */
  483. put_bits32(&buf, 0xFFFFFFFF & cs->first->pts); /* StartMediaTimeOfSegment */
  484. put_bits32(&buf, 0xFFFFFFFF & cs->last->pts); /* EndMediaTimeOfSegment */
  485. for (i = 0; i < 5; i++) {
  486. /* put 243 bits ( = 7 * 32 + 19 = 8 * 28 + 19) into buffer */
  487. for (j = 0; j < 30; j++) {
  488. put_bits(&buf, 8, cs->data[i][j]);
  489. }
  490. put_bits(&buf, 3, cs->data[i][30] >> 5);
  491. }
  492. }
  493. /* finesignatures */
  494. put_bits(&buf, 1, 0); /* CompressionFlag, only 0 supported */
  495. for (fs = sc->finesiglist; fs; fs = fs->next) {
  496. put_bits(&buf, 1, 1); /* MediaTimeFlagOfFrame */
  497. put_bits32(&buf, 0xFFFFFFFF & fs->pts); /* MediaTimeOfFrame */
  498. put_bits(&buf, 8, fs->confidence); /* FrameConfidence */
  499. for (i = 0; i < 5; i++) {
  500. put_bits(&buf, 8, fs->words[i]); /* Words */
  501. }
  502. /* framesignature */
  503. for (i = 0; i < SIGELEM_SIZE/5; i++) {
  504. put_bits(&buf, 8, fs->framesig[i]);
  505. }
  506. }
  507. avpriv_align_put_bits(&buf);
  508. flush_put_bits(&buf);
  509. fwrite(buffer, 1, put_bits_count(&buf)/8, f);
  510. fclose(f);
  511. av_freep(&buffer);
  512. return 0;
  513. }
  514. static int export(AVFilterContext *ctx, StreamContext *sc, int input)
  515. {
  516. SignatureContext* sic = ctx->priv;
  517. char filename[1024];
  518. if (sic->nb_inputs > 1) {
  519. /* error already handled */
  520. av_assert0(av_get_frame_filename(filename, sizeof(filename), sic->filename, input) == 0);
  521. } else {
  522. if (av_strlcpy(filename, sic->filename, sizeof(filename)) >= sizeof(filename))
  523. return AVERROR(EINVAL);
  524. }
  525. if (sic->format == FORMAT_XML) {
  526. return xml_export(ctx, sc, filename);
  527. } else {
  528. return binary_export(ctx, sc, filename);
  529. }
  530. }
  531. static int request_frame(AVFilterLink *outlink)
  532. {
  533. AVFilterContext *ctx = outlink->src;
  534. SignatureContext *sic = ctx->priv;
  535. StreamContext *sc, *sc2;
  536. MatchingInfo match;
  537. int i, j, ret;
  538. int lookup = 1; /* indicates wheather EOF of all files is reached */
  539. /* process all inputs */
  540. for (i = 0; i < sic->nb_inputs; i++){
  541. sc = &(sic->streamcontexts[i]);
  542. ret = ff_request_frame(ctx->inputs[i]);
  543. /* return if unexpected error occurs in input stream */
  544. if (ret < 0 && ret != AVERROR_EOF)
  545. return ret;
  546. /* export signature at EOF */
  547. if (ret == AVERROR_EOF && !sc->exported) {
  548. /* export if wanted */
  549. if (strlen(sic->filename) > 0) {
  550. if (export(ctx, sc, i) < 0)
  551. return ret;
  552. }
  553. sc->exported = 1;
  554. }
  555. lookup &= sc->exported;
  556. }
  557. /* signature lookup */
  558. if (lookup && sic->mode != MODE_OFF) {
  559. /* iterate over every pair */
  560. for (i = 0; i < sic->nb_inputs; i++) {
  561. sc = &(sic->streamcontexts[i]);
  562. for (j = i+1; j < sic->nb_inputs; j++) {
  563. sc2 = &(sic->streamcontexts[j]);
  564. match = lookup_signatures(ctx, sic, sc, sc2, sic->mode);
  565. if (match.score != 0) {
  566. av_log(ctx, AV_LOG_INFO, "matching of video %d at %f and %d at %f, %d frames matching\n",
  567. i, ((double) match.first->pts * sc->time_base.num) / sc->time_base.den,
  568. j, ((double) match.second->pts * sc2->time_base.num) / sc2->time_base.den,
  569. match.matchframes);
  570. if (match.whole)
  571. av_log(ctx, AV_LOG_INFO, "whole video matching\n");
  572. } else {
  573. av_log(ctx, AV_LOG_INFO, "no matching of video %d and %d\n", i, j);
  574. }
  575. }
  576. }
  577. }
  578. return ret;
  579. }
  580. static av_cold int init(AVFilterContext *ctx)
  581. {
  582. SignatureContext *sic = ctx->priv;
  583. StreamContext *sc;
  584. int i, ret;
  585. char tmp[1024];
  586. sic->streamcontexts = av_mallocz(sic->nb_inputs * sizeof(StreamContext));
  587. if (!sic->streamcontexts)
  588. return AVERROR(ENOMEM);
  589. for (i = 0; i < sic->nb_inputs; i++) {
  590. AVFilterPad pad = {
  591. .type = AVMEDIA_TYPE_VIDEO,
  592. .name = av_asprintf("in%d", i),
  593. .config_props = config_input,
  594. .filter_frame = filter_frame,
  595. };
  596. if (!pad.name)
  597. return AVERROR(ENOMEM);
  598. sc = &(sic->streamcontexts[i]);
  599. sc->lastindex = 0;
  600. sc->finesiglist = av_mallocz(sizeof(FineSignature));
  601. if (!sc->finesiglist)
  602. return AVERROR(ENOMEM);
  603. sc->curfinesig = NULL;
  604. sc->coarsesiglist = av_mallocz(sizeof(CoarseSignature));
  605. if (!sc->coarsesiglist)
  606. return AVERROR(ENOMEM);
  607. sc->curcoarsesig1 = sc->coarsesiglist;
  608. sc->coarseend = sc->coarsesiglist;
  609. sc->coarsecount = 0;
  610. sc->midcoarse = 0;
  611. if ((ret = ff_insert_inpad(ctx, i, &pad)) < 0) {
  612. av_freep(&pad.name);
  613. return ret;
  614. }
  615. }
  616. /* check filename */
  617. if (sic->nb_inputs > 1 && strlen(sic->filename) > 0 && av_get_frame_filename(tmp, sizeof(tmp), sic->filename, 0) == -1) {
  618. av_log(ctx, AV_LOG_ERROR, "The filename must contain %%d or %%0nd, if you have more than one input.\n");
  619. return AVERROR(EINVAL);
  620. }
  621. return 0;
  622. }
  623. static av_cold void uninit(AVFilterContext *ctx)
  624. {
  625. SignatureContext *sic = ctx->priv;
  626. StreamContext *sc;
  627. void* tmp;
  628. FineSignature* finsig;
  629. CoarseSignature* cousig;
  630. int i;
  631. /* free the lists */
  632. if (sic->streamcontexts != NULL) {
  633. for (i = 0; i < sic->nb_inputs; i++) {
  634. sc = &(sic->streamcontexts[i]);
  635. finsig = sc->finesiglist;
  636. cousig = sc->coarsesiglist;
  637. while (finsig) {
  638. tmp = finsig;
  639. finsig = finsig->next;
  640. av_freep(&tmp);
  641. }
  642. sc->finesiglist = NULL;
  643. while (cousig) {
  644. tmp = cousig;
  645. cousig = cousig->next;
  646. av_freep(&tmp);
  647. }
  648. sc->coarsesiglist = NULL;
  649. }
  650. av_freep(&sic->streamcontexts);
  651. }
  652. }
  653. static int config_output(AVFilterLink *outlink)
  654. {
  655. AVFilterContext *ctx = outlink->src;
  656. AVFilterLink *inlink = ctx->inputs[0];
  657. outlink->time_base = inlink->time_base;
  658. outlink->frame_rate = inlink->frame_rate;
  659. outlink->sample_aspect_ratio = inlink->sample_aspect_ratio;
  660. outlink->w = inlink->w;
  661. outlink->h = inlink->h;
  662. return 0;
  663. }
  664. static const AVFilterPad signature_outputs[] = {
  665. {
  666. .name = "default",
  667. .type = AVMEDIA_TYPE_VIDEO,
  668. .request_frame = request_frame,
  669. .config_props = config_output,
  670. },
  671. { NULL }
  672. };
  673. AVFilter ff_vf_signature = {
  674. .name = "signature",
  675. .description = NULL_IF_CONFIG_SMALL("Calculate the MPEG-7 video signature"),
  676. .priv_size = sizeof(SignatureContext),
  677. .priv_class = &signature_class,
  678. .init = init,
  679. .uninit = uninit,
  680. .query_formats = query_formats,
  681. .outputs = signature_outputs,
  682. .inputs = NULL,
  683. .flags = AVFILTER_FLAG_DYNAMIC_INPUTS,
  684. };