vf_signature.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  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. av_freep(&elemsignature);
  235. return AVERROR(ENOMEM);
  236. }
  237. for (j = 0; j < elemcat->elem_count; j++) {
  238. blocksum = 0;
  239. blocksize = 0;
  240. for (k = 0; k < elemcat->left_count; k++) {
  241. blocksum += get_block_sum(sc, intpic, &elemcat->blocks[j*elemcat->block_count+k]);
  242. blocksize += get_block_size(&elemcat->blocks[j*elemcat->block_count+k]);
  243. }
  244. sum = blocksum / blocksize;
  245. if (elemcat->av_elem) {
  246. sum -= 128 * precfactor * denom;
  247. } else {
  248. blocksum = 0;
  249. blocksize = 0;
  250. for (; k < elemcat->block_count; k++) {
  251. blocksum += get_block_sum(sc, intpic, &elemcat->blocks[j*elemcat->block_count+k]);
  252. blocksize += get_block_size(&elemcat->blocks[j*elemcat->block_count+k]);
  253. }
  254. sum -= blocksum / blocksize;
  255. conflist[g++] = FFABS(sum * 8 / (precfactor * denom));
  256. }
  257. elemsignature[j] = sum;
  258. sortsignature[j] = FFABS(sum);
  259. }
  260. /* get threshold */
  261. qsort(sortsignature, elemcat->elem_count, sizeof(uint64_t), (void*) cmp);
  262. th = sortsignature[(int) (elemcat->elem_count*0.333)];
  263. /* ternarize */
  264. for (j = 0; j < elemcat->elem_count; j++) {
  265. if (elemsignature[j] < -th) {
  266. ternary = 0;
  267. } else if (elemsignature[j] <= th) {
  268. ternary = 1;
  269. } else {
  270. ternary = 2;
  271. }
  272. fs->framesig[f/5] += ternary * pot3[f%5];
  273. if (f == wordvec[w]) {
  274. fs->words[s2usw[w]/5] += ternary * pot3[wordt2b[s2usw[w]/5]++];
  275. if (w < 24)
  276. w++;
  277. }
  278. f++;
  279. }
  280. av_freep(&elemsignature);
  281. av_freep(&sortsignature);
  282. }
  283. /* confidence */
  284. qsort(conflist, DIFFELEM_SIZE, sizeof(uint64_t), (void*) cmp);
  285. fs->confidence = FFMIN(conflist[DIFFELEM_SIZE/2], 255);
  286. /* coarsesignature */
  287. if (sc->coarsecount == 0) {
  288. if (sc->curcoarsesig2) {
  289. sc->curcoarsesig1 = av_mallocz(sizeof(CoarseSignature));
  290. if (!sc->curcoarsesig1)
  291. return AVERROR(ENOMEM);
  292. sc->curcoarsesig1->first = fs;
  293. sc->curcoarsesig2->next = sc->curcoarsesig1;
  294. sc->coarseend = sc->curcoarsesig1;
  295. }
  296. }
  297. if (sc->coarsecount == 45) {
  298. sc->midcoarse = 1;
  299. sc->curcoarsesig2 = av_mallocz(sizeof(CoarseSignature));
  300. if (!sc->curcoarsesig2)
  301. return AVERROR(ENOMEM);
  302. sc->curcoarsesig2->first = fs;
  303. sc->curcoarsesig1->next = sc->curcoarsesig2;
  304. sc->coarseend = sc->curcoarsesig2;
  305. }
  306. for (i = 0; i < 5; i++) {
  307. set_bit(sc->curcoarsesig1->data[i], fs->words[i]);
  308. }
  309. /* assuming the actual frame is the last */
  310. sc->curcoarsesig1->last = fs;
  311. if (sc->midcoarse) {
  312. for (i = 0; i < 5; i++) {
  313. set_bit(sc->curcoarsesig2->data[i], fs->words[i]);
  314. }
  315. sc->curcoarsesig2->last = fs;
  316. }
  317. sc->coarsecount = (sc->coarsecount+1)%90;
  318. /* debug printing finesignature */
  319. if (av_log_get_level() == AV_LOG_DEBUG) {
  320. av_log(ctx, AV_LOG_DEBUG, "input %d, confidence: %d\n", FF_INLINK_IDX(inlink), fs->confidence);
  321. av_log(ctx, AV_LOG_DEBUG, "words:");
  322. for (i = 0; i < 5; i++) {
  323. av_log(ctx, AV_LOG_DEBUG, " %d:", fs->words[i] );
  324. av_log(ctx, AV_LOG_DEBUG, " %d", fs->words[i] / pot3[0] );
  325. for (j = 1; j < 5; j++)
  326. av_log(ctx, AV_LOG_DEBUG, ",%d", fs->words[i] % pot3[j-1] / pot3[j] );
  327. av_log(ctx, AV_LOG_DEBUG, ";");
  328. }
  329. av_log(ctx, AV_LOG_DEBUG, "\n");
  330. av_log(ctx, AV_LOG_DEBUG, "framesignature:");
  331. for (i = 0; i < SIGELEM_SIZE/5; i++) {
  332. av_log(ctx, AV_LOG_DEBUG, " %d", fs->framesig[i] / pot3[0] );
  333. for (j = 1; j < 5; j++)
  334. av_log(ctx, AV_LOG_DEBUG, ",%d", fs->framesig[i] % pot3[j-1] / pot3[j] );
  335. }
  336. av_log(ctx, AV_LOG_DEBUG, "\n");
  337. }
  338. if (FF_INLINK_IDX(inlink) == 0)
  339. return ff_filter_frame(inlink->dst->outputs[0], picref);
  340. return 1;
  341. }
  342. static int xml_export(AVFilterContext *ctx, StreamContext *sc, const char* filename)
  343. {
  344. FineSignature* fs;
  345. CoarseSignature* cs;
  346. int i, j;
  347. FILE* f;
  348. unsigned int pot3[5] = { 3*3*3*3, 3*3*3, 3*3, 3, 1 };
  349. f = fopen(filename, "w");
  350. if (!f) {
  351. int err = AVERROR(EINVAL);
  352. char buf[128];
  353. av_strerror(err, buf, sizeof(buf));
  354. av_log(ctx, AV_LOG_ERROR, "cannot open xml file %s: %s\n", filename, buf);
  355. return err;
  356. }
  357. /* header */
  358. fprintf(f, "<?xml version='1.0' encoding='ASCII' ?>\n");
  359. 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");
  360. fprintf(f, " <DescriptionUnit xsi:type=\"DescriptorCollectionType\">\n");
  361. fprintf(f, " <Descriptor xsi:type=\"VideoSignatureType\">\n");
  362. fprintf(f, " <VideoSignatureRegion>\n");
  363. fprintf(f, " <VideoSignatureSpatialRegion>\n");
  364. fprintf(f, " <Pixel>0 0 </Pixel>\n");
  365. fprintf(f, " <Pixel>%d %d </Pixel>\n", sc->w - 1, sc->h - 1);
  366. fprintf(f, " </VideoSignatureSpatialRegion>\n");
  367. fprintf(f, " <StartFrameOfSpatialRegion>0</StartFrameOfSpatialRegion>\n");
  368. /* hoping num is 1, other values are vague */
  369. fprintf(f, " <MediaTimeUnit>%d</MediaTimeUnit>\n", sc->time_base.den / sc->time_base.num);
  370. fprintf(f, " <MediaTimeOfSpatialRegion>\n");
  371. fprintf(f, " <StartMediaTimeOfSpatialRegion>0</StartMediaTimeOfSpatialRegion>\n");
  372. fprintf(f, " <EndMediaTimeOfSpatialRegion>%" PRIu64 "</EndMediaTimeOfSpatialRegion>\n", sc->coarseend->last->pts);
  373. fprintf(f, " </MediaTimeOfSpatialRegion>\n");
  374. /* coarsesignatures */
  375. for (cs = sc->coarsesiglist; cs; cs = cs->next) {
  376. fprintf(f, " <VSVideoSegment>\n");
  377. fprintf(f, " <StartFrameOfSegment>%" PRIu32 "</StartFrameOfSegment>\n", cs->first->index);
  378. fprintf(f, " <EndFrameOfSegment>%" PRIu32 "</EndFrameOfSegment>\n", cs->last->index);
  379. fprintf(f, " <MediaTimeOfSegment>\n");
  380. fprintf(f, " <StartMediaTimeOfSegment>%" PRIu64 "</StartMediaTimeOfSegment>\n", cs->first->pts);
  381. fprintf(f, " <EndMediaTimeOfSegment>%" PRIu64 "</EndMediaTimeOfSegment>\n", cs->last->pts);
  382. fprintf(f, " </MediaTimeOfSegment>\n");
  383. for (i = 0; i < 5; i++) {
  384. fprintf(f, " <BagOfWords>");
  385. for (j = 0; j < 31; j++) {
  386. uint8_t n = cs->data[i][j];
  387. if (j < 30) {
  388. fprintf(f, "%d %d %d %d %d %d %d %d ", (n & 0x80) >> 7,
  389. (n & 0x40) >> 6,
  390. (n & 0x20) >> 5,
  391. (n & 0x10) >> 4,
  392. (n & 0x08) >> 3,
  393. (n & 0x04) >> 2,
  394. (n & 0x02) >> 1,
  395. (n & 0x01));
  396. } else {
  397. /* print only 3 bit in last byte */
  398. fprintf(f, "%d %d %d ", (n & 0x80) >> 7,
  399. (n & 0x40) >> 6,
  400. (n & 0x20) >> 5);
  401. }
  402. }
  403. fprintf(f, "</BagOfWords>\n");
  404. }
  405. fprintf(f, " </VSVideoSegment>\n");
  406. }
  407. /* finesignatures */
  408. for (fs = sc->finesiglist; fs; fs = fs->next) {
  409. fprintf(f, " <VideoFrame>\n");
  410. fprintf(f, " <MediaTimeOfFrame>%" PRIu64 "</MediaTimeOfFrame>\n", fs->pts);
  411. /* confidence */
  412. fprintf(f, " <FrameConfidence>%d</FrameConfidence>\n", fs->confidence);
  413. /* words */
  414. fprintf(f, " <Word>");
  415. for (i = 0; i < 5; i++) {
  416. fprintf(f, "%d ", fs->words[i]);
  417. if (i < 4) {
  418. fprintf(f, " ");
  419. }
  420. }
  421. fprintf(f, "</Word>\n");
  422. /* framesignature */
  423. fprintf(f, " <FrameSignature>");
  424. for (i = 0; i< SIGELEM_SIZE/5; i++) {
  425. if (i > 0) {
  426. fprintf(f, " ");
  427. }
  428. fprintf(f, "%d ", fs->framesig[i] / pot3[0]);
  429. for (j = 1; j < 5; j++)
  430. fprintf(f, " %d ", fs->framesig[i] % pot3[j-1] / pot3[j] );
  431. }
  432. fprintf(f, "</FrameSignature>\n");
  433. fprintf(f, " </VideoFrame>\n");
  434. }
  435. fprintf(f, " </VideoSignatureRegion>\n");
  436. fprintf(f, " </Descriptor>\n");
  437. fprintf(f, " </DescriptionUnit>\n");
  438. fprintf(f, "</Mpeg7>\n");
  439. fclose(f);
  440. return 0;
  441. }
  442. static int binary_export(AVFilterContext *ctx, StreamContext *sc, const char* filename)
  443. {
  444. FILE* f;
  445. FineSignature* fs;
  446. CoarseSignature* cs;
  447. uint32_t numofsegments = (sc->lastindex + 44)/45;
  448. int i, j;
  449. PutBitContext buf;
  450. /* buffer + header + coarsesignatures + finesignature */
  451. int len = (512 + 6 * 32 + 3*16 + 2 +
  452. numofsegments * (4*32 + 1 + 5*243) +
  453. sc->lastindex * (2 + 32 + 6*8 + 608)) / 8;
  454. uint8_t* buffer = av_malloc_array(len, sizeof(uint8_t));
  455. if (!buffer)
  456. return AVERROR(ENOMEM);
  457. f = fopen(filename, "wb");
  458. if (!f) {
  459. int err = AVERROR(EINVAL);
  460. char buf[128];
  461. av_strerror(err, buf, sizeof(buf));
  462. av_log(ctx, AV_LOG_ERROR, "cannot open file %s: %s\n", filename, buf);
  463. av_freep(&buffer);
  464. return err;
  465. }
  466. init_put_bits(&buf, buffer, len);
  467. put_bits32(&buf, 1); /* NumOfSpatial Regions, only 1 supported */
  468. put_bits(&buf, 1, 1); /* SpatialLocationFlag, always the whole image */
  469. put_bits32(&buf, 0); /* PixelX,1 PixelY,1, 0,0 */
  470. put_bits(&buf, 16, sc->w-1 & 0xFFFF); /* PixelX,2 */
  471. put_bits(&buf, 16, sc->h-1 & 0xFFFF); /* PixelY,2 */
  472. put_bits32(&buf, 0); /* StartFrameOfSpatialRegion */
  473. put_bits32(&buf, sc->lastindex); /* NumOfFrames */
  474. /* hoping num is 1, other values are vague */
  475. /* den/num might be greater than 16 bit, so cutting it */
  476. put_bits(&buf, 16, 0xFFFF & (sc->time_base.den / sc->time_base.num)); /* MediaTimeUnit */
  477. put_bits(&buf, 1, 1); /* MediaTimeFlagOfSpatialRegion */
  478. put_bits32(&buf, 0); /* StartMediaTimeOfSpatialRegion */
  479. put_bits32(&buf, 0xFFFFFFFF & sc->coarseend->last->pts); /* EndMediaTimeOfSpatialRegion */
  480. put_bits32(&buf, numofsegments); /* NumOfSegments */
  481. /* coarsesignatures */
  482. for (cs = sc->coarsesiglist; cs; cs = cs->next) {
  483. put_bits32(&buf, cs->first->index); /* StartFrameOfSegment */
  484. put_bits32(&buf, cs->last->index); /* EndFrameOfSegment */
  485. put_bits(&buf, 1, 1); /* MediaTimeFlagOfSegment */
  486. put_bits32(&buf, 0xFFFFFFFF & cs->first->pts); /* StartMediaTimeOfSegment */
  487. put_bits32(&buf, 0xFFFFFFFF & cs->last->pts); /* EndMediaTimeOfSegment */
  488. for (i = 0; i < 5; i++) {
  489. /* put 243 bits ( = 7 * 32 + 19 = 8 * 28 + 19) into buffer */
  490. for (j = 0; j < 30; j++) {
  491. put_bits(&buf, 8, cs->data[i][j]);
  492. }
  493. put_bits(&buf, 3, cs->data[i][30] >> 5);
  494. }
  495. }
  496. /* finesignatures */
  497. put_bits(&buf, 1, 0); /* CompressionFlag, only 0 supported */
  498. for (fs = sc->finesiglist; fs; fs = fs->next) {
  499. put_bits(&buf, 1, 1); /* MediaTimeFlagOfFrame */
  500. put_bits32(&buf, 0xFFFFFFFF & fs->pts); /* MediaTimeOfFrame */
  501. put_bits(&buf, 8, fs->confidence); /* FrameConfidence */
  502. for (i = 0; i < 5; i++) {
  503. put_bits(&buf, 8, fs->words[i]); /* Words */
  504. }
  505. /* framesignature */
  506. for (i = 0; i < SIGELEM_SIZE/5; i++) {
  507. put_bits(&buf, 8, fs->framesig[i]);
  508. }
  509. }
  510. avpriv_align_put_bits(&buf);
  511. flush_put_bits(&buf);
  512. fwrite(buffer, 1, put_bits_count(&buf)/8, f);
  513. fclose(f);
  514. av_freep(&buffer);
  515. return 0;
  516. }
  517. static int export(AVFilterContext *ctx, StreamContext *sc, int input)
  518. {
  519. SignatureContext* sic = ctx->priv;
  520. char filename[1024];
  521. if (sic->nb_inputs > 1) {
  522. /* error already handled */
  523. av_assert0(av_get_frame_filename(filename, sizeof(filename), sic->filename, input) == 0);
  524. } else {
  525. if (av_strlcpy(filename, sic->filename, sizeof(filename)) >= sizeof(filename))
  526. return AVERROR(EINVAL);
  527. }
  528. if (sic->format == FORMAT_XML) {
  529. return xml_export(ctx, sc, filename);
  530. } else {
  531. return binary_export(ctx, sc, filename);
  532. }
  533. }
  534. static int request_frame(AVFilterLink *outlink)
  535. {
  536. AVFilterContext *ctx = outlink->src;
  537. SignatureContext *sic = ctx->priv;
  538. StreamContext *sc, *sc2;
  539. MatchingInfo match;
  540. int i, j, ret;
  541. int lookup = 1; /* indicates wheather EOF of all files is reached */
  542. /* process all inputs */
  543. for (i = 0; i < sic->nb_inputs; i++){
  544. sc = &(sic->streamcontexts[i]);
  545. ret = ff_request_frame(ctx->inputs[i]);
  546. /* return if unexpected error occurs in input stream */
  547. if (ret < 0 && ret != AVERROR_EOF)
  548. return ret;
  549. /* export signature at EOF */
  550. if (ret == AVERROR_EOF && !sc->exported) {
  551. /* export if wanted */
  552. if (strlen(sic->filename) > 0) {
  553. if (export(ctx, sc, i) < 0)
  554. return ret;
  555. }
  556. sc->exported = 1;
  557. }
  558. lookup &= sc->exported;
  559. }
  560. /* signature lookup */
  561. if (lookup && sic->mode != MODE_OFF) {
  562. /* iterate over every pair */
  563. for (i = 0; i < sic->nb_inputs; i++) {
  564. sc = &(sic->streamcontexts[i]);
  565. for (j = i+1; j < sic->nb_inputs; j++) {
  566. sc2 = &(sic->streamcontexts[j]);
  567. match = lookup_signatures(ctx, sic, sc, sc2, sic->mode);
  568. if (match.score != 0) {
  569. av_log(ctx, AV_LOG_INFO, "matching of video %d at %f and %d at %f, %d frames matching\n",
  570. i, ((double) match.first->pts * sc->time_base.num) / sc->time_base.den,
  571. j, ((double) match.second->pts * sc2->time_base.num) / sc2->time_base.den,
  572. match.matchframes);
  573. if (match.whole)
  574. av_log(ctx, AV_LOG_INFO, "whole video matching\n");
  575. } else {
  576. av_log(ctx, AV_LOG_INFO, "no matching of video %d and %d\n", i, j);
  577. }
  578. }
  579. }
  580. }
  581. return ret;
  582. }
  583. static av_cold int init(AVFilterContext *ctx)
  584. {
  585. SignatureContext *sic = ctx->priv;
  586. StreamContext *sc;
  587. int i, ret;
  588. char tmp[1024];
  589. sic->streamcontexts = av_mallocz(sic->nb_inputs * sizeof(StreamContext));
  590. if (!sic->streamcontexts)
  591. return AVERROR(ENOMEM);
  592. for (i = 0; i < sic->nb_inputs; i++) {
  593. AVFilterPad pad = {
  594. .type = AVMEDIA_TYPE_VIDEO,
  595. .name = av_asprintf("in%d", i),
  596. .config_props = config_input,
  597. .filter_frame = filter_frame,
  598. };
  599. if (!pad.name)
  600. return AVERROR(ENOMEM);
  601. sc = &(sic->streamcontexts[i]);
  602. sc->lastindex = 0;
  603. sc->finesiglist = av_mallocz(sizeof(FineSignature));
  604. if (!sc->finesiglist)
  605. return AVERROR(ENOMEM);
  606. sc->curfinesig = NULL;
  607. sc->coarsesiglist = av_mallocz(sizeof(CoarseSignature));
  608. if (!sc->coarsesiglist)
  609. return AVERROR(ENOMEM);
  610. sc->curcoarsesig1 = sc->coarsesiglist;
  611. sc->coarseend = sc->coarsesiglist;
  612. sc->coarsecount = 0;
  613. sc->midcoarse = 0;
  614. if ((ret = ff_insert_inpad(ctx, i, &pad)) < 0) {
  615. av_freep(&pad.name);
  616. return ret;
  617. }
  618. }
  619. /* check filename */
  620. if (sic->nb_inputs > 1 && strlen(sic->filename) > 0 && av_get_frame_filename(tmp, sizeof(tmp), sic->filename, 0) == -1) {
  621. av_log(ctx, AV_LOG_ERROR, "The filename must contain %%d or %%0nd, if you have more than one input.\n");
  622. return AVERROR(EINVAL);
  623. }
  624. return 0;
  625. }
  626. static av_cold void uninit(AVFilterContext *ctx)
  627. {
  628. SignatureContext *sic = ctx->priv;
  629. StreamContext *sc;
  630. void* tmp;
  631. FineSignature* finsig;
  632. CoarseSignature* cousig;
  633. int i;
  634. /* free the lists */
  635. if (sic->streamcontexts != NULL) {
  636. for (i = 0; i < sic->nb_inputs; i++) {
  637. sc = &(sic->streamcontexts[i]);
  638. finsig = sc->finesiglist;
  639. cousig = sc->coarsesiglist;
  640. while (finsig) {
  641. tmp = finsig;
  642. finsig = finsig->next;
  643. av_freep(&tmp);
  644. }
  645. sc->finesiglist = NULL;
  646. while (cousig) {
  647. tmp = cousig;
  648. cousig = cousig->next;
  649. av_freep(&tmp);
  650. }
  651. sc->coarsesiglist = NULL;
  652. }
  653. av_freep(&sic->streamcontexts);
  654. }
  655. }
  656. static int config_output(AVFilterLink *outlink)
  657. {
  658. AVFilterContext *ctx = outlink->src;
  659. AVFilterLink *inlink = ctx->inputs[0];
  660. outlink->time_base = inlink->time_base;
  661. outlink->frame_rate = inlink->frame_rate;
  662. outlink->sample_aspect_ratio = inlink->sample_aspect_ratio;
  663. outlink->w = inlink->w;
  664. outlink->h = inlink->h;
  665. return 0;
  666. }
  667. static const AVFilterPad signature_outputs[] = {
  668. {
  669. .name = "default",
  670. .type = AVMEDIA_TYPE_VIDEO,
  671. .request_frame = request_frame,
  672. .config_props = config_output,
  673. },
  674. { NULL }
  675. };
  676. AVFilter ff_vf_signature = {
  677. .name = "signature",
  678. .description = NULL_IF_CONFIG_SMALL("Calculate the MPEG-7 video signature"),
  679. .priv_size = sizeof(SignatureContext),
  680. .priv_class = &signature_class,
  681. .init = init,
  682. .uninit = uninit,
  683. .query_formats = query_formats,
  684. .outputs = signature_outputs,
  685. .inputs = NULL,
  686. .flags = AVFILTER_FLAG_DYNAMIC_INPUTS,
  687. };