737601e2d204198b36bf711311a92ff7837145bd
[goodguy/history.git] / cinelerra-5.1 / plugins / findobj / findobj.C
1
2 /*
3  * CINELERRA
4  * Copyright (C) 1997-2012 Adam Williams <broadcast at earthling dot net>
5  *
6  * This program 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  * This program 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
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 #include "affine.h"
22 #include "bccolors.h"
23 #include "clip.h"
24 #include "filexml.h"
25 #include "language.h"
26 #include "findobj.h"
27 #include "findobjwindow.h"
28 #include "mutex.h"
29 #include "overlayframe.h"
30 #include "plugin.h"
31 #include "pluginserver.h"
32 #include "track.h"
33
34 #include <errno.h>
35 #include <exception>
36 #include <unistd.h>
37
38 REGISTER_PLUGIN(FindObjMain)
39
40 FindObjConfig::FindObjConfig()
41 {
42         reset();
43 }
44
45 void FindObjConfig::reset()
46 {
47         algorithm = NO_ALGORITHM;
48         use_flann = 1;
49         mode = MODE_QUADRILATERAL;
50         draw_match = 0;
51         aspect = 1;
52         scale = 1;
53         translate = 1;
54         rotate = 1;
55         draw_keypoints = 0;
56         draw_scene_border = 0;
57         replace_object = 0;
58         draw_object_border = 0;
59         draw_replace_border = 0;
60         object_x = 50;  object_y = 50;
61         object_w = 100; object_h = 100;
62         drag_object = 0;
63         scene_x = 50;   scene_y = 50;
64         scene_w = 100;  scene_h = 100;
65         drag_replace = 0;
66         replace_x = 50;   replace_y = 50;
67         replace_w = 100;  replace_h = 100;
68         replace_dx = 0;   replace_dy = 0;
69         drag_scene = 0;
70         scene_layer = 0;
71         object_layer = 1;
72         replace_layer = 2;
73         blend = 100;
74 }
75
76 void FindObjConfig::boundaries()
77 {
78         bclamp(object_x, 0, 100);  bclamp(object_y, 0, 100);
79         bclamp(object_w, 0, 100);  bclamp(object_h, 0, 100);
80         bclamp(scene_x, 0, 100);   bclamp(scene_y, 0, 100);
81         bclamp(scene_w, 0, 100);   bclamp(scene_h, 0, 100);
82         bclamp(object_layer, MIN_LAYER, MAX_LAYER);
83         bclamp(replace_layer, MIN_LAYER, MAX_LAYER);
84         bclamp(scene_layer, MIN_LAYER, MAX_LAYER);
85         bclamp(blend, MIN_BLEND, MAX_BLEND);
86 }
87
88 int FindObjConfig::equivalent(FindObjConfig &that)
89 {
90         int result =
91                 algorithm == that.algorithm &&
92                 use_flann == that.use_flann &&
93                 mode == that.mode &&
94                 aspect == that.aspect &&
95                 scale == that.scale &&
96                 translate == that.translate &&
97                 rotate == that.rotate &&
98                 draw_keypoints == that.draw_keypoints &&
99                 draw_match == that.draw_match &&
100                 draw_scene_border == that.draw_scene_border &&
101                 replace_object == that.replace_object &&
102                 draw_object_border == that.draw_object_border &&
103                 draw_replace_border == that.draw_replace_border &&
104                 object_x == that.object_x && object_y == that.object_y &&
105                 object_w == that.object_w && object_h == that.object_h &&
106                 drag_object == that.drag_object &&
107                 scene_x == that.scene_x && scene_y == that.scene_y &&
108                 scene_w == that.scene_w && scene_h == that.scene_h &&
109                 drag_scene == that.drag_scene &&
110                 replace_x == that.replace_x && replace_y == that.replace_y &&
111                 replace_w == that.replace_w && replace_h == that.replace_h &&
112                 replace_dx == that.replace_dx && replace_dy == that.replace_dy &&
113                 drag_replace == that.drag_replace &&
114                 object_layer == that.object_layer &&
115                 replace_layer == that.replace_layer &&
116                 scene_layer == that.scene_layer &&
117                 blend == that.blend;
118         return result;
119 }
120
121 void FindObjConfig::copy_from(FindObjConfig &that)
122 {
123         algorithm = that.algorithm;
124         use_flann = that.use_flann;
125         mode = that.mode;
126         aspect = that.aspect;
127         scale = that.scale;
128         translate = that.translate;
129         rotate = that.rotate;
130         draw_keypoints = that.draw_keypoints;
131         draw_match = that.draw_match;
132         draw_scene_border = that.draw_scene_border;
133         replace_object = that.replace_object;
134         draw_object_border = that.draw_object_border;
135         draw_replace_border = that.draw_replace_border;
136         object_x = that.object_x;  object_y = that.object_y;
137         object_w = that.object_w;  object_h = that.object_h;
138         drag_object = that.drag_object;
139         scene_x = that.scene_x;    scene_y = that.scene_y;
140         scene_w = that.scene_w;    scene_h = that.scene_h;
141         drag_scene = that.drag_scene;
142         replace_x = that.replace_x;   replace_y = that.replace_y;
143         replace_w = that.replace_w;   replace_h = that.replace_h;
144         replace_dx = that.replace_dx; replace_dy = that.replace_dy;
145         drag_replace = that.drag_replace;
146         object_layer = that.object_layer;
147         replace_layer = that.replace_layer;
148         scene_layer = that.scene_layer;
149         blend = that.blend;
150 }
151
152 void FindObjConfig::interpolate(FindObjConfig &prev, FindObjConfig &next,
153         int64_t prev_frame, int64_t next_frame, int64_t current_frame)
154 {
155         copy_from(prev);
156 }
157
158
159 FindObjMain::FindObjMain(PluginServer *server)
160  : PluginVClient(server)
161 {
162         affine = 0;
163         overlayer = 0;
164
165         cvmodel = BC_RGB888;
166         w = h = 0;
167         object = scene = replace = 0;
168         object_x = object_y = 0;
169         object_w = object_h = 0;
170         scene_x = scene_y = 0;
171         scene_w = scene_h = 0;
172         object_layer = 0;
173         scene_layer = 1;
174         replace_layer = 2;
175
176         match_x1 = 0;  match_y1 = 0;
177         match_x2 = 0;  match_y2 = 0;
178         match_x3 = 0;  match_y3 = 0;
179         match_x4 = 0;  match_y4 = 0;
180         shape_x1 = 0;  shape_y1 = 0;
181         shape_x2 = 0;  shape_y2 = 0;
182         shape_x3 = 0;  shape_y3 = 0;
183         shape_x4 = 0;  shape_y4 = 0;
184         out_x1 = 0;    out_y1 = 0;
185         out_x2 = 0;    out_y2 = 0;
186         out_x3 = 0;    out_y3 = 0;
187         out_x4 = 0;    out_y4 = 0;
188
189         init_border = 1;
190 }
191
192 FindObjMain::~FindObjMain()
193 {
194         delete affine;
195         delete overlayer;
196 }
197
198 const char* FindObjMain::plugin_title() { return N_("FindObj"); }
199 int FindObjMain::is_realtime() { return 1; }
200 int FindObjMain::is_multichannel() { return 1; }
201
202 NEW_WINDOW_MACRO(FindObjMain, FindObjWindow)
203 LOAD_CONFIGURATION_MACRO(FindObjMain, FindObjConfig)
204
205 void FindObjMain::update_gui()
206 {
207         if( !thread ) return;
208         if( !load_configuration() ) return;
209         FindObjWindow *window = (FindObjWindow*)thread->window;
210         window->lock_window("FindObjMain::update_gui");
211         window->update_gui();
212         window->flush();
213         window->unlock_window();
214 }
215
216 void FindObjMain::save_data(KeyFrame *keyframe)
217 {
218         FileXML output;
219
220 // cause data to be stored directly in text
221         output.set_shared_output(keyframe->get_data(), MESSAGESIZE);
222         output.tag.set_title("FINDOBJ");
223         output.tag.set_property("ALGORITHM", config.algorithm);
224         output.tag.set_property("USE_FLANN", config.use_flann);
225         output.tag.set_property("MODE", config.mode);
226         output.tag.set_property("ASPECT", config.aspect);
227         output.tag.set_property("SCALE", config.scale);
228         output.tag.set_property("TRANSLATE", config.translate);
229         output.tag.set_property("ROTATE", config.rotate);
230         output.tag.set_property("DRAG_OBJECT", config.drag_object);
231         output.tag.set_property("OBJECT_X", config.object_x);
232         output.tag.set_property("OBJECT_Y", config.object_y);
233         output.tag.set_property("OBJECT_W", config.object_w);
234         output.tag.set_property("OBJECT_H", config.object_h);
235         output.tag.set_property("DRAG_SCENE", config.drag_scene);
236         output.tag.set_property("SCENE_X", config.scene_x);
237         output.tag.set_property("SCENE_Y", config.scene_y);
238         output.tag.set_property("SCENE_W", config.scene_w);
239         output.tag.set_property("SCENE_H", config.scene_h);
240         output.tag.set_property("DRAG_REPLACE", config.drag_replace);
241         output.tag.set_property("REPLACE_X", config.replace_x);
242         output.tag.set_property("REPLACE_Y", config.replace_y);
243         output.tag.set_property("REPLACE_W", config.replace_w);
244         output.tag.set_property("REPLACE_H", config.replace_h);
245         output.tag.set_property("REPLACE_DX", config.replace_dx);
246         output.tag.set_property("REPLACE_DY", config.replace_dy);
247         output.tag.set_property("DRAW_KEYPOINTS", config.draw_keypoints);
248         output.tag.set_property("DRAW_MATCH", config.draw_match);
249         output.tag.set_property("DRAW_SCENE_BORDER", config.draw_scene_border);
250         output.tag.set_property("REPLACE_OBJECT", config.replace_object);
251         output.tag.set_property("DRAW_OBJECT_BORDER", config.draw_object_border);
252         output.tag.set_property("DRAW_REPLACE_BORDER", config.draw_replace_border);
253         output.tag.set_property("OBJECT_LAYER", config.object_layer);
254         output.tag.set_property("REPLACE_LAYER", config.replace_layer);
255         output.tag.set_property("SCENE_LAYER", config.scene_layer);
256         output.tag.set_property("BLEND", config.blend);
257         output.append_tag();
258         output.tag.set_title("/FINDOBJ");
259         output.append_tag();
260         output.append_newline();
261         output.terminate_string();
262 }
263
264 void FindObjMain::read_data(KeyFrame *keyframe)
265 {
266         FileXML input;
267
268         input.set_shared_input(keyframe->get_data(), strlen(keyframe->get_data()));
269
270         int result = 0;
271
272         while( !(result = input.read_tag()) ) {
273                 if( input.tag.title_is("FINDOBJ") ) {
274                         config.algorithm = input.tag.get_property("ALGORITHM", config.algorithm);
275                         config.use_flann = input.tag.get_property("USE_FLANN", config.use_flann);
276                         config.mode = input.tag.get_property("MODE", config.mode);
277                         config.aspect = input.tag.get_property("ASPECT", config.aspect);
278                         config.scale = input.tag.get_property("SCALE", config.scale);
279                         config.translate = input.tag.get_property("TRANSLATE", config.translate);
280                         config.rotate = input.tag.get_property("ROTATE", config.rotate);
281                         config.object_x = input.tag.get_property("OBJECT_X", config.object_x);
282                         config.object_y = input.tag.get_property("OBJECT_Y", config.object_y);
283                         config.object_w = input.tag.get_property("OBJECT_W", config.object_w);
284                         config.object_h = input.tag.get_property("OBJECT_H", config.object_h);
285                         config.drag_object = input.tag.get_property("DRAG_OBJECT", config.drag_object);
286                         config.scene_x = input.tag.get_property("SCENE_X", config.scene_x);
287                         config.scene_y = input.tag.get_property("SCENE_Y", config.scene_y);
288                         config.scene_w = input.tag.get_property("SCENE_W", config.scene_w);
289                         config.scene_h = input.tag.get_property("SCENE_H", config.scene_h);
290                         config.drag_scene = input.tag.get_property("DRAG_SCENE", config.drag_scene);
291                         config.replace_x = input.tag.get_property("REPLACE_X", config.replace_x);
292                         config.replace_y = input.tag.get_property("REPLACE_Y", config.replace_y);
293                         config.replace_w = input.tag.get_property("REPLACE_W", config.replace_w);
294                         config.replace_h = input.tag.get_property("REPLACE_H", config.replace_h);
295                         config.replace_dx = input.tag.get_property("REPLACE_DX", config.replace_dx);
296                         config.replace_dy = input.tag.get_property("REPLACE_DY", config.replace_dy);
297                         config.drag_replace = input.tag.get_property("DRAG_REPLACE", config.drag_replace);
298                         config.draw_keypoints = input.tag.get_property("DRAW_KEYPOINTS", config.draw_keypoints);
299                         config.draw_match = input.tag.get_property("DRAW_MATCH", config.draw_match);
300                         config.draw_scene_border = input.tag.get_property("DRAW_SCENE_BORDER", config.draw_scene_border);
301                         config.replace_object = input.tag.get_property("REPLACE_OBJECT", config.replace_object);
302                         config.draw_object_border = input.tag.get_property("DRAW_OBJECT_BORDER", config.draw_object_border);
303                         config.draw_replace_border = input.tag.get_property("DRAW_REPLACE_BORDER", config.draw_replace_border);
304                         config.object_layer = input.tag.get_property("OBJECT_LAYER", config.object_layer);
305                         config.replace_layer = input.tag.get_property("REPLACE_LAYER", config.replace_layer);
306                         config.scene_layer = input.tag.get_property("SCENE_LAYER", config.scene_layer);
307                         config.blend = input.tag.get_property("BLEND", config.blend);
308                 }
309         }
310
311         config.boundaries();
312 }
313
314 void FindObjMain::draw_line(VFrame *vframe, int x1, int y1, int x2, int y2)
315 {
316         vframe->draw_line(x1, y1, x2, y2);
317 }
318
319 void FindObjMain::draw_quad(VFrame *vframe,
320                 int x1, int y1, int x2, int y2,
321                 int x3, int y3, int x4, int y4)
322 {
323         int r = bmin(vframe->get_w(), vframe->get_h()) / 200 + 1;
324         for( int i=r; --i>0; ) {
325                 draw_line(vframe, x1+i, y1+i, x2, y2);
326                 draw_line(vframe, x1-i, y1-i, x2, y2);
327                 draw_line(vframe, x2+i, y2+i, x3, y3);
328                 draw_line(vframe, x2-i, y2-i, x3, y3);
329                 draw_line(vframe, x3+i, y3+i, x4, y4);
330                 draw_line(vframe, x3-i, y3-i, x4, y4);
331                 draw_line(vframe, x4+i, y4+i, x1, y1);
332                 draw_line(vframe, x4-i, y4-i, x1, y1);
333         }
334         draw_line(vframe, x1, y1, x2, y2);
335         draw_line(vframe, x2, y2, x3, y3);
336         draw_line(vframe, x3, y3, x4, y4);
337         draw_line(vframe, x4, y4, x1, y1);
338         for( int i=r; --i>0; )
339                 draw_circle(vframe, x1, y1, i);
340 }
341
342 void FindObjMain::draw_rect(VFrame *vframe, int x1, int y1, int x2, int y2)
343 {
344         int r = bmin(vframe->get_w(), vframe->get_h()) / 200 + 1;
345         for( int i=r; --i>0; ) {
346                 --x2;  --y2;
347                 draw_line(vframe, x1, y1, x2, y1);
348                 draw_line(vframe, x2, y1, x2, y2);
349                 draw_line(vframe, x2, y2, x1, y2);
350                 draw_line(vframe, x1, y2, x1, y1);
351                 ++x1;  ++y1;
352         }
353 }
354
355 void FindObjMain::draw_circle(VFrame *vframe, int x, int y, int r)
356 {
357         int x1 = x-r, x2 = x+r;
358         int y1 = y-r, y2 = y+r;
359         vframe->draw_smooth(x1,y, x1,y1, x,y1);
360         vframe->draw_smooth(x,y1, x2,y1, x2,y);
361         vframe->draw_smooth(x2,y, x2,y2, x,y2);
362         vframe->draw_smooth(x,y2, x1,y2, x1,y);
363 }
364
365 void FindObjMain::filter_matches(ptV &p1, ptV &p2, double ratio)
366 {
367         DMatches::iterator it;
368         for( it=pairs.begin(); it!=pairs.end(); ++it ) { 
369                 DMatchV &m = *it;
370                 if( m.size() == 2 && m[0].distance < m[1].distance*ratio ) {
371                         p1.push_back(obj_keypts[m[0].queryIdx].pt);
372                         p2.push_back(scn_keypts[m[0].trainIdx].pt);
373                 }
374         }
375 }
376
377 void FindObjMain::to_mat(Mat &mat, int mcols, int mrows,
378         VFrame *inp, int ix,int iy, BC_CModel mcolor_model)
379 {
380         int mcomp = BC_CModels::components(mcolor_model);
381         int mbpp = BC_CModels::calculate_pixelsize(mcolor_model);
382         int psz = mbpp / mcomp;
383         int mdepth = psz < 2 ? CV_8U : CV_16U;
384         if( mat.dims != 2 || mat.depth() != mdepth || mat.channels() != mcomp ||
385             mat.cols != mcols || mat.rows != mrows ) {
386                 mat.release();
387         }
388         if( mat.empty() ) {
389                 int type = CV_MAKETYPE(mdepth, mcomp);
390                 mat.create(mrows, mcols, type);
391         }
392         uint8_t *mat_rows[mrows];
393         for( int y=0; y<mrows; ++y ) mat_rows[y] = mat.ptr(y);
394         uint8_t **inp_rows = inp->get_rows();
395         int ibpl = inp->get_bytes_per_line(), obpl = mcols * mbpp;
396         int icolor_model = inp->get_color_model();
397         BC_CModels::transfer(mat_rows, mcolor_model, 0,0, mcols,mrows, obpl,
398                 inp_rows, icolor_model, ix,iy, mcols,mrows, ibpl, 0);
399 //      VFrame vfrm(mat_rows[0], -1, mcols,mrows, mcolor_model, mat_rows[1]-mat_rows[0]);
400 //      static int vfrm_no = 0; char vfn[64]; sprintf(vfn,"/tmp/dat/%06d.png", vfrm_no++);
401 //      vfrm.write_png(vfn);
402 }
403
404 void FindObjMain::detect(Mat &mat, KeyPointV &keypts,Mat &descrs)
405 {
406         keypts.clear();
407         descrs.release();
408         try {
409                 detector->detectAndCompute(mat, noArray(), keypts, descrs);
410         } catch(std::exception e) { printf(_("detector exception: %s\n"), e.what()); }
411 }
412
413 void FindObjMain::match()
414 {
415         pairs.clear();
416         try {
417                 matcher->knnMatch(obj_descrs, scn_descrs, pairs, 2);
418         } catch(std::exception e) { printf(_("match execption: %s\n"), e.what()); }
419 }
420
421 Ptr<DescriptorMatcher> FindObjMain::flann_kdtree_matcher()
422 { // trees=5
423         const Ptr<flann::IndexParams>& indexParams =
424                 makePtr<flann::KDTreeIndexParams>(5);
425         const Ptr<flann::SearchParams>& searchParams =
426                 makePtr<flann::SearchParams>();
427         return makePtr<FlannBasedMatcher>(indexParams, searchParams);
428 }
429 Ptr<DescriptorMatcher> FindObjMain::flann_lshidx_matcher()
430 { // table_number = 6#12, key_size = 12#20, multi_probe_level = 1#2
431         const Ptr<flann::IndexParams>& indexParams =
432                 makePtr<flann::LshIndexParams>(6, 12, 1);
433         const Ptr<flann::SearchParams>& searchParams =
434                 makePtr<flann::SearchParams>();
435         return makePtr<FlannBasedMatcher>(indexParams, searchParams);
436 }
437 Ptr<DescriptorMatcher> FindObjMain::bf_matcher_norm_l2()
438 {
439         return BFMatcher::create(NORM_L2);
440 }
441 Ptr<DescriptorMatcher> FindObjMain::bf_matcher_norm_hamming()
442 {
443         return BFMatcher::create(NORM_HAMMING);
444 }
445
446 #ifdef _SIFT
447 void FindObjMain::set_sift()
448 {
449         cvmodel = BC_GREY8;
450         detector = SIFT::create();
451         matcher = config.use_flann ?
452                 flann_kdtree_matcher() : bf_matcher_norm_l2();
453 }
454 #endif
455 #ifdef _SURF
456 void FindObjMain::set_surf()
457 {
458         cvmodel = BC_GREY8;
459         detector = SURF::create(800);
460         matcher = config.use_flann ?
461                 flann_kdtree_matcher() : bf_matcher_norm_l2();
462 }
463 #endif
464 #ifdef _ORB
465 void FindObjMain::set_orb()
466 {
467         cvmodel = BC_GREY8;
468         detector = ORB::create();
469         matcher = config.use_flann ?
470                 flann_lshidx_matcher() : bf_matcher_norm_hamming();
471 }
472 #endif
473 #ifdef _AKAZE
474 void FindObjMain::set_akaze()
475 {
476         cvmodel = BC_GREY8;
477         detector = AKAZE::create();
478         matcher = config.use_flann ?
479                 flann_lshidx_matcher() : bf_matcher_norm_hamming();
480 }
481 #endif
482 #ifdef _BRISK
483 void FindObjMain::set_brisk()
484 {
485         cvmodel = BC_GREY8;
486         detector = BRISK::create();
487         matcher = config.use_flann ?
488                 flann_lshidx_matcher() : bf_matcher_norm_hamming();
489 }
490 #endif
491
492
493 void FindObjMain::process_match()
494 {
495         if( config.algorithm == NO_ALGORITHM ) return;
496
497         if( detector.empty() ) {
498                 switch( config.algorithm ) {
499 #ifdef _SIFT
500                 case ALGORITHM_SIFT:   set_sift();   break;
501 #endif
502 #ifdef _SURF
503                 case ALGORITHM_SURF:   set_surf();   break;
504 #endif
505 #ifdef _ORB
506                 case ALGORITHM_ORB:    set_orb();    break;
507 #endif
508 #ifdef _AKAZE
509                 case ALGORITHM_AKAZE:  set_akaze();  break;
510 #endif
511 #ifdef _BRISK
512                 case ALGORITHM_BRISK:  set_brisk();  break;
513 #endif
514                 }
515                 obj_keypts.clear();  obj_descrs.release();
516                 to_mat(object_mat, object_w,object_h, object, object_x,object_y, cvmodel);
517                 detect(object_mat, obj_keypts, obj_descrs);
518 //printf("detect obj %d features\n", (int)obj_keypts.size());
519         }
520
521         to_mat(scene_mat, scene_w,scene_h, scene, scene_x,scene_y, cvmodel);
522         detect(scene_mat, scn_keypts, scn_descrs);
523 //printf("detect scn %d features\n", (int)scn_keypts.size());
524         match();
525         ptV p1, p2;
526         filter_matches(p1, p2);
527         if( p1.size() < 4 ) return;
528         Mat H = findHomography(p1, p2, RANSAC, 5.0);
529         if( !H.dims || !H.rows || !H.cols ) {
530 //printf("fail, size p1=%d,p2=%d\n",(int)p1.size(),(int)p2.size());
531                 return;
532         }
533
534         ptV src, dst;
535         float out_x1 = 0, out_x2 = object_w;
536         float out_y1 = 0, out_y2 = object_h;
537         src.push_back(Point2f(out_x1,out_y1));
538         src.push_back(Point2f(out_x2,out_y1));
539         src.push_back(Point2f(out_x2,out_y2));
540         src.push_back(Point2f(out_x1,out_y2));
541         perspectiveTransform(src, dst, H);
542
543         match_x1 = dst[0].x + scene_x;  match_y1 = dst[0].y + scene_y;
544         match_x2 = dst[1].x + scene_x;  match_y2 = dst[1].y + scene_y;
545         match_x3 = dst[2].x + scene_x;  match_y3 = dst[2].y + scene_y;
546         match_x4 = dst[3].x + scene_x;  match_y4 = dst[3].y + scene_y;
547 }
548
549
550 static double area(float x1, float y1, float x2, float y2,
551                 float x3, float y3, float x4, float y4)
552 { // quadrelateral area, sign is +ccw,-cw, use abs
553         double dx1 = x3-x1, dy1 = y3-y1;
554         double dx2 = x4-x2, dy2 = y4-y2;
555         return 0.5 * (dx1 * dy2 - dx2 * dy1);
556 }
557 static double dist(float x1,float y1, float x2, float y2)
558 {
559         double dx = x2-x1, dy = y2-y1;
560         return sqrt(dx*dx + dy*dy);
561 }
562 static int intersects(double x1, double y1, double x2, double y2,
563                 double x3, double y3, double x4, double y4)
564 {
565         double dx12 = x2 - x1, dy12 = y2 - y1;
566         double dx34 = x4 - x3, dy34 = y4 - y3;
567         double d = dx12*dy34 - dx34*dy12;
568         if( !d ) return 0; // parallel
569         double dx13 = x3 - x1, dy13 = y3 - y1;
570         double u = (dx13*dy34 - dx34*dy13) / d;
571         if( u < 0 || u > 1 ) return 0;
572         double v = (dx13*dy12 - dx12*dy13) / d;
573         if( v < 0 || v > 1 ) return 0;
574         return 1;
575 }
576
577 /*
578  * 4---------3    1---------2
579  * |0,h   w,h|    |0,0   w,0|
580  * |    +    |    |    +    |
581  * |0,0   w,0|    |0,h   w,h|
582  * 1---------2    1---------2
583  * pt locations    screen pts
584  */
585 void FindObjMain::reshape()
586 {
587         if( config.mode == MODE_NONE ) return;
588         const double pi = M_PI;
589         double x1 = match_x1, y1 = match_y1;
590         double x2 = match_x2, y2 = match_y2;
591         double x3 = match_x3, y3 = match_y3;
592         double x4 = match_x4, y4 = match_y4;
593         double ia = area(x1,y1, x2,y2, x3,y3, x4,y4);
594 // centroid
595         double cx = (x1 + x2 + x3 + x4) / 4;
596         double cy = (y1 + y2 + y3 + y4) / 4;
597 // centered
598         x1 -= cx;  x2 -= cx;  x3 -= cx;  x4 -= cx;
599         y1 -= cy;  y2 -= cy;  y3 -= cy;  y4 -= cy;
600 // bowtied
601         if( intersects(x1,y1, x2,y2, x3,y3, x4,y4) ) {
602                 double x = x2, y = y2;
603                 x2 = x3;  y2 = y3;
604                 x3 = x;   y3 = y;
605         }
606         else if( intersects(x1,y1, x4,y4, x3,y3, x2,y2) ) {
607                 double x = x4, y = y4;
608                 x4 = x3;  y4 = y3;
609                 x3 = x;   y3 = y;
610         }
611
612 // rotation, if mode is quad: reverse rotate
613         double r = 0;
614         if( (config.mode == MODE_QUADRILATERAL) ^ (config.rotate != 0) ) {
615 // edge centers
616                 double cx12 = (x1 + x2) / 2, cy12 = (y1 + y2) / 2;
617                 double cx23 = (x2 + x3) / 2, cy23 = (y2 + y3) / 2;
618                 double cx34 = (x3 + x4) / 2, cy34 = (y3 + y4) / 2;
619                 double cx41 = (x4 + x1) / 2, cy41 = (y4 + y1) / 2;
620                 double vx = cx34 - cx12, vy = cy34 - cy12;
621                 double hx = cx23 - cx41, hy = cy23 - cy41;
622                 double v = atan2(vy, vx);
623                 double h = atan2(hy, hx);
624                 r = (h + v - pi/2) / 2;
625         }
626 // diagonal length
627         double a = dist(x1,y1, x3,y3) / 2;
628         double b = dist(x2,y2, x4,y4) / 2;
629         if( config.mode == MODE_SQUARE ||
630             config.mode == MODE_RECTANGLE )
631                 a = b = (a + b) / 2;
632 // central angles
633         double a1 = atan2(y1, x1);
634         double a2 = atan2(y2, x2);
635         double a3 = atan2(y3, x3);
636         double a4 = atan2(y4, x4);
637 // edge angles
638         double a12 = a2 - a1, a23 = a3 - a2;
639         double a34 = a4 - a3, a41 = a1 - a4;
640         double dt = (a12 - a23 + a34 - a41)/4;
641 // mirrored
642         if( ia < 0 ) { ia = -ia;  dt = -dt;  r = -r; }
643         switch( config.mode ) {
644         case MODE_SQUARE:
645         case MODE_RHOMBUS:
646                 dt = pi/2;
647         case MODE_RECTANGLE:
648         case MODE_PARALLELOGRAM: {
649                 double t = -(pi+dt)/2;
650                 x1 = a*cos(t);  y1 = a*sin(t);  t += dt;
651                 x2 = b*cos(t);  y2 = b*sin(t);  t += pi - dt;
652                 x3 = a*cos(t);  y3 = a*sin(t);  t += dt;
653                 x4 = b*cos(t);  y4 = b*sin(t); }
654         case MODE_QUADRILATERAL:
655                 break;
656         }
657 // aspect
658         if( !config.aspect ) {
659                 double cx12 = (x1 + x2) / 2, cy12 = (y1 + y2) / 2;
660                 double cx23 = (x2 + x3) / 2, cy23 = (y2 + y3) / 2;
661                 double cx34 = (x3 + x4) / 2, cy34 = (y3 + y4) / 2;
662                 double cx41 = (x4 + x1) / 2, cy41 = (y4 + y1) / 2;
663                 double iw = dist(cx41,cy41, cx23,cy23);
664                 double ih = dist(cx12,cy12, cx34,cy34);
665                 double ow = object_w, oh = object_h;
666                 double sx = iw && ih ? sqrt((ih*ow)/(iw*oh)) : 1;
667                 double sy = sx ? 1 / sx : 1;
668                 x1 *= sx;  x2 *= sx;  x3 *= sx;  x4 *= sx;
669                 y1 *= sy;  y2 *= sy;  y3 *= sy;  y4 *= sy;
670         }
671 // rotation
672         if( r ) {
673                 double ct = cos(r), st = sin(r), x, y;
674                 x = x1*ct + y1*st;  y = y1*ct - x1*st;  x1 = x;  y1 = y;
675                 x = x2*ct + y2*st;  y = y2*ct - x2*st;  x2 = x;  y2 = y;
676                 x = x3*ct + y3*st;  y = y3*ct - x3*st;  x3 = x;  y3 = y;
677                 x = x4*ct + y4*st;  y = y4*ct - x4*st;  x4 = x;  y4 = y;
678         }
679 // scaling
680         ia = !config.scale ? object_w * object_h : ia;
681         double oa = abs(area(x1,y1, x2,y2, x3,y3, x4,y4));
682         double sf =  oa ? sqrt(ia / oa) : 0;
683         x1 *= sf;  x2 *= sf;  x3 *= sf;  x4 *= sf;
684         y1 *= sf;  y2 *= sf;  y3 *= sf;  y4 *= sf;
685 // translation
686         double ox = !config.translate ? object_x + object_w/2. : cx;
687         double oy = !config.translate ? object_y + object_h/2. : cy;
688         x1 += ox;  x2 += ox;  x3 += ox;  x4 += ox;
689         y1 += oy;  y2 += oy;  y3 += oy;  y4 += oy;
690
691         shape_x1 = x1;  shape_y1 = y1;
692         shape_x2 = x2;  shape_y2 = y2;
693         shape_x3 = x3;  shape_y3 = y3;
694         shape_x4 = x4;  shape_y4 = y4;
695 }
696
697 int FindObjMain::process_buffer(VFrame **frame, int64_t start_position, double frame_rate)
698 {
699         int prev_algorithm = config.algorithm;
700         int prev_use_flann = config.use_flann;
701
702         if( load_configuration() )
703                 init_border = 1;
704
705         if( prev_algorithm != config.algorithm ||
706             prev_use_flann != config.use_flann ) {
707                 detector.release();
708                 matcher.release();
709         }
710
711         object_layer = config.object_layer;
712         scene_layer = config.scene_layer;
713         replace_layer = config.replace_layer;
714         Track *track = server->plugin->track;
715         w = track->track_w;
716         h = track->track_h;
717
718         int max_layer = PluginClient::get_total_buffers() - 1;
719         object_layer = bclip(config.object_layer, 0, max_layer);
720         scene_layer = bclip(config.scene_layer, 0, max_layer);
721         replace_layer = bclip(config.replace_layer, 0, max_layer);
722
723         int cfg_w = (int)(w * config.object_w / 100.);
724         int cfg_h = (int)(h * config.object_h / 100.);
725         int cfg_x1 = (int)(w * config.object_x / 100. - cfg_w / 2);
726         int cfg_y1 = (int)(h * config.object_y / 100. - cfg_h / 2);
727         int cfg_x2 = cfg_x1 + cfg_w;
728         int cfg_y2 = cfg_y1 + cfg_h;
729         bclamp(cfg_x1, 0, w);  object_x = cfg_x1;
730         bclamp(cfg_y1, 0, h);  object_y = cfg_y1;
731         bclamp(cfg_x2, 0, w);  object_w = cfg_x2 - cfg_x1;
732         bclamp(cfg_y2, 0, h);  object_h = cfg_y2 - cfg_y1;
733
734         cfg_w = (int)(w * config.scene_w / 100.);
735         cfg_h = (int)(h * config.scene_h / 100.);
736         cfg_x1 = (int)(w * config.scene_x / 100. - cfg_w / 2);
737         cfg_y1 = (int)(h * config.scene_y / 100. - cfg_h / 2);
738         cfg_x2 = cfg_x1 + cfg_w;
739         cfg_y2 = cfg_y1 + cfg_h;
740         bclamp(cfg_x1, 0, w);  scene_x = cfg_x1;
741         bclamp(cfg_y1, 0, h);  scene_y = cfg_y1;
742         bclamp(cfg_x2, 0, w);  scene_w = cfg_x2 - cfg_x1;
743         bclamp(cfg_y2, 0, h);  scene_h = cfg_y2 - cfg_y1;
744
745         cfg_w = (int)(w * config.replace_w / 100.);
746         cfg_h = (int)(h * config.replace_h / 100.);
747         cfg_x1 = (int)(w * config.replace_x / 100. - cfg_w / 2);
748         cfg_y1 = (int)(h * config.replace_y / 100. - cfg_h / 2);
749         cfg_x2 = cfg_x1 + cfg_w;
750         cfg_y2 = cfg_y1 + cfg_h;
751         bclamp(cfg_x1, 0, w);  replace_x = cfg_x1;
752         bclamp(cfg_y1, 0, h);  replace_y = cfg_y1;
753         bclamp(cfg_x2, 0, w);  replace_w = cfg_x2 - cfg_x1;
754         bclamp(cfg_y2, 0, h);  replace_h = cfg_y2 - cfg_y1;
755
756         int cfg_dx = (int)(w * config.replace_dx / 100.);
757         int cfg_dy = (int)(h * config.replace_dy / 100.);
758         bclamp(cfg_dx, -h, h);  replace_dx = cfg_dx;
759         bclamp(cfg_dy, -w, w);  replace_dy = cfg_dy;
760
761 // Read in the input frames
762         for( int i = 0; i < PluginClient::get_total_buffers(); i++ ) {
763                 read_frame(frame[i], i, start_position, frame_rate, 0);
764         }
765
766         object = frame[object_layer];
767         scene = frame[scene_layer];
768         replace = frame[replace_layer];
769
770         shape_x1 = out_x1;  shape_y1 = out_y1;
771         shape_x2 = out_x2;  shape_y2 = out_y2;
772         shape_x3 = out_x3;  shape_y3 = out_y3;
773         shape_x4 = out_x4;  shape_y4 = out_y4;
774
775         if( scene_w > 0 && scene_h > 0 && object_w > 0 && object_h > 0 ) {
776                 process_match();
777                 reshape();
778         }
779
780         double w0 = init_border ? 1. : config.blend/100., w1 = 1. - w0;
781         init_border = 0;
782         out_x1 = shape_x1*w0 + out_x1*w1;  out_y1 = shape_y1*w0 + out_y1*w1;
783         out_x2 = shape_x2*w0 + out_x2*w1;  out_y2 = shape_y2*w0 + out_y2*w1;
784         out_x3 = shape_x3*w0 + out_x3*w1;  out_y3 = shape_y3*w0 + out_y3*w1;
785         out_x4 = shape_x4*w0 + out_x4*w1;  out_y4 = shape_y4*w0 + out_y4*w1;
786 // Replace object in the scene layer
787         if( config.replace_object ) {
788                 int cpus1 = get_project_smp() + 1;
789                 if( !affine )
790                         affine = new AffineEngine(cpus1, cpus1);
791                 if( !overlayer )
792                         overlayer = new OverlayFrame(cpus1);
793                 VFrame *temp = new_temp(w, h, scene->get_color_model());
794                 temp->clear_frame();
795                 affine->set_in_viewport(replace_x, replace_y, replace_w, replace_h);
796                 float ix1 = replace_x, ix2 = ix1 + replace_w;
797                 float iy1 = replace_y, iy2 = iy1 + replace_h;
798                 float dx = replace_dx, dy = replace_dy;
799                 float ox1 = out_x1+dx, ox2 = out_x2+dx, ox3 = out_x3+dx, ox4 = out_x4+dx;
800                 float oy1 = out_y1-dy, oy2 = out_y2-dy, oy3 = out_y3-dy, oy4 = out_y4-dy;
801                 affine->set_matrix(ix1,iy1, ix2,iy2, ox1,oy1, ox2,oy2, ox4,oy4, ox3,oy3);
802                 affine->process(temp, replace, 0,
803                         AffineEngine::TRANSFORM, 0,0, 100,0, 100,100, 0,100, 1);
804                 overlayer->overlay(scene, temp,  0,0, w,h,  0,0, w,h,
805                         1, TRANSFER_NORMAL, NEAREST_NEIGHBOR);
806
807         }
808
809         int wh = (w+h)>>8, ss = 1; while( wh>>=1 ) ss<<=1;
810         if( config.draw_scene_border ) {
811                 scene->set_stiple(ss*2);
812                 scene->set_pixel_color(WHITE);
813                 draw_rect(scene, scene_x, scene_y, scene_x+scene_w, scene_y+scene_h);
814         }
815         if( config.draw_object_border ) {
816                 scene->set_stiple(ss*3);
817                 scene->set_pixel_color(YELLOW); 
818                 draw_rect(scene, object_x, object_y, object_x+object_w, object_y+object_h);
819         }
820         if( config.draw_replace_border ) {
821                 scene->set_stiple(ss*3);
822                 scene->set_pixel_color(GREEN);
823                 draw_rect(scene, replace_x, replace_y, replace_x+replace_w, replace_y+replace_h);
824         }
825         scene->set_stiple(0);
826         if( config.draw_keypoints ) {
827                 scene->set_pixel_color(GREEN);
828                 for( int i=0,n=obj_keypts.size(); i<n; ++i ) {
829                         Point2f &pt = obj_keypts[i].pt;
830                         int r = obj_keypts[i].size * 1.2/9 * 2;
831                         int x = pt.x + object_x, y = pt.y + object_y;
832                         draw_circle(scene, x, y, r);
833                 }
834                 scene->set_pixel_color(RED);
835                 for( int i=0,n=scn_keypts.size(); i<n; ++i ) {
836                         Point2f &pt = scn_keypts[i].pt;
837                         int r = scn_keypts[i].size * 1.2/9 * 2;
838                         int x = pt.x + scene_x, y = pt.y + scene_y;
839                         draw_circle(scene, x, y, r);
840                 }
841         }
842         if( config.draw_match ) {
843                 scene->set_pixel_color(BLUE);
844                 draw_quad(scene, match_x1, match_y1, match_x2, match_y2,
845                                 match_x3, match_y3, match_x4, match_y4);
846         }
847
848         if( gui_open() ) {
849                 if( config.drag_scene ) {
850                         scene->set_pixel_color(WHITE);
851                         DragCheckBox::draw_boundary(scene, scene_x, scene_y, scene_w, scene_h);
852                 }
853                 if( config.drag_object ) {
854                         scene->set_pixel_color(YELLOW);
855                         DragCheckBox::draw_boundary(scene, object_x, object_y, object_w, object_h);
856                 }
857                 if( config.drag_replace ) {
858                         scene->set_pixel_color(GREEN);
859                         DragCheckBox::draw_boundary(scene, replace_x, replace_y, replace_w, replace_h);
860                 }
861         }
862
863         scene->set_pixel_color(BLACK);
864         scene->set_stiple(0);
865         return 0;
866 }
867