vf_deshake_opencl.c 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166
  1. /*
  2. * This file is part of FFmpeg.
  3. *
  4. * FFmpeg is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Lesser General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 2.1 of the License, or (at your option) any later version.
  8. *
  9. * FFmpeg is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Lesser General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Lesser General Public
  15. * License along with FFmpeg; if not, write to the Free Software
  16. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. *
  18. * Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
  19. * Copyright (C) 2009, Willow Garage Inc., all rights reserved.
  20. * Copyright (C) 2013, OpenCV Foundation, all rights reserved.
  21. * Third party copyrights are property of their respective owners.
  22. *
  23. * Redistribution and use in source and binary forms, with or without modification,
  24. * are permitted provided that the following conditions are met:
  25. *
  26. * * Redistribution's of source code must retain the above copyright notice,
  27. * this list of conditions and the following disclaimer.
  28. *
  29. * * Redistribution's in binary form must reproduce the above copyright notice,
  30. * this list of conditions and the following disclaimer in the documentation
  31. * and/or other materials provided with the distribution.
  32. *
  33. * * The name of the copyright holders may not be used to endorse or promote products
  34. * derived from this software without specific prior written permission.
  35. *
  36. * This software is provided by the copyright holders and contributors "as is" and
  37. * any express or implied warranties, including, but not limited to, the implied
  38. * warranties of merchantability and fitness for a particular purpose are disclaimed.
  39. * In no event shall the Intel Corporation or contributors be liable for any direct,
  40. * indirect, incidental, special, exemplary, or consequential damages
  41. * (including, but not limited to, procurement of substitute goods or services;
  42. * loss of use, data, or profits; or business interruption) however caused
  43. * and on any theory of liability, whether in contract, strict liability,
  44. * or tort (including negligence or otherwise) arising in any way out of
  45. * the use of this software, even if advised of the possibility of such damage.
  46. */
  47. #include <float.h>
  48. #include <libavutil/lfg.h>
  49. #include "libavutil/opt.h"
  50. #include "libavutil/mem.h"
  51. #include "libavutil/fifo.h"
  52. #include "libavutil/common.h"
  53. #include "libavutil/avassert.h"
  54. #include "libavutil/pixdesc.h"
  55. #include "libavutil/pixfmt.h"
  56. #include "avfilter.h"
  57. #include "framequeue.h"
  58. #include "filters.h"
  59. #include "transform.h"
  60. #include "internal.h"
  61. #include "opencl.h"
  62. #include "opencl_source.h"
  63. #include "video.h"
  64. /*
  65. This filter matches feature points between frames (dealing with outliers) and then
  66. uses the matches to estimate an affine transform between frames. This transform is
  67. decomposed into various values (translation, scale, rotation) and the values are
  68. summed relative to the start of the video to obtain on absolute camera position
  69. for each frame. This "camera path" is then smoothed via a gaussian filter, resulting
  70. in a new path that is turned back into an affine transform and applied to each
  71. frame to render it.
  72. High-level overview:
  73. All of the work to extract motion data from frames occurs in queue_frame. Motion data
  74. is buffered in a smoothing window, so queue_frame simply computes the absolute camera
  75. positions and places them in ringbuffers.
  76. filter_frame is responsible for looking at the absolute camera positions currently
  77. in the ringbuffers, applying the gaussian filter, and then transforming the frames.
  78. */
  79. // Number of bits for BRIEF descriptors
  80. #define BREIFN 512
  81. // Size of the patch from which a BRIEF descriptor is extracted
  82. // This is the size used in OpenCV
  83. #define BRIEF_PATCH_SIZE 31
  84. #define BRIEF_PATCH_SIZE_HALF (BRIEF_PATCH_SIZE / 2)
  85. #define MATCHES_CONTIG_SIZE 2000
  86. #define ROUNDED_UP_DIV(a, b) ((a + (b - 1)) / b)
  87. typedef struct PointPair {
  88. // Previous frame
  89. cl_float2 p1;
  90. // Current frame
  91. cl_float2 p2;
  92. } PointPair;
  93. typedef struct MotionVector {
  94. PointPair p;
  95. // Used to mark vectors as potential outliers
  96. cl_int should_consider;
  97. } MotionVector;
  98. // Denotes the indices for the different types of motion in the ringbuffers array
  99. enum RingbufferIndices {
  100. RingbufX,
  101. RingbufY,
  102. RingbufRot,
  103. RingbufScaleX,
  104. RingbufScaleY,
  105. // Should always be last
  106. RingbufCount
  107. };
  108. // Struct that holds data for drawing point match debug data
  109. typedef struct DebugMatches {
  110. MotionVector *matches;
  111. // The points used to calculate the affine transform for a frame
  112. MotionVector model_matches[3];
  113. int num_matches;
  114. // For cases where we couldn't calculate a model
  115. int num_model_matches;
  116. } DebugMatches;
  117. // Groups together the ringbuffers that store absolute distortion / position values
  118. // for each frame
  119. typedef struct AbsoluteFrameMotion {
  120. // Array with the various ringbuffers, indexed via the RingbufferIndices enum
  121. AVFifo *ringbuffers[RingbufCount];
  122. // Offset to get to the current frame being processed
  123. // (not in bytes)
  124. int curr_frame_offset;
  125. // Keeps track of where the start and end of contiguous motion data is (to
  126. // deal with cases where no motion data is found between two frames)
  127. int data_start_offset;
  128. int data_end_offset;
  129. AVFifo *debug_matches;
  130. } AbsoluteFrameMotion;
  131. // Takes care of freeing the arrays within the DebugMatches inside of the
  132. // debug_matches ringbuffer and then freeing the buffer itself.
  133. static void free_debug_matches(AbsoluteFrameMotion *afm) {
  134. DebugMatches dm;
  135. if (!afm->debug_matches) {
  136. return;
  137. }
  138. while (av_fifo_read(afm->debug_matches, &dm, 1) >= 0)
  139. av_freep(&dm.matches);
  140. av_fifo_freep2(&afm->debug_matches);
  141. }
  142. // Stores the translation, scale, rotation, and skew deltas between two frames
  143. typedef struct FrameDelta {
  144. cl_float2 translation;
  145. float rotation;
  146. cl_float2 scale;
  147. cl_float2 skew;
  148. } FrameDelta;
  149. typedef struct SimilarityMatrix {
  150. // The 2x3 similarity matrix
  151. double matrix[6];
  152. } SimilarityMatrix;
  153. typedef struct CropInfo {
  154. // The top left corner of the bounding box for the crop
  155. cl_float2 top_left;
  156. // The bottom right corner of the bounding box for the crop
  157. cl_float2 bottom_right;
  158. } CropInfo;
  159. // Returned from function that determines start and end values for iteration
  160. // around the current frame in a ringbuffer
  161. typedef struct IterIndices {
  162. int start;
  163. int end;
  164. } IterIndices;
  165. typedef struct DeshakeOpenCLContext {
  166. OpenCLFilterContext ocf;
  167. // Whether or not the above `OpenCLFilterContext` has been initialized
  168. int initialized;
  169. // These variables are used in the activate callback
  170. int64_t duration;
  171. int eof;
  172. // State for random number generation
  173. AVLFG alfg;
  174. // FIFO frame queue used to buffer future frames for processing
  175. FFFrameQueue fq;
  176. // Ringbuffers for frame positions
  177. AbsoluteFrameMotion abs_motion;
  178. // The number of frames' motion to consider before and after the frame we are
  179. // smoothing
  180. int smooth_window;
  181. // The number of the frame we are currently processing
  182. int curr_frame;
  183. // Stores a 1d array of normalised gaussian kernel values for convolution
  184. float *gauss_kernel;
  185. // Buffer for error values used in RANSAC code
  186. float *ransac_err;
  187. // Information regarding how to crop the smoothed luminance (or RGB) planes
  188. CropInfo crop_y;
  189. // Information regarding how to crop the smoothed chroma planes
  190. CropInfo crop_uv;
  191. // Whether or not we are processing YUV input (as oppposed to RGB)
  192. int is_yuv;
  193. // The underlying format of the hardware surfaces
  194. int sw_format;
  195. // Buffer to copy `matches` into for the CPU to work with
  196. MotionVector *matches_host;
  197. MotionVector *matches_contig_host;
  198. MotionVector *inliers;
  199. cl_command_queue command_queue;
  200. cl_kernel kernel_grayscale;
  201. cl_kernel kernel_harris_response;
  202. cl_kernel kernel_refine_features;
  203. cl_kernel kernel_brief_descriptors;
  204. cl_kernel kernel_match_descriptors;
  205. cl_kernel kernel_transform;
  206. cl_kernel kernel_crop_upscale;
  207. // Stores a frame converted to grayscale
  208. cl_mem grayscale;
  209. // Stores the harris response for a frame (measure of "cornerness" for each pixel)
  210. cl_mem harris_buf;
  211. // Detected features after non-maximum suppression and sub-pixel refinement
  212. cl_mem refined_features;
  213. // Saved from the previous frame
  214. cl_mem prev_refined_features;
  215. // BRIEF sampling pattern that is randomly initialized
  216. cl_mem brief_pattern;
  217. // Feature point descriptors for the current frame
  218. cl_mem descriptors;
  219. // Feature point descriptors for the previous frame
  220. cl_mem prev_descriptors;
  221. // Vectors between points in current and previous frame
  222. cl_mem matches;
  223. cl_mem matches_contig;
  224. // Holds the matrix to transform luminance (or RGB) with
  225. cl_mem transform_y;
  226. // Holds the matrix to transform chroma with
  227. cl_mem transform_uv;
  228. // Configurable options
  229. int tripod_mode;
  230. int debug_on;
  231. int should_crop;
  232. // Whether or not feature points should be refined at a sub-pixel level
  233. cl_int refine_features;
  234. // If the user sets a value other than the default, 0, this percentage is
  235. // translated into a sigma value ranging from 0.5 to 40.0
  236. float smooth_percent;
  237. // This number is multiplied by the video frame rate to determine the size
  238. // of the smooth window
  239. float smooth_window_multiplier;
  240. // Debug stuff
  241. cl_kernel kernel_draw_debug_info;
  242. cl_mem debug_matches;
  243. cl_mem debug_model_matches;
  244. // These store the total time spent executing the different kernels in nanoseconds
  245. unsigned long long grayscale_time;
  246. unsigned long long harris_response_time;
  247. unsigned long long refine_features_time;
  248. unsigned long long brief_descriptors_time;
  249. unsigned long long match_descriptors_time;
  250. unsigned long long transform_time;
  251. unsigned long long crop_upscale_time;
  252. // Time spent copying matched features from the device to the host
  253. unsigned long long read_buf_time;
  254. } DeshakeOpenCLContext;
  255. // Returns a random uniformly-distributed number in [low, high]
  256. static int rand_in(int low, int high, AVLFG *alfg) {
  257. return (av_lfg_get(alfg) % (high - low)) + low;
  258. }
  259. // Returns the average execution time for an event given the total time and the
  260. // number of frames processed.
  261. static double averaged_event_time_ms(unsigned long long total_time, int num_frames) {
  262. return (double)total_time / (double)num_frames / 1000000.0;
  263. }
  264. // The following code is loosely ported from OpenCV
  265. // Estimates affine transform from 3 point pairs
  266. // model is a 2x3 matrix:
  267. // a b c
  268. // d e f
  269. static void run_estimate_kernel(const MotionVector *point_pairs, double *model)
  270. {
  271. // src points
  272. double x1 = point_pairs[0].p.p1.s[0];
  273. double y1 = point_pairs[0].p.p1.s[1];
  274. double x2 = point_pairs[1].p.p1.s[0];
  275. double y2 = point_pairs[1].p.p1.s[1];
  276. double x3 = point_pairs[2].p.p1.s[0];
  277. double y3 = point_pairs[2].p.p1.s[1];
  278. // dest points
  279. double X1 = point_pairs[0].p.p2.s[0];
  280. double Y1 = point_pairs[0].p.p2.s[1];
  281. double X2 = point_pairs[1].p.p2.s[0];
  282. double Y2 = point_pairs[1].p.p2.s[1];
  283. double X3 = point_pairs[2].p.p2.s[0];
  284. double Y3 = point_pairs[2].p.p2.s[1];
  285. double d = 1.0 / ( x1*(y2-y3) + x2*(y3-y1) + x3*(y1-y2) );
  286. model[0] = d * ( X1*(y2-y3) + X2*(y3-y1) + X3*(y1-y2) );
  287. model[1] = d * ( X1*(x3-x2) + X2*(x1-x3) + X3*(x2-x1) );
  288. model[2] = d * ( X1*(x2*y3 - x3*y2) + X2*(x3*y1 - x1*y3) + X3*(x1*y2 - x2*y1) );
  289. model[3] = d * ( Y1*(y2-y3) + Y2*(y3-y1) + Y3*(y1-y2) );
  290. model[4] = d * ( Y1*(x3-x2) + Y2*(x1-x3) + Y3*(x2-x1) );
  291. model[5] = d * ( Y1*(x2*y3 - x3*y2) + Y2*(x3*y1 - x1*y3) + Y3*(x1*y2 - x2*y1) );
  292. }
  293. // Checks that the 3 points in the given array are not collinear
  294. static int points_not_collinear(const cl_float2 **points)
  295. {
  296. int j, k, i = 2;
  297. for (j = 0; j < i; j++) {
  298. double dx1 = points[j]->s[0] - points[i]->s[0];
  299. double dy1 = points[j]->s[1] - points[i]->s[1];
  300. for (k = 0; k < j; k++) {
  301. double dx2 = points[k]->s[0] - points[i]->s[0];
  302. double dy2 = points[k]->s[1] - points[i]->s[1];
  303. // Assuming a 3840 x 2160 video with a point at (0, 0) and one at
  304. // (3839, 2159), this prevents a third point from being within roughly
  305. // 0.5 of a pixel of the line connecting the two on both axes
  306. if (fabs(dx2*dy1 - dy2*dx1) <= 1.0) {
  307. return 0;
  308. }
  309. }
  310. }
  311. return 1;
  312. }
  313. // Checks a subset of 3 point pairs to make sure that the points are not collinear
  314. // and not too close to each other
  315. static int check_subset(const MotionVector *pairs_subset)
  316. {
  317. const cl_float2 *prev_points[] = {
  318. &pairs_subset[0].p.p1,
  319. &pairs_subset[1].p.p1,
  320. &pairs_subset[2].p.p1
  321. };
  322. const cl_float2 *curr_points[] = {
  323. &pairs_subset[0].p.p2,
  324. &pairs_subset[1].p.p2,
  325. &pairs_subset[2].p.p2
  326. };
  327. return points_not_collinear(prev_points) && points_not_collinear(curr_points);
  328. }
  329. // Selects a random subset of 3 points from point_pairs and places them in pairs_subset
  330. static int get_subset(
  331. AVLFG *alfg,
  332. const MotionVector *point_pairs,
  333. const int num_point_pairs,
  334. MotionVector *pairs_subset,
  335. int max_attempts
  336. ) {
  337. int idx[3];
  338. int i = 0, j, iters = 0;
  339. for (; iters < max_attempts; iters++) {
  340. for (i = 0; i < 3 && iters < max_attempts;) {
  341. int idx_i = 0;
  342. for (;;) {
  343. idx_i = idx[i] = rand_in(0, num_point_pairs, alfg);
  344. for (j = 0; j < i; j++) {
  345. if (idx_i == idx[j]) {
  346. break;
  347. }
  348. }
  349. if (j == i) {
  350. break;
  351. }
  352. }
  353. pairs_subset[i] = point_pairs[idx[i]];
  354. i++;
  355. }
  356. if (i == 3 && !check_subset(pairs_subset)) {
  357. continue;
  358. }
  359. break;
  360. }
  361. return i == 3 && iters < max_attempts;
  362. }
  363. // Computes the error for each of the given points based on the given model.
  364. static void compute_error(
  365. const MotionVector *point_pairs,
  366. const int num_point_pairs,
  367. const double *model,
  368. float *err
  369. ) {
  370. double F0 = model[0], F1 = model[1], F2 = model[2];
  371. double F3 = model[3], F4 = model[4], F5 = model[5];
  372. for (int i = 0; i < num_point_pairs; i++) {
  373. const cl_float2 *f = &point_pairs[i].p.p1;
  374. const cl_float2 *t = &point_pairs[i].p.p2;
  375. double a = F0*f->s[0] + F1*f->s[1] + F2 - t->s[0];
  376. double b = F3*f->s[0] + F4*f->s[1] + F5 - t->s[1];
  377. err[i] = a*a + b*b;
  378. }
  379. }
  380. // Determines which of the given point matches are inliers for the given model
  381. // based on the specified threshold.
  382. //
  383. // err must be an array of num_point_pairs length
  384. static int find_inliers(
  385. MotionVector *point_pairs,
  386. const int num_point_pairs,
  387. const double *model,
  388. float *err,
  389. double thresh
  390. ) {
  391. float t = (float)(thresh * thresh);
  392. int i, n = num_point_pairs, num_inliers = 0;
  393. compute_error(point_pairs, num_point_pairs, model, err);
  394. for (i = 0; i < n; i++) {
  395. if (err[i] <= t) {
  396. // This is an inlier
  397. point_pairs[i].should_consider = 1;
  398. num_inliers += 1;
  399. } else {
  400. point_pairs[i].should_consider = 0;
  401. }
  402. }
  403. return num_inliers;
  404. }
  405. // Determines the number of iterations required to achieve the desired confidence level.
  406. //
  407. // The equation used to determine the number of iterations to do is:
  408. // 1 - confidence = (1 - inlier_probability^num_points)^num_iters
  409. //
  410. // Solving for num_iters:
  411. //
  412. // num_iters = log(1 - confidence) / log(1 - inlier_probability^num_points)
  413. //
  414. // A more in-depth explanation can be found at https://en.wikipedia.org/wiki/Random_sample_consensus
  415. // under the 'Parameters' heading
  416. static int ransac_update_num_iters(double confidence, double num_outliers, int max_iters)
  417. {
  418. double num, denom;
  419. confidence = av_clipd(confidence, 0.0, 1.0);
  420. num_outliers = av_clipd(num_outliers, 0.0, 1.0);
  421. // avoid inf's & nan's
  422. num = FFMAX(1.0 - confidence, DBL_MIN);
  423. denom = 1.0 - pow(1.0 - num_outliers, 3);
  424. if (denom < DBL_MIN) {
  425. return 0;
  426. }
  427. num = log(num);
  428. denom = log(denom);
  429. return denom >= 0 || -num >= max_iters * (-denom) ? max_iters : (int)round(num / denom);
  430. }
  431. // Estimates an affine transform between the given pairs of points using RANdom
  432. // SAmple Consensus
  433. static int estimate_affine_2d(
  434. DeshakeOpenCLContext *deshake_ctx,
  435. MotionVector *point_pairs,
  436. DebugMatches *debug_matches,
  437. const int num_point_pairs,
  438. double *model_out,
  439. const double threshold,
  440. const int max_iters,
  441. const double confidence
  442. ) {
  443. int result = 0;
  444. double best_model[6], model[6];
  445. MotionVector pairs_subset[3], best_pairs[3];
  446. int iter, niters = FFMAX(max_iters, 1);
  447. int good_count, max_good_count = 0;
  448. // We need at least 3 points to build a model from
  449. if (num_point_pairs < 3) {
  450. return 0;
  451. } else if (num_point_pairs == 3) {
  452. // There are only 3 points, so RANSAC doesn't apply here
  453. run_estimate_kernel(point_pairs, model_out);
  454. for (int i = 0; i < 3; ++i) {
  455. point_pairs[i].should_consider = 1;
  456. }
  457. return 1;
  458. }
  459. for (iter = 0; iter < niters; ++iter) {
  460. int found = get_subset(&deshake_ctx->alfg, point_pairs, num_point_pairs, pairs_subset, 10000);
  461. if (!found) {
  462. if (iter == 0) {
  463. return 0;
  464. }
  465. break;
  466. }
  467. run_estimate_kernel(pairs_subset, model);
  468. good_count = find_inliers(point_pairs, num_point_pairs, model, deshake_ctx->ransac_err, threshold);
  469. if (good_count > FFMAX(max_good_count, 2)) {
  470. for (int mi = 0; mi < 6; ++mi) {
  471. best_model[mi] = model[mi];
  472. }
  473. for (int pi = 0; pi < 3; pi++) {
  474. best_pairs[pi] = pairs_subset[pi];
  475. }
  476. max_good_count = good_count;
  477. niters = ransac_update_num_iters(
  478. confidence,
  479. (double)(num_point_pairs - good_count) / num_point_pairs,
  480. niters
  481. );
  482. }
  483. }
  484. if (max_good_count > 0) {
  485. for (int mi = 0; mi < 6; ++mi) {
  486. model_out[mi] = best_model[mi];
  487. }
  488. for (int pi = 0; pi < 3; ++pi) {
  489. debug_matches->model_matches[pi] = best_pairs[pi];
  490. }
  491. debug_matches->num_model_matches = 3;
  492. // Find the inliers again for the best model for debugging
  493. find_inliers(point_pairs, num_point_pairs, best_model, deshake_ctx->ransac_err, threshold);
  494. result = 1;
  495. }
  496. return result;
  497. }
  498. // "Wiggles" the first point in best_pairs around a tiny bit in order to decrease the
  499. // total error
  500. static void optimize_model(
  501. DeshakeOpenCLContext *deshake_ctx,
  502. MotionVector *best_pairs,
  503. MotionVector *inliers,
  504. const int num_inliers,
  505. float best_err,
  506. double *model_out
  507. ) {
  508. float move_x_val = 0.01;
  509. float move_y_val = 0.01;
  510. int move_x = 1;
  511. float old_move_x_val = 0;
  512. double model[6];
  513. int last_changed = 0;
  514. for (int iters = 0; iters < 200; iters++) {
  515. float total_err = 0;
  516. if (move_x) {
  517. best_pairs[0].p.p2.s[0] += move_x_val;
  518. } else {
  519. best_pairs[0].p.p2.s[0] += move_y_val;
  520. }
  521. run_estimate_kernel(best_pairs, model);
  522. compute_error(inliers, num_inliers, model, deshake_ctx->ransac_err);
  523. for (int j = 0; j < num_inliers; j++) {
  524. total_err += deshake_ctx->ransac_err[j];
  525. }
  526. if (total_err < best_err) {
  527. for (int mi = 0; mi < 6; ++mi) {
  528. model_out[mi] = model[mi];
  529. }
  530. best_err = total_err;
  531. last_changed = iters;
  532. } else {
  533. // Undo the change
  534. if (move_x) {
  535. best_pairs[0].p.p2.s[0] -= move_x_val;
  536. } else {
  537. best_pairs[0].p.p2.s[0] -= move_y_val;
  538. }
  539. if (iters - last_changed > 4) {
  540. // We've already improved the model as much as we can
  541. break;
  542. }
  543. old_move_x_val = move_x_val;
  544. if (move_x) {
  545. move_x_val *= -1;
  546. } else {
  547. move_y_val *= -1;
  548. }
  549. if (old_move_x_val < 0) {
  550. move_x = 0;
  551. } else {
  552. move_x = 1;
  553. }
  554. }
  555. }
  556. }
  557. // Uses a process similar to that of RANSAC to find a transform that minimizes
  558. // the total error for a set of point matches determined to be inliers
  559. //
  560. // (Pick random subsets, compute model, find total error, iterate until error
  561. // is minimized.)
  562. static int minimize_error(
  563. DeshakeOpenCLContext *deshake_ctx,
  564. MotionVector *inliers,
  565. DebugMatches *debug_matches,
  566. const int num_inliers,
  567. double *model_out,
  568. const int max_iters
  569. ) {
  570. int result = 0;
  571. float best_err = FLT_MAX;
  572. double best_model[6], model[6];
  573. MotionVector pairs_subset[3], best_pairs[3];
  574. for (int i = 0; i < max_iters; i++) {
  575. float total_err = 0;
  576. int found = get_subset(&deshake_ctx->alfg, inliers, num_inliers, pairs_subset, 10000);
  577. if (!found) {
  578. if (i == 0) {
  579. return 0;
  580. }
  581. break;
  582. }
  583. run_estimate_kernel(pairs_subset, model);
  584. compute_error(inliers, num_inliers, model, deshake_ctx->ransac_err);
  585. for (int j = 0; j < num_inliers; j++) {
  586. total_err += deshake_ctx->ransac_err[j];
  587. }
  588. if (total_err < best_err) {
  589. for (int mi = 0; mi < 6; ++mi) {
  590. best_model[mi] = model[mi];
  591. }
  592. for (int pi = 0; pi < 3; pi++) {
  593. best_pairs[pi] = pairs_subset[pi];
  594. }
  595. best_err = total_err;
  596. }
  597. }
  598. for (int mi = 0; mi < 6; ++mi) {
  599. model_out[mi] = best_model[mi];
  600. }
  601. for (int pi = 0; pi < 3; ++pi) {
  602. debug_matches->model_matches[pi] = best_pairs[pi];
  603. }
  604. debug_matches->num_model_matches = 3;
  605. result = 1;
  606. optimize_model(deshake_ctx, best_pairs, inliers, num_inliers, best_err, model_out);
  607. return result;
  608. }
  609. // End code from OpenCV
  610. // Decomposes a similarity matrix into translation, rotation, scale, and skew
  611. //
  612. // See http://frederic-wang.fr/decomposition-of-2d-transform-matrices.html
  613. static FrameDelta decompose_transform(double *model)
  614. {
  615. FrameDelta ret;
  616. double a = model[0];
  617. double c = model[1];
  618. double e = model[2];
  619. double b = model[3];
  620. double d = model[4];
  621. double f = model[5];
  622. double delta = a * d - b * c;
  623. memset(&ret, 0, sizeof(ret));
  624. ret.translation.s[0] = e;
  625. ret.translation.s[1] = f;
  626. // This is the QR method
  627. if (a != 0 || b != 0) {
  628. double r = hypot(a, b);
  629. ret.rotation = FFSIGN(b) * acos(a / r);
  630. ret.scale.s[0] = r;
  631. ret.scale.s[1] = delta / r;
  632. ret.skew.s[0] = atan((a * c + b * d) / (r * r));
  633. ret.skew.s[1] = 0;
  634. } else if (c != 0 || d != 0) {
  635. double s = sqrt(c * c + d * d);
  636. ret.rotation = M_PI / 2 - FFSIGN(d) * acos(-c / s);
  637. ret.scale.s[0] = delta / s;
  638. ret.scale.s[1] = s;
  639. ret.skew.s[0] = 0;
  640. ret.skew.s[1] = atan((a * c + b * d) / (s * s));
  641. } // otherwise there is only translation
  642. return ret;
  643. }
  644. // Move valid vectors from the 2d buffer into a 1d buffer where they are contiguous
  645. static int make_vectors_contig(
  646. DeshakeOpenCLContext *deshake_ctx,
  647. int size_y,
  648. int size_x
  649. ) {
  650. int num_vectors = 0;
  651. for (int i = 0; i < size_y; ++i) {
  652. for (int j = 0; j < size_x; ++j) {
  653. MotionVector v = deshake_ctx->matches_host[j + i * size_x];
  654. if (v.should_consider) {
  655. deshake_ctx->matches_contig_host[num_vectors] = v;
  656. ++num_vectors;
  657. }
  658. // Make sure we do not exceed the amount of space we allocated for these vectors
  659. if (num_vectors == MATCHES_CONTIG_SIZE - 1) {
  660. return num_vectors;
  661. }
  662. }
  663. }
  664. return num_vectors;
  665. }
  666. // Returns the gaussian kernel value for the given x coordinate and sigma value
  667. static float gaussian_for(int x, float sigma) {
  668. return 1.0f / expf(((float)x * (float)x) / (2.0f * sigma * sigma));
  669. }
  670. // Makes a normalized gaussian kernel of the given length for the given sigma
  671. // and places it in gauss_kernel
  672. static void make_gauss_kernel(float *gauss_kernel, float length, float sigma)
  673. {
  674. float gauss_sum = 0;
  675. int window_half = length / 2;
  676. for (int i = 0; i < length; ++i) {
  677. float val = gaussian_for(i - window_half, sigma);
  678. gauss_sum += val;
  679. gauss_kernel[i] = val;
  680. }
  681. // Normalize the gaussian values
  682. for (int i = 0; i < length; ++i) {
  683. gauss_kernel[i] /= gauss_sum;
  684. }
  685. }
  686. // Returns indices to start and end iteration at in order to iterate over a window
  687. // of length size centered at the current frame in a ringbuffer
  688. //
  689. // Always returns numbers that result in a window of length size, even if that
  690. // means specifying negative indices or indices past the end of the values in the
  691. // ringbuffers. Make sure you clip indices appropriately within your loop.
  692. static IterIndices start_end_for(DeshakeOpenCLContext *deshake_ctx, int length) {
  693. IterIndices indices;
  694. indices.start = deshake_ctx->abs_motion.curr_frame_offset - (length / 2);
  695. indices.end = deshake_ctx->abs_motion.curr_frame_offset + (length / 2) + (length % 2);
  696. return indices;
  697. }
  698. // Sets val to the value in the given ringbuffer at the given offset, taking care of
  699. // clipping the offset into the appropriate range
  700. static void ringbuf_float_at(
  701. DeshakeOpenCLContext *deshake_ctx,
  702. AVFifo *values,
  703. float *val,
  704. int offset
  705. ) {
  706. int clip_start, clip_end, offset_clipped;
  707. if (deshake_ctx->abs_motion.data_end_offset != -1) {
  708. clip_end = deshake_ctx->abs_motion.data_end_offset;
  709. } else {
  710. // This expression represents the last valid index in the buffer,
  711. // which we use repeatedly at the end of the video.
  712. clip_end = deshake_ctx->smooth_window - av_fifo_can_write(values) - 1;
  713. }
  714. if (deshake_ctx->abs_motion.data_start_offset != -1) {
  715. clip_start = deshake_ctx->abs_motion.data_start_offset;
  716. } else {
  717. // Negative indices will occur at the start of the video, and we want
  718. // them to be clipped to 0 in order to repeatedly use the position of
  719. // the first frame.
  720. clip_start = 0;
  721. }
  722. offset_clipped = av_clip(
  723. offset,
  724. clip_start,
  725. clip_end
  726. );
  727. av_fifo_peek(values, val, 1, offset_clipped);
  728. }
  729. // Returns smoothed current frame value of the given buffer of floats based on the
  730. // given Gaussian kernel and its length (also the window length, centered around the
  731. // current frame) and the "maximum value" of the motion.
  732. //
  733. // This "maximum value" should be the width / height of the image in the case of
  734. // translation and an empirically chosen constant for rotation / scale.
  735. //
  736. // The sigma chosen to generate the final gaussian kernel with used to smooth the
  737. // camera path is either hardcoded (set by user, deshake_ctx->smooth_percent) or
  738. // adaptively chosen.
  739. static float smooth(
  740. DeshakeOpenCLContext *deshake_ctx,
  741. float *gauss_kernel,
  742. int length,
  743. float max_val,
  744. AVFifo *values
  745. ) {
  746. float new_large_s = 0, new_small_s = 0, new_best = 0, old, diff_between,
  747. percent_of_max, inverted_percent;
  748. IterIndices indices = start_end_for(deshake_ctx, length);
  749. float large_sigma = 40.0f;
  750. float small_sigma = 2.0f;
  751. float best_sigma;
  752. if (deshake_ctx->smooth_percent) {
  753. best_sigma = (large_sigma - 0.5f) * deshake_ctx->smooth_percent + 0.5f;
  754. } else {
  755. // Strategy to adaptively smooth trajectory:
  756. //
  757. // 1. Smooth path with large and small sigma values
  758. // 2. Take the absolute value of the difference between them
  759. // 3. Get a percentage by putting the difference over the "max value"
  760. // 4, Invert the percentage
  761. // 5. Calculate a new sigma value weighted towards the larger sigma value
  762. // 6. Determine final smoothed trajectory value using that sigma
  763. make_gauss_kernel(gauss_kernel, length, large_sigma);
  764. for (int i = indices.start, j = 0; i < indices.end; ++i, ++j) {
  765. ringbuf_float_at(deshake_ctx, values, &old, i);
  766. new_large_s += old * gauss_kernel[j];
  767. }
  768. make_gauss_kernel(gauss_kernel, length, small_sigma);
  769. for (int i = indices.start, j = 0; i < indices.end; ++i, ++j) {
  770. ringbuf_float_at(deshake_ctx, values, &old, i);
  771. new_small_s += old * gauss_kernel[j];
  772. }
  773. diff_between = fabsf(new_large_s - new_small_s);
  774. percent_of_max = diff_between / max_val;
  775. inverted_percent = 1 - percent_of_max;
  776. best_sigma = large_sigma * powf(inverted_percent, 40);
  777. }
  778. make_gauss_kernel(gauss_kernel, length, best_sigma);
  779. for (int i = indices.start, j = 0; i < indices.end; ++i, ++j) {
  780. ringbuf_float_at(deshake_ctx, values, &old, i);
  781. new_best += old * gauss_kernel[j];
  782. }
  783. return new_best;
  784. }
  785. // Returns the position of the given point after the transform is applied
  786. static cl_float2 transformed_point(float x, float y, float *transform) {
  787. cl_float2 ret;
  788. ret.s[0] = x * transform[0] + y * transform[1] + transform[2];
  789. ret.s[1] = x * transform[3] + y * transform[4] + transform[5];
  790. return ret;
  791. }
  792. // Creates an affine transform that scales from the center of a frame
  793. static void transform_center_scale(
  794. float x_shift,
  795. float y_shift,
  796. float angle,
  797. float scale_x,
  798. float scale_y,
  799. float center_w,
  800. float center_h,
  801. float *matrix
  802. ) {
  803. cl_float2 center_s;
  804. float center_s_w, center_s_h;
  805. ff_get_matrix(
  806. 0,
  807. 0,
  808. 0,
  809. scale_x,
  810. scale_y,
  811. matrix
  812. );
  813. center_s = transformed_point(center_w, center_h, matrix);
  814. center_s_w = center_w - center_s.s[0];
  815. center_s_h = center_h - center_s.s[1];
  816. ff_get_matrix(
  817. x_shift + center_s_w,
  818. y_shift + center_s_h,
  819. angle,
  820. scale_x,
  821. scale_y,
  822. matrix
  823. );
  824. }
  825. // Determines the crop necessary to eliminate black borders from a smoothed frame
  826. // and updates target crop accordingly
  827. static void update_needed_crop(
  828. CropInfo* crop,
  829. float *transform,
  830. float frame_width,
  831. float frame_height
  832. ) {
  833. float new_width, new_height, adjusted_width, adjusted_height, adjusted_x, adjusted_y;
  834. cl_float2 top_left = transformed_point(0, 0, transform);
  835. cl_float2 top_right = transformed_point(frame_width, 0, transform);
  836. cl_float2 bottom_left = transformed_point(0, frame_height, transform);
  837. cl_float2 bottom_right = transformed_point(frame_width, frame_height, transform);
  838. float ar_h = frame_height / frame_width;
  839. float ar_w = frame_width / frame_height;
  840. if (crop->bottom_right.s[0] == 0) {
  841. // The crop hasn't been set to the original size of the plane
  842. crop->bottom_right.s[0] = frame_width;
  843. crop->bottom_right.s[1] = frame_height;
  844. }
  845. crop->top_left.s[0] = FFMAX3(
  846. crop->top_left.s[0],
  847. top_left.s[0],
  848. bottom_left.s[0]
  849. );
  850. crop->top_left.s[1] = FFMAX3(
  851. crop->top_left.s[1],
  852. top_left.s[1],
  853. top_right.s[1]
  854. );
  855. crop->bottom_right.s[0] = FFMIN3(
  856. crop->bottom_right.s[0],
  857. bottom_right.s[0],
  858. top_right.s[0]
  859. );
  860. crop->bottom_right.s[1] = FFMIN3(
  861. crop->bottom_right.s[1],
  862. bottom_right.s[1],
  863. bottom_left.s[1]
  864. );
  865. // Make sure our potentially new bounding box has the same aspect ratio
  866. new_height = crop->bottom_right.s[1] - crop->top_left.s[1];
  867. new_width = crop->bottom_right.s[0] - crop->top_left.s[0];
  868. adjusted_width = new_height * ar_w;
  869. adjusted_x = crop->bottom_right.s[0] - adjusted_width;
  870. if (adjusted_x >= crop->top_left.s[0]) {
  871. crop->top_left.s[0] = adjusted_x;
  872. } else {
  873. adjusted_height = new_width * ar_h;
  874. adjusted_y = crop->bottom_right.s[1] - adjusted_height;
  875. crop->top_left.s[1] = adjusted_y;
  876. }
  877. }
  878. static av_cold void deshake_opencl_uninit(AVFilterContext *avctx)
  879. {
  880. DeshakeOpenCLContext *ctx = avctx->priv;
  881. cl_int cle;
  882. for (int i = 0; i < RingbufCount; i++)
  883. av_fifo_freep2(&ctx->abs_motion.ringbuffers[i]);
  884. if (ctx->debug_on)
  885. free_debug_matches(&ctx->abs_motion);
  886. if (ctx->gauss_kernel)
  887. av_freep(&ctx->gauss_kernel);
  888. if (ctx->ransac_err)
  889. av_freep(&ctx->ransac_err);
  890. if (ctx->matches_host)
  891. av_freep(&ctx->matches_host);
  892. if (ctx->matches_contig_host)
  893. av_freep(&ctx->matches_contig_host);
  894. if (ctx->inliers)
  895. av_freep(&ctx->inliers);
  896. ff_framequeue_free(&ctx->fq);
  897. CL_RELEASE_KERNEL(ctx->kernel_grayscale);
  898. CL_RELEASE_KERNEL(ctx->kernel_harris_response);
  899. CL_RELEASE_KERNEL(ctx->kernel_refine_features);
  900. CL_RELEASE_KERNEL(ctx->kernel_brief_descriptors);
  901. CL_RELEASE_KERNEL(ctx->kernel_match_descriptors);
  902. CL_RELEASE_KERNEL(ctx->kernel_crop_upscale);
  903. if (ctx->debug_on)
  904. CL_RELEASE_KERNEL(ctx->kernel_draw_debug_info);
  905. CL_RELEASE_QUEUE(ctx->command_queue);
  906. if (!ctx->is_yuv)
  907. CL_RELEASE_MEMORY(ctx->grayscale);
  908. CL_RELEASE_MEMORY(ctx->harris_buf);
  909. CL_RELEASE_MEMORY(ctx->refined_features);
  910. CL_RELEASE_MEMORY(ctx->prev_refined_features);
  911. CL_RELEASE_MEMORY(ctx->brief_pattern);
  912. CL_RELEASE_MEMORY(ctx->descriptors);
  913. CL_RELEASE_MEMORY(ctx->prev_descriptors);
  914. CL_RELEASE_MEMORY(ctx->matches);
  915. CL_RELEASE_MEMORY(ctx->matches_contig);
  916. CL_RELEASE_MEMORY(ctx->transform_y);
  917. CL_RELEASE_MEMORY(ctx->transform_uv);
  918. if (ctx->debug_on) {
  919. CL_RELEASE_MEMORY(ctx->debug_matches);
  920. CL_RELEASE_MEMORY(ctx->debug_model_matches);
  921. }
  922. ff_opencl_filter_uninit(avctx);
  923. }
  924. static int deshake_opencl_init(AVFilterContext *avctx)
  925. {
  926. DeshakeOpenCLContext *ctx = avctx->priv;
  927. AVFilterLink *outlink = avctx->outputs[0];
  928. AVFilterLink *inlink = avctx->inputs[0];
  929. // Pointer to the host-side pattern buffer to be initialized and then copied
  930. // to the GPU
  931. PointPair *pattern_host = NULL;
  932. cl_int cle;
  933. int err;
  934. cl_ulong8 zeroed_ulong8;
  935. FFFrameQueueGlobal fqg;
  936. cl_image_format grayscale_format;
  937. cl_image_desc grayscale_desc;
  938. cl_command_queue_properties queue_props;
  939. const enum AVPixelFormat disallowed_formats[14] = {
  940. AV_PIX_FMT_GBRP,
  941. AV_PIX_FMT_GBRP9BE,
  942. AV_PIX_FMT_GBRP9LE,
  943. AV_PIX_FMT_GBRP10BE,
  944. AV_PIX_FMT_GBRP10LE,
  945. AV_PIX_FMT_GBRP16BE,
  946. AV_PIX_FMT_GBRP16LE,
  947. AV_PIX_FMT_GBRAP,
  948. AV_PIX_FMT_GBRAP16BE,
  949. AV_PIX_FMT_GBRAP16LE,
  950. AV_PIX_FMT_GBRAP12BE,
  951. AV_PIX_FMT_GBRAP12LE,
  952. AV_PIX_FMT_GBRAP10BE,
  953. AV_PIX_FMT_GBRAP10LE
  954. };
  955. // Number of elements for an array
  956. const int image_grid_32 = ROUNDED_UP_DIV(outlink->h, 32) * ROUNDED_UP_DIV(outlink->w, 32);
  957. const int descriptor_buf_size = image_grid_32 * (BREIFN / 8);
  958. const int features_buf_size = image_grid_32 * sizeof(cl_float2);
  959. const AVHWFramesContext *hw_frames_ctx = (AVHWFramesContext*)inlink->hw_frames_ctx->data;
  960. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(hw_frames_ctx->sw_format);
  961. av_assert0(hw_frames_ctx);
  962. av_assert0(desc);
  963. ff_framequeue_global_init(&fqg);
  964. ff_framequeue_init(&ctx->fq, &fqg);
  965. ctx->eof = 0;
  966. ctx->smooth_window = (int)(av_q2d(avctx->inputs[0]->frame_rate) * ctx->smooth_window_multiplier);
  967. ctx->curr_frame = 0;
  968. memset(&zeroed_ulong8, 0, sizeof(cl_ulong8));
  969. ctx->gauss_kernel = av_malloc_array(ctx->smooth_window, sizeof(float));
  970. if (!ctx->gauss_kernel) {
  971. err = AVERROR(ENOMEM);
  972. goto fail;
  973. }
  974. ctx->ransac_err = av_malloc_array(MATCHES_CONTIG_SIZE, sizeof(float));
  975. if (!ctx->ransac_err) {
  976. err = AVERROR(ENOMEM);
  977. goto fail;
  978. }
  979. for (int i = 0; i < RingbufCount; i++) {
  980. ctx->abs_motion.ringbuffers[i] = av_fifo_alloc2(ctx->smooth_window,
  981. sizeof(float), 0);
  982. if (!ctx->abs_motion.ringbuffers[i]) {
  983. err = AVERROR(ENOMEM);
  984. goto fail;
  985. }
  986. }
  987. if (ctx->debug_on) {
  988. ctx->abs_motion.debug_matches = av_fifo_alloc2(
  989. ctx->smooth_window / 2,
  990. sizeof(DebugMatches), 0
  991. );
  992. if (!ctx->abs_motion.debug_matches) {
  993. err = AVERROR(ENOMEM);
  994. goto fail;
  995. }
  996. }
  997. ctx->abs_motion.curr_frame_offset = 0;
  998. ctx->abs_motion.data_start_offset = -1;
  999. ctx->abs_motion.data_end_offset = -1;
  1000. pattern_host = av_malloc_array(BREIFN, sizeof(PointPair));
  1001. if (!pattern_host) {
  1002. err = AVERROR(ENOMEM);
  1003. goto fail;
  1004. }
  1005. ctx->matches_host = av_malloc_array(image_grid_32, sizeof(MotionVector));
  1006. if (!ctx->matches_host) {
  1007. err = AVERROR(ENOMEM);
  1008. goto fail;
  1009. }
  1010. ctx->matches_contig_host = av_malloc_array(MATCHES_CONTIG_SIZE, sizeof(MotionVector));
  1011. if (!ctx->matches_contig_host) {
  1012. err = AVERROR(ENOMEM);
  1013. goto fail;
  1014. }
  1015. ctx->inliers = av_malloc_array(MATCHES_CONTIG_SIZE, sizeof(MotionVector));
  1016. if (!ctx->inliers) {
  1017. err = AVERROR(ENOMEM);
  1018. goto fail;
  1019. }
  1020. // Initializing the patch pattern for building BREIF descriptors with
  1021. av_lfg_init(&ctx->alfg, 234342424);
  1022. for (int i = 0; i < BREIFN; ++i) {
  1023. PointPair pair;
  1024. for (int j = 0; j < 2; ++j) {
  1025. pair.p1.s[j] = rand_in(-BRIEF_PATCH_SIZE_HALF, BRIEF_PATCH_SIZE_HALF + 1, &ctx->alfg);
  1026. pair.p2.s[j] = rand_in(-BRIEF_PATCH_SIZE_HALF, BRIEF_PATCH_SIZE_HALF + 1, &ctx->alfg);
  1027. }
  1028. pattern_host[i] = pair;
  1029. }
  1030. for (int i = 0; i < 14; i++) {
  1031. if (ctx->sw_format == disallowed_formats[i]) {
  1032. av_log(avctx, AV_LOG_ERROR, "unsupported format in deshake_opencl.\n");
  1033. err = AVERROR(ENOSYS);
  1034. goto fail;
  1035. }
  1036. }
  1037. if (desc->flags & AV_PIX_FMT_FLAG_RGB) {
  1038. ctx->is_yuv = 0;
  1039. } else {
  1040. ctx->is_yuv = 1;
  1041. }
  1042. ctx->sw_format = hw_frames_ctx->sw_format;
  1043. err = ff_opencl_filter_load_program(avctx, &ff_source_deshake_cl, 1);
  1044. if (err < 0)
  1045. goto fail;
  1046. if (ctx->debug_on) {
  1047. queue_props = CL_QUEUE_PROFILING_ENABLE;
  1048. } else {
  1049. queue_props = 0;
  1050. }
  1051. ctx->command_queue = clCreateCommandQueue(
  1052. ctx->ocf.hwctx->context,
  1053. ctx->ocf.hwctx->device_id,
  1054. queue_props,
  1055. &cle
  1056. );
  1057. CL_FAIL_ON_ERROR(AVERROR(EIO), "Failed to create OpenCL command queue %d.\n", cle);
  1058. CL_CREATE_KERNEL(ctx, grayscale);
  1059. CL_CREATE_KERNEL(ctx, harris_response);
  1060. CL_CREATE_KERNEL(ctx, refine_features);
  1061. CL_CREATE_KERNEL(ctx, brief_descriptors);
  1062. CL_CREATE_KERNEL(ctx, match_descriptors);
  1063. CL_CREATE_KERNEL(ctx, transform);
  1064. CL_CREATE_KERNEL(ctx, crop_upscale);
  1065. if (ctx->debug_on)
  1066. CL_CREATE_KERNEL(ctx, draw_debug_info);
  1067. if (!ctx->is_yuv) {
  1068. grayscale_format.image_channel_order = CL_R;
  1069. grayscale_format.image_channel_data_type = CL_FLOAT;
  1070. grayscale_desc = (cl_image_desc) {
  1071. .image_type = CL_MEM_OBJECT_IMAGE2D,
  1072. .image_width = outlink->w,
  1073. .image_height = outlink->h,
  1074. .image_depth = 0,
  1075. .image_array_size = 0,
  1076. .image_row_pitch = 0,
  1077. .image_slice_pitch = 0,
  1078. .num_mip_levels = 0,
  1079. .num_samples = 0,
  1080. .buffer = NULL,
  1081. };
  1082. ctx->grayscale = clCreateImage(
  1083. ctx->ocf.hwctx->context,
  1084. 0,
  1085. &grayscale_format,
  1086. &grayscale_desc,
  1087. NULL,
  1088. &cle
  1089. );
  1090. CL_FAIL_ON_ERROR(AVERROR(EIO), "Failed to create grayscale image: %d.\n", cle);
  1091. }
  1092. CL_CREATE_BUFFER(ctx, harris_buf, outlink->h * outlink->w * sizeof(float));
  1093. CL_CREATE_BUFFER(ctx, refined_features, features_buf_size);
  1094. CL_CREATE_BUFFER(ctx, prev_refined_features, features_buf_size);
  1095. CL_CREATE_BUFFER_FLAGS(
  1096. ctx,
  1097. brief_pattern,
  1098. CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,
  1099. BREIFN * sizeof(PointPair),
  1100. pattern_host
  1101. );
  1102. CL_CREATE_BUFFER(ctx, descriptors, descriptor_buf_size);
  1103. CL_CREATE_BUFFER(ctx, prev_descriptors, descriptor_buf_size);
  1104. CL_CREATE_BUFFER(ctx, matches, image_grid_32 * sizeof(MotionVector));
  1105. CL_CREATE_BUFFER(ctx, matches_contig, MATCHES_CONTIG_SIZE * sizeof(MotionVector));
  1106. CL_CREATE_BUFFER(ctx, transform_y, 9 * sizeof(float));
  1107. CL_CREATE_BUFFER(ctx, transform_uv, 9 * sizeof(float));
  1108. if (ctx->debug_on) {
  1109. CL_CREATE_BUFFER(ctx, debug_matches, MATCHES_CONTIG_SIZE * sizeof(MotionVector));
  1110. CL_CREATE_BUFFER(ctx, debug_model_matches, 3 * sizeof(MotionVector));
  1111. }
  1112. ctx->initialized = 1;
  1113. av_freep(&pattern_host);
  1114. return 0;
  1115. fail:
  1116. av_freep(&pattern_host);
  1117. return err;
  1118. }
  1119. // Logs debug information about the transform data
  1120. static void transform_debug(AVFilterContext *avctx, float *new_vals, float *old_vals, int curr_frame) {
  1121. av_log(avctx, AV_LOG_VERBOSE,
  1122. "Frame %d:\n"
  1123. "\tframe moved from: %f x, %f y\n"
  1124. "\t to: %f x, %f y\n"
  1125. "\t rotated from: %f degrees\n"
  1126. "\t to: %f degrees\n"
  1127. "\t scaled from: %f x, %f y\n"
  1128. "\t to: %f x, %f y\n"
  1129. "\n"
  1130. "\tframe moved by: %f x, %f y\n"
  1131. "\t rotated by: %f degrees\n"
  1132. "\t scaled by: %f x, %f y\n",
  1133. curr_frame,
  1134. old_vals[RingbufX], old_vals[RingbufY],
  1135. new_vals[RingbufX], new_vals[RingbufY],
  1136. old_vals[RingbufRot] * (180.0 / M_PI),
  1137. new_vals[RingbufRot] * (180.0 / M_PI),
  1138. old_vals[RingbufScaleX], old_vals[RingbufScaleY],
  1139. new_vals[RingbufScaleX], new_vals[RingbufScaleY],
  1140. old_vals[RingbufX] - new_vals[RingbufX], old_vals[RingbufY] - new_vals[RingbufY],
  1141. old_vals[RingbufRot] * (180.0 / M_PI) - new_vals[RingbufRot] * (180.0 / M_PI),
  1142. new_vals[RingbufScaleX] / old_vals[RingbufScaleX], new_vals[RingbufScaleY] / old_vals[RingbufScaleY]
  1143. );
  1144. }
  1145. // Uses the buffered motion information to determine a transform that smooths the
  1146. // given frame and applies it
  1147. static int filter_frame(AVFilterLink *link, AVFrame *input_frame)
  1148. {
  1149. AVFilterContext *avctx = link->dst;
  1150. AVFilterLink *outlink = avctx->outputs[0];
  1151. DeshakeOpenCLContext *deshake_ctx = avctx->priv;
  1152. AVFrame *cropped_frame = NULL, *transformed_frame = NULL;
  1153. int err;
  1154. cl_int cle;
  1155. float new_vals[RingbufCount];
  1156. float old_vals[RingbufCount];
  1157. // Luma (in the case of YUV) transform, or just the transform in the case of RGB
  1158. float transform_y[9];
  1159. // Chroma transform
  1160. float transform_uv[9];
  1161. // Luma crop transform (or RGB)
  1162. float transform_crop_y[9];
  1163. // Chroma crop transform
  1164. float transform_crop_uv[9];
  1165. float transform_debug_rgb[9];
  1166. size_t global_work[2];
  1167. int64_t duration;
  1168. cl_mem src, transformed, dst;
  1169. cl_mem transforms[3];
  1170. CropInfo crops[3];
  1171. cl_event transform_event, crop_upscale_event;
  1172. DebugMatches debug_matches;
  1173. cl_int num_model_matches;
  1174. const float center_w = (float)input_frame->width / 2;
  1175. const float center_h = (float)input_frame->height / 2;
  1176. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(deshake_ctx->sw_format);
  1177. const int chroma_width = AV_CEIL_RSHIFT(input_frame->width, desc->log2_chroma_w);
  1178. const int chroma_height = AV_CEIL_RSHIFT(input_frame->height, desc->log2_chroma_h);
  1179. const float center_w_chroma = (float)chroma_width / 2;
  1180. const float center_h_chroma = (float)chroma_height / 2;
  1181. const float luma_w_over_chroma_w = ((float)input_frame->width / (float)chroma_width);
  1182. const float luma_h_over_chroma_h = ((float)input_frame->height / (float)chroma_height);
  1183. if (deshake_ctx->debug_on) {
  1184. av_fifo_read(
  1185. deshake_ctx->abs_motion.debug_matches,
  1186. &debug_matches, 1);
  1187. }
  1188. if (input_frame->duration) {
  1189. duration = input_frame->duration;
  1190. } else {
  1191. duration = av_rescale_q(1, av_inv_q(outlink->frame_rate), outlink->time_base);
  1192. }
  1193. deshake_ctx->duration = input_frame->pts + duration;
  1194. // Get the absolute transform data for this frame
  1195. for (int i = 0; i < RingbufCount; i++) {
  1196. av_fifo_peek(deshake_ctx->abs_motion.ringbuffers[i],
  1197. &old_vals[i], 1,
  1198. deshake_ctx->abs_motion.curr_frame_offset);
  1199. }
  1200. if (deshake_ctx->tripod_mode) {
  1201. // If tripod mode is turned on we simply undo all motion relative to the
  1202. // first frame
  1203. new_vals[RingbufX] = 0.0f;
  1204. new_vals[RingbufY] = 0.0f;
  1205. new_vals[RingbufRot] = 0.0f;
  1206. new_vals[RingbufScaleX] = 1.0f;
  1207. new_vals[RingbufScaleY] = 1.0f;
  1208. } else {
  1209. // Tripod mode is off and we need to smooth a moving camera
  1210. new_vals[RingbufX] = smooth(
  1211. deshake_ctx,
  1212. deshake_ctx->gauss_kernel,
  1213. deshake_ctx->smooth_window,
  1214. input_frame->width,
  1215. deshake_ctx->abs_motion.ringbuffers[RingbufX]
  1216. );
  1217. new_vals[RingbufY] = smooth(
  1218. deshake_ctx,
  1219. deshake_ctx->gauss_kernel,
  1220. deshake_ctx->smooth_window,
  1221. input_frame->height,
  1222. deshake_ctx->abs_motion.ringbuffers[RingbufY]
  1223. );
  1224. new_vals[RingbufRot] = smooth(
  1225. deshake_ctx,
  1226. deshake_ctx->gauss_kernel,
  1227. deshake_ctx->smooth_window,
  1228. M_PI / 4,
  1229. deshake_ctx->abs_motion.ringbuffers[RingbufRot]
  1230. );
  1231. new_vals[RingbufScaleX] = smooth(
  1232. deshake_ctx,
  1233. deshake_ctx->gauss_kernel,
  1234. deshake_ctx->smooth_window,
  1235. 2.0f,
  1236. deshake_ctx->abs_motion.ringbuffers[RingbufScaleX]
  1237. );
  1238. new_vals[RingbufScaleY] = smooth(
  1239. deshake_ctx,
  1240. deshake_ctx->gauss_kernel,
  1241. deshake_ctx->smooth_window,
  1242. 2.0f,
  1243. deshake_ctx->abs_motion.ringbuffers[RingbufScaleY]
  1244. );
  1245. }
  1246. transform_center_scale(
  1247. old_vals[RingbufX] - new_vals[RingbufX],
  1248. old_vals[RingbufY] - new_vals[RingbufY],
  1249. old_vals[RingbufRot] - new_vals[RingbufRot],
  1250. new_vals[RingbufScaleX] / old_vals[RingbufScaleX],
  1251. new_vals[RingbufScaleY] / old_vals[RingbufScaleY],
  1252. center_w,
  1253. center_h,
  1254. transform_y
  1255. );
  1256. transform_center_scale(
  1257. (old_vals[RingbufX] - new_vals[RingbufX]) / luma_w_over_chroma_w,
  1258. (old_vals[RingbufY] - new_vals[RingbufY]) / luma_h_over_chroma_h,
  1259. old_vals[RingbufRot] - new_vals[RingbufRot],
  1260. new_vals[RingbufScaleX] / old_vals[RingbufScaleX],
  1261. new_vals[RingbufScaleY] / old_vals[RingbufScaleY],
  1262. center_w_chroma,
  1263. center_h_chroma,
  1264. transform_uv
  1265. );
  1266. CL_BLOCKING_WRITE_BUFFER(deshake_ctx->command_queue, deshake_ctx->transform_y, 9 * sizeof(float), transform_y, NULL);
  1267. CL_BLOCKING_WRITE_BUFFER(deshake_ctx->command_queue, deshake_ctx->transform_uv, 9 * sizeof(float), transform_uv, NULL);
  1268. if (deshake_ctx->debug_on)
  1269. transform_debug(avctx, new_vals, old_vals, deshake_ctx->curr_frame);
  1270. cropped_frame = ff_get_video_buffer(outlink, outlink->w, outlink->h);
  1271. if (!cropped_frame) {
  1272. err = AVERROR(ENOMEM);
  1273. goto fail;
  1274. }
  1275. transformed_frame = ff_get_video_buffer(outlink, outlink->w, outlink->h);
  1276. if (!transformed_frame) {
  1277. err = AVERROR(ENOMEM);
  1278. goto fail;
  1279. }
  1280. transforms[0] = deshake_ctx->transform_y;
  1281. transforms[1] = transforms[2] = deshake_ctx->transform_uv;
  1282. for (int p = 0; p < FF_ARRAY_ELEMS(transformed_frame->data); p++) {
  1283. // Transform all of the planes appropriately
  1284. src = (cl_mem)input_frame->data[p];
  1285. transformed = (cl_mem)transformed_frame->data[p];
  1286. if (!transformed)
  1287. break;
  1288. err = ff_opencl_filter_work_size_from_image(avctx, global_work, input_frame, p, 0);
  1289. if (err < 0)
  1290. goto fail;
  1291. CL_RUN_KERNEL_WITH_ARGS(
  1292. deshake_ctx->command_queue,
  1293. deshake_ctx->kernel_transform,
  1294. global_work,
  1295. NULL,
  1296. &transform_event,
  1297. { sizeof(cl_mem), &src },
  1298. { sizeof(cl_mem), &transformed },
  1299. { sizeof(cl_mem), &transforms[p] },
  1300. );
  1301. }
  1302. if (deshake_ctx->debug_on && !deshake_ctx->is_yuv && debug_matches.num_matches > 0) {
  1303. CL_BLOCKING_WRITE_BUFFER(
  1304. deshake_ctx->command_queue,
  1305. deshake_ctx->debug_matches,
  1306. debug_matches.num_matches * sizeof(MotionVector),
  1307. debug_matches.matches,
  1308. NULL
  1309. );
  1310. CL_BLOCKING_WRITE_BUFFER(
  1311. deshake_ctx->command_queue,
  1312. deshake_ctx->debug_model_matches,
  1313. debug_matches.num_model_matches * sizeof(MotionVector),
  1314. debug_matches.model_matches,
  1315. NULL
  1316. );
  1317. num_model_matches = debug_matches.num_model_matches;
  1318. // Invert the transform
  1319. transform_center_scale(
  1320. new_vals[RingbufX] - old_vals[RingbufX],
  1321. new_vals[RingbufY] - old_vals[RingbufY],
  1322. new_vals[RingbufRot] - old_vals[RingbufRot],
  1323. old_vals[RingbufScaleX] / new_vals[RingbufScaleX],
  1324. old_vals[RingbufScaleY] / new_vals[RingbufScaleY],
  1325. center_w,
  1326. center_h,
  1327. transform_debug_rgb
  1328. );
  1329. CL_BLOCKING_WRITE_BUFFER(deshake_ctx->command_queue, deshake_ctx->transform_y, 9 * sizeof(float), transform_debug_rgb, NULL);
  1330. transformed = (cl_mem)transformed_frame->data[0];
  1331. CL_RUN_KERNEL_WITH_ARGS(
  1332. deshake_ctx->command_queue,
  1333. deshake_ctx->kernel_draw_debug_info,
  1334. (size_t[]){ debug_matches.num_matches },
  1335. NULL,
  1336. NULL,
  1337. { sizeof(cl_mem), &transformed },
  1338. { sizeof(cl_mem), &deshake_ctx->debug_matches },
  1339. { sizeof(cl_mem), &deshake_ctx->debug_model_matches },
  1340. { sizeof(cl_int), &num_model_matches },
  1341. { sizeof(cl_mem), &deshake_ctx->transform_y }
  1342. );
  1343. }
  1344. if (deshake_ctx->should_crop) {
  1345. // Generate transforms for cropping
  1346. transform_center_scale(
  1347. (old_vals[RingbufX] - new_vals[RingbufX]) / 5,
  1348. (old_vals[RingbufY] - new_vals[RingbufY]) / 5,
  1349. (old_vals[RingbufRot] - new_vals[RingbufRot]) / 5,
  1350. new_vals[RingbufScaleX] / old_vals[RingbufScaleX],
  1351. new_vals[RingbufScaleY] / old_vals[RingbufScaleY],
  1352. center_w,
  1353. center_h,
  1354. transform_crop_y
  1355. );
  1356. update_needed_crop(&deshake_ctx->crop_y, transform_crop_y, input_frame->width, input_frame->height);
  1357. transform_center_scale(
  1358. (old_vals[RingbufX] - new_vals[RingbufX]) / (5 * luma_w_over_chroma_w),
  1359. (old_vals[RingbufY] - new_vals[RingbufY]) / (5 * luma_h_over_chroma_h),
  1360. (old_vals[RingbufRot] - new_vals[RingbufRot]) / 5,
  1361. new_vals[RingbufScaleX] / old_vals[RingbufScaleX],
  1362. new_vals[RingbufScaleY] / old_vals[RingbufScaleY],
  1363. center_w_chroma,
  1364. center_h_chroma,
  1365. transform_crop_uv
  1366. );
  1367. update_needed_crop(&deshake_ctx->crop_uv, transform_crop_uv, chroma_width, chroma_height);
  1368. crops[0] = deshake_ctx->crop_y;
  1369. crops[1] = crops[2] = deshake_ctx->crop_uv;
  1370. for (int p = 0; p < FF_ARRAY_ELEMS(cropped_frame->data); p++) {
  1371. // Crop all of the planes appropriately
  1372. dst = (cl_mem)cropped_frame->data[p];
  1373. transformed = (cl_mem)transformed_frame->data[p];
  1374. if (!dst)
  1375. break;
  1376. err = ff_opencl_filter_work_size_from_image(avctx, global_work, input_frame, p, 0);
  1377. if (err < 0)
  1378. goto fail;
  1379. CL_RUN_KERNEL_WITH_ARGS(
  1380. deshake_ctx->command_queue,
  1381. deshake_ctx->kernel_crop_upscale,
  1382. global_work,
  1383. NULL,
  1384. &crop_upscale_event,
  1385. { sizeof(cl_mem), &transformed },
  1386. { sizeof(cl_mem), &dst },
  1387. { sizeof(cl_float2), &crops[p].top_left },
  1388. { sizeof(cl_float2), &crops[p].bottom_right },
  1389. );
  1390. }
  1391. }
  1392. if (deshake_ctx->curr_frame < deshake_ctx->smooth_window / 2) {
  1393. // This means we are somewhere at the start of the video. We need to
  1394. // increment the current frame offset until it reaches the center of
  1395. // the ringbuffers (as the current frame will be located there for
  1396. // the rest of the video).
  1397. //
  1398. // The end of the video is taken care of by draining motion data
  1399. // one-by-one out of the buffer, causing the (at that point fixed)
  1400. // offset to move towards later frames' data.
  1401. ++deshake_ctx->abs_motion.curr_frame_offset;
  1402. }
  1403. if (deshake_ctx->abs_motion.data_end_offset != -1) {
  1404. // Keep the end offset in sync with the frame it's supposed to be
  1405. // positioned at
  1406. --deshake_ctx->abs_motion.data_end_offset;
  1407. if (deshake_ctx->abs_motion.data_end_offset == deshake_ctx->abs_motion.curr_frame_offset - 1) {
  1408. // The end offset would be the start of the new video sequence; flip to
  1409. // start offset
  1410. deshake_ctx->abs_motion.data_end_offset = -1;
  1411. deshake_ctx->abs_motion.data_start_offset = deshake_ctx->abs_motion.curr_frame_offset;
  1412. }
  1413. } else if (deshake_ctx->abs_motion.data_start_offset != -1) {
  1414. // Keep the start offset in sync with the frame it's supposed to be
  1415. // positioned at
  1416. --deshake_ctx->abs_motion.data_start_offset;
  1417. }
  1418. if (deshake_ctx->debug_on) {
  1419. deshake_ctx->transform_time += ff_opencl_get_event_time(transform_event);
  1420. if (deshake_ctx->should_crop) {
  1421. deshake_ctx->crop_upscale_time += ff_opencl_get_event_time(crop_upscale_event);
  1422. }
  1423. }
  1424. ++deshake_ctx->curr_frame;
  1425. if (deshake_ctx->debug_on)
  1426. av_freep(&debug_matches.matches);
  1427. if (deshake_ctx->should_crop) {
  1428. err = av_frame_copy_props(cropped_frame, input_frame);
  1429. if (err < 0)
  1430. goto fail;
  1431. av_frame_free(&transformed_frame);
  1432. av_frame_free(&input_frame);
  1433. return ff_filter_frame(outlink, cropped_frame);
  1434. } else {
  1435. err = av_frame_copy_props(transformed_frame, input_frame);
  1436. if (err < 0)
  1437. goto fail;
  1438. av_frame_free(&cropped_frame);
  1439. av_frame_free(&input_frame);
  1440. return ff_filter_frame(outlink, transformed_frame);
  1441. }
  1442. fail:
  1443. clFinish(deshake_ctx->command_queue);
  1444. if (deshake_ctx->debug_on)
  1445. if (debug_matches.matches)
  1446. av_freep(&debug_matches.matches);
  1447. av_frame_free(&input_frame);
  1448. av_frame_free(&transformed_frame);
  1449. av_frame_free(&cropped_frame);
  1450. return err;
  1451. }
  1452. // Add the given frame to the frame queue to eventually be processed.
  1453. //
  1454. // Also determines the motion from the previous frame and updates the stored
  1455. // motion information accordingly.
  1456. static int queue_frame(AVFilterLink *link, AVFrame *input_frame)
  1457. {
  1458. AVFilterContext *avctx = link->dst;
  1459. DeshakeOpenCLContext *deshake_ctx = avctx->priv;
  1460. int err;
  1461. int num_vectors;
  1462. int num_inliers = 0;
  1463. cl_int cle;
  1464. FrameDelta relative;
  1465. SimilarityMatrix model;
  1466. size_t global_work[2];
  1467. size_t harris_global_work[2];
  1468. size_t grid_32_global_work[2];
  1469. int grid_32_h, grid_32_w;
  1470. size_t local_work[2];
  1471. cl_mem src, temp;
  1472. float prev_vals[5];
  1473. float new_vals[5];
  1474. cl_event grayscale_event, harris_response_event, refine_features_event,
  1475. brief_event, match_descriptors_event, read_buf_event;
  1476. DebugMatches debug_matches;
  1477. num_vectors = 0;
  1478. local_work[0] = 8;
  1479. local_work[1] = 8;
  1480. err = ff_opencl_filter_work_size_from_image(avctx, global_work, input_frame, 0, 0);
  1481. if (err < 0)
  1482. goto fail;
  1483. err = ff_opencl_filter_work_size_from_image(avctx, harris_global_work, input_frame, 0, 8);
  1484. if (err < 0)
  1485. goto fail;
  1486. err = ff_opencl_filter_work_size_from_image(avctx, grid_32_global_work, input_frame, 0, 32);
  1487. if (err < 0)
  1488. goto fail;
  1489. // We want a single work-item for each 32x32 block of pixels in the input frame
  1490. grid_32_global_work[0] /= 32;
  1491. grid_32_global_work[1] /= 32;
  1492. grid_32_h = ROUNDED_UP_DIV(input_frame->height, 32);
  1493. grid_32_w = ROUNDED_UP_DIV(input_frame->width, 32);
  1494. if (deshake_ctx->is_yuv) {
  1495. deshake_ctx->grayscale = (cl_mem)input_frame->data[0];
  1496. } else {
  1497. src = (cl_mem)input_frame->data[0];
  1498. CL_RUN_KERNEL_WITH_ARGS(
  1499. deshake_ctx->command_queue,
  1500. deshake_ctx->kernel_grayscale,
  1501. global_work,
  1502. NULL,
  1503. &grayscale_event,
  1504. { sizeof(cl_mem), &src },
  1505. { sizeof(cl_mem), &deshake_ctx->grayscale }
  1506. );
  1507. }
  1508. CL_RUN_KERNEL_WITH_ARGS(
  1509. deshake_ctx->command_queue,
  1510. deshake_ctx->kernel_harris_response,
  1511. harris_global_work,
  1512. local_work,
  1513. &harris_response_event,
  1514. { sizeof(cl_mem), &deshake_ctx->grayscale },
  1515. { sizeof(cl_mem), &deshake_ctx->harris_buf }
  1516. );
  1517. CL_RUN_KERNEL_WITH_ARGS(
  1518. deshake_ctx->command_queue,
  1519. deshake_ctx->kernel_refine_features,
  1520. grid_32_global_work,
  1521. NULL,
  1522. &refine_features_event,
  1523. { sizeof(cl_mem), &deshake_ctx->grayscale },
  1524. { sizeof(cl_mem), &deshake_ctx->harris_buf },
  1525. { sizeof(cl_mem), &deshake_ctx->refined_features },
  1526. { sizeof(cl_int), &deshake_ctx->refine_features }
  1527. );
  1528. CL_RUN_KERNEL_WITH_ARGS(
  1529. deshake_ctx->command_queue,
  1530. deshake_ctx->kernel_brief_descriptors,
  1531. grid_32_global_work,
  1532. NULL,
  1533. &brief_event,
  1534. { sizeof(cl_mem), &deshake_ctx->grayscale },
  1535. { sizeof(cl_mem), &deshake_ctx->refined_features },
  1536. { sizeof(cl_mem), &deshake_ctx->descriptors },
  1537. { sizeof(cl_mem), &deshake_ctx->brief_pattern}
  1538. );
  1539. if (!av_fifo_can_read(deshake_ctx->abs_motion.ringbuffers[RingbufX])) {
  1540. // This is the first frame we've been given to queue, meaning there is
  1541. // no previous frame to match descriptors to
  1542. goto no_motion_data;
  1543. }
  1544. CL_RUN_KERNEL_WITH_ARGS(
  1545. deshake_ctx->command_queue,
  1546. deshake_ctx->kernel_match_descriptors,
  1547. grid_32_global_work,
  1548. NULL,
  1549. &match_descriptors_event,
  1550. { sizeof(cl_mem), &deshake_ctx->prev_refined_features },
  1551. { sizeof(cl_mem), &deshake_ctx->refined_features },
  1552. { sizeof(cl_mem), &deshake_ctx->descriptors },
  1553. { sizeof(cl_mem), &deshake_ctx->prev_descriptors },
  1554. { sizeof(cl_mem), &deshake_ctx->matches }
  1555. );
  1556. cle = clEnqueueReadBuffer(
  1557. deshake_ctx->command_queue,
  1558. deshake_ctx->matches,
  1559. CL_TRUE,
  1560. 0,
  1561. grid_32_h * grid_32_w * sizeof(MotionVector),
  1562. deshake_ctx->matches_host,
  1563. 0,
  1564. NULL,
  1565. &read_buf_event
  1566. );
  1567. CL_FAIL_ON_ERROR(AVERROR(EIO), "Failed to read matches to host: %d.\n", cle);
  1568. num_vectors = make_vectors_contig(deshake_ctx, grid_32_h, grid_32_w);
  1569. if (num_vectors < 10) {
  1570. // Not enough matches to get reliable motion data for this frame
  1571. //
  1572. // From this point on all data is relative to this frame rather than the
  1573. // original frame. We have to make sure that we don't mix values that were
  1574. // relative to the original frame with the new values relative to this
  1575. // frame when doing the gaussian smoothing. We keep track of where the old
  1576. // values end using this data_end_offset field in order to accomplish
  1577. // that goal.
  1578. //
  1579. // If no motion data is present for multiple frames in a short window of
  1580. // time, we leave the end where it was to avoid mixing 0s in with the
  1581. // old data (and just treat them all as part of the new values)
  1582. if (deshake_ctx->abs_motion.data_end_offset == -1) {
  1583. deshake_ctx->abs_motion.data_end_offset =
  1584. av_fifo_can_read(deshake_ctx->abs_motion.ringbuffers[RingbufX]) - 1;
  1585. }
  1586. goto no_motion_data;
  1587. }
  1588. if (!estimate_affine_2d(
  1589. deshake_ctx,
  1590. deshake_ctx->matches_contig_host,
  1591. &debug_matches,
  1592. num_vectors,
  1593. model.matrix,
  1594. 10.0,
  1595. 3000,
  1596. 0.999999999999
  1597. )) {
  1598. goto no_motion_data;
  1599. }
  1600. for (int i = 0; i < num_vectors; i++) {
  1601. if (deshake_ctx->matches_contig_host[i].should_consider) {
  1602. deshake_ctx->inliers[num_inliers] = deshake_ctx->matches_contig_host[i];
  1603. num_inliers++;
  1604. }
  1605. }
  1606. if (!minimize_error(
  1607. deshake_ctx,
  1608. deshake_ctx->inliers,
  1609. &debug_matches,
  1610. num_inliers,
  1611. model.matrix,
  1612. 400
  1613. )) {
  1614. goto no_motion_data;
  1615. }
  1616. relative = decompose_transform(model.matrix);
  1617. // Get the absolute transform data for the previous frame
  1618. for (int i = 0; i < RingbufCount; i++) {
  1619. av_fifo_peek(
  1620. deshake_ctx->abs_motion.ringbuffers[i],
  1621. &prev_vals[i], 1,
  1622. av_fifo_can_read(deshake_ctx->abs_motion.ringbuffers[i]) - 1);
  1623. }
  1624. new_vals[RingbufX] = prev_vals[RingbufX] + relative.translation.s[0];
  1625. new_vals[RingbufY] = prev_vals[RingbufY] + relative.translation.s[1];
  1626. new_vals[RingbufRot] = prev_vals[RingbufRot] + relative.rotation;
  1627. new_vals[RingbufScaleX] = prev_vals[RingbufScaleX] / relative.scale.s[0];
  1628. new_vals[RingbufScaleY] = prev_vals[RingbufScaleY] / relative.scale.s[1];
  1629. if (deshake_ctx->debug_on) {
  1630. if (!deshake_ctx->is_yuv) {
  1631. deshake_ctx->grayscale_time += ff_opencl_get_event_time(grayscale_event);
  1632. }
  1633. deshake_ctx->harris_response_time += ff_opencl_get_event_time(harris_response_event);
  1634. deshake_ctx->refine_features_time += ff_opencl_get_event_time(refine_features_event);
  1635. deshake_ctx->brief_descriptors_time += ff_opencl_get_event_time(brief_event);
  1636. deshake_ctx->match_descriptors_time += ff_opencl_get_event_time(match_descriptors_event);
  1637. deshake_ctx->read_buf_time += ff_opencl_get_event_time(read_buf_event);
  1638. }
  1639. goto end;
  1640. no_motion_data:
  1641. new_vals[RingbufX] = 0.0f;
  1642. new_vals[RingbufY] = 0.0f;
  1643. new_vals[RingbufRot] = 0.0f;
  1644. new_vals[RingbufScaleX] = 1.0f;
  1645. new_vals[RingbufScaleY] = 1.0f;
  1646. for (int i = 0; i < num_vectors; i++) {
  1647. deshake_ctx->matches_contig_host[i].should_consider = 0;
  1648. }
  1649. debug_matches.num_model_matches = 0;
  1650. if (deshake_ctx->debug_on) {
  1651. av_log(avctx, AV_LOG_VERBOSE,
  1652. "\n[ALERT] No motion data found in queue_frame, motion reset to 0\n\n"
  1653. );
  1654. }
  1655. goto end;
  1656. end:
  1657. // Swap the descriptor buffers (we don't need the previous frame's descriptors
  1658. // again so we will use that space for the next frame's descriptors)
  1659. temp = deshake_ctx->prev_descriptors;
  1660. deshake_ctx->prev_descriptors = deshake_ctx->descriptors;
  1661. deshake_ctx->descriptors = temp;
  1662. // Same for the refined features
  1663. temp = deshake_ctx->prev_refined_features;
  1664. deshake_ctx->prev_refined_features = deshake_ctx->refined_features;
  1665. deshake_ctx->refined_features = temp;
  1666. if (deshake_ctx->debug_on) {
  1667. if (num_vectors == 0) {
  1668. debug_matches.matches = NULL;
  1669. } else {
  1670. debug_matches.matches = av_malloc_array(num_vectors, sizeof(MotionVector));
  1671. if (!debug_matches.matches) {
  1672. err = AVERROR(ENOMEM);
  1673. goto fail;
  1674. }
  1675. }
  1676. for (int i = 0; i < num_vectors; i++) {
  1677. debug_matches.matches[i] = deshake_ctx->matches_contig_host[i];
  1678. }
  1679. debug_matches.num_matches = num_vectors;
  1680. av_fifo_write(
  1681. deshake_ctx->abs_motion.debug_matches,
  1682. &debug_matches, 1);
  1683. }
  1684. for (int i = 0; i < RingbufCount; i++) {
  1685. av_fifo_write(deshake_ctx->abs_motion.ringbuffers[i], &new_vals[i], 1);
  1686. }
  1687. return ff_framequeue_add(&deshake_ctx->fq, input_frame);
  1688. fail:
  1689. clFinish(deshake_ctx->command_queue);
  1690. av_frame_free(&input_frame);
  1691. return err;
  1692. }
  1693. static int activate(AVFilterContext *ctx)
  1694. {
  1695. AVFilterLink *inlink = ctx->inputs[0];
  1696. AVFilterLink *outlink = ctx->outputs[0];
  1697. DeshakeOpenCLContext *deshake_ctx = ctx->priv;
  1698. AVFrame *frame = NULL;
  1699. int ret, status;
  1700. int64_t pts;
  1701. FF_FILTER_FORWARD_STATUS_BACK(outlink, inlink);
  1702. if (!deshake_ctx->eof) {
  1703. ret = ff_inlink_consume_frame(inlink, &frame);
  1704. if (ret < 0)
  1705. return ret;
  1706. if (ret > 0) {
  1707. if (!frame->hw_frames_ctx)
  1708. return AVERROR(EINVAL);
  1709. if (!deshake_ctx->initialized) {
  1710. ret = deshake_opencl_init(ctx);
  1711. if (ret < 0)
  1712. return ret;
  1713. }
  1714. // If there is no more space in the ringbuffers, remove the oldest
  1715. // values to make room for the new ones
  1716. if (!av_fifo_can_write(deshake_ctx->abs_motion.ringbuffers[RingbufX])) {
  1717. for (int i = 0; i < RingbufCount; i++) {
  1718. av_fifo_drain2(deshake_ctx->abs_motion.ringbuffers[i], 1);
  1719. }
  1720. }
  1721. ret = queue_frame(inlink, frame);
  1722. if (ret < 0)
  1723. return ret;
  1724. if (ret >= 0) {
  1725. // See if we have enough buffered frames to process one
  1726. //
  1727. // "enough" is half the smooth window of queued frames into the future
  1728. if (ff_framequeue_queued_frames(&deshake_ctx->fq) >= deshake_ctx->smooth_window / 2) {
  1729. return filter_frame(inlink, ff_framequeue_take(&deshake_ctx->fq));
  1730. }
  1731. }
  1732. }
  1733. }
  1734. if (!deshake_ctx->eof && ff_inlink_acknowledge_status(inlink, &status, &pts)) {
  1735. if (status == AVERROR_EOF) {
  1736. deshake_ctx->eof = 1;
  1737. }
  1738. }
  1739. if (deshake_ctx->eof) {
  1740. // Finish processing the rest of the frames in the queue.
  1741. while(ff_framequeue_queued_frames(&deshake_ctx->fq) != 0) {
  1742. for (int i = 0; i < RingbufCount; i++) {
  1743. av_fifo_drain2(deshake_ctx->abs_motion.ringbuffers[i], 1);
  1744. }
  1745. ret = filter_frame(inlink, ff_framequeue_take(&deshake_ctx->fq));
  1746. if (ret < 0) {
  1747. return ret;
  1748. }
  1749. }
  1750. if (deshake_ctx->debug_on) {
  1751. av_log(ctx, AV_LOG_VERBOSE,
  1752. "Average kernel execution times:\n"
  1753. "\t grayscale: %0.3f ms\n"
  1754. "\t harris_response: %0.3f ms\n"
  1755. "\t refine_features: %0.3f ms\n"
  1756. "\tbrief_descriptors: %0.3f ms\n"
  1757. "\tmatch_descriptors: %0.3f ms\n"
  1758. "\t transform: %0.3f ms\n"
  1759. "\t crop_upscale: %0.3f ms\n"
  1760. "Average buffer read times:\n"
  1761. "\t features buf: %0.3f ms\n",
  1762. averaged_event_time_ms(deshake_ctx->grayscale_time, deshake_ctx->curr_frame),
  1763. averaged_event_time_ms(deshake_ctx->harris_response_time, deshake_ctx->curr_frame),
  1764. averaged_event_time_ms(deshake_ctx->refine_features_time, deshake_ctx->curr_frame),
  1765. averaged_event_time_ms(deshake_ctx->brief_descriptors_time, deshake_ctx->curr_frame),
  1766. averaged_event_time_ms(deshake_ctx->match_descriptors_time, deshake_ctx->curr_frame),
  1767. averaged_event_time_ms(deshake_ctx->transform_time, deshake_ctx->curr_frame),
  1768. averaged_event_time_ms(deshake_ctx->crop_upscale_time, deshake_ctx->curr_frame),
  1769. averaged_event_time_ms(deshake_ctx->read_buf_time, deshake_ctx->curr_frame)
  1770. );
  1771. }
  1772. ff_outlink_set_status(outlink, AVERROR_EOF, deshake_ctx->duration);
  1773. return 0;
  1774. }
  1775. if (!deshake_ctx->eof) {
  1776. FF_FILTER_FORWARD_WANTED(outlink, inlink);
  1777. }
  1778. return FFERROR_NOT_READY;
  1779. }
  1780. static const AVFilterPad deshake_opencl_inputs[] = {
  1781. {
  1782. .name = "default",
  1783. .type = AVMEDIA_TYPE_VIDEO,
  1784. .config_props = &ff_opencl_filter_config_input,
  1785. },
  1786. };
  1787. static const AVFilterPad deshake_opencl_outputs[] = {
  1788. {
  1789. .name = "default",
  1790. .type = AVMEDIA_TYPE_VIDEO,
  1791. .config_props = &ff_opencl_filter_config_output,
  1792. },
  1793. };
  1794. #define OFFSET(x) offsetof(DeshakeOpenCLContext, x)
  1795. #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
  1796. static const AVOption deshake_opencl_options[] = {
  1797. {
  1798. "tripod", "simulates a tripod by preventing any camera movement whatsoever "
  1799. "from the original frame",
  1800. OFFSET(tripod_mode), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, FLAGS
  1801. },
  1802. {
  1803. "debug", "turn on additional debugging information",
  1804. OFFSET(debug_on), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, FLAGS
  1805. },
  1806. {
  1807. "adaptive_crop", "attempt to subtly crop borders to reduce mirrored content",
  1808. OFFSET(should_crop), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, FLAGS
  1809. },
  1810. {
  1811. "refine_features", "refine feature point locations at a sub-pixel level",
  1812. OFFSET(refine_features), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, FLAGS
  1813. },
  1814. {
  1815. "smooth_strength", "smoothing strength (0 attempts to adaptively determine optimal strength)",
  1816. OFFSET(smooth_percent), AV_OPT_TYPE_FLOAT, {.dbl = 0.0f}, 0.0f, 1.0f, FLAGS
  1817. },
  1818. {
  1819. "smooth_window_multiplier", "multiplier for number of frames to buffer for motion data",
  1820. OFFSET(smooth_window_multiplier), AV_OPT_TYPE_FLOAT, {.dbl = 2.0}, 0.1, 10.0, FLAGS
  1821. },
  1822. { NULL }
  1823. };
  1824. AVFILTER_DEFINE_CLASS(deshake_opencl);
  1825. const AVFilter ff_vf_deshake_opencl = {
  1826. .name = "deshake_opencl",
  1827. .description = NULL_IF_CONFIG_SMALL("Feature-point based video stabilization filter"),
  1828. .priv_size = sizeof(DeshakeOpenCLContext),
  1829. .priv_class = &deshake_opencl_class,
  1830. .init = &ff_opencl_filter_init,
  1831. .uninit = &deshake_opencl_uninit,
  1832. .activate = activate,
  1833. FILTER_INPUTS(deshake_opencl_inputs),
  1834. FILTER_OUTPUTS(deshake_opencl_outputs),
  1835. FILTER_SINGLE_PIXFMT(AV_PIX_FMT_OPENCL),
  1836. .flags_internal = FF_FILTER_FLAG_HWFRAME_AWARE,
  1837. .flags = AVFILTER_FLAG_HWDEVICE,
  1838. };