-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.cpp
416 lines (335 loc) · 12.4 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
/*
* Copyright (c) 2017 Dmitry Odintsov
* This code is licensed under the MIT license (MIT)
* (http://opensource.org/licenses/MIT)
*/
#include <vips/vips8>
#include <cstdlib>
#include <getopt.h>
#include <iomanip>
#include <iostream>
#include <map>
#include <thread>
#include <vector>
#include "Reporter.hpp"
#include "WorkerPool.hpp"
static const char* s_appName = "aniniscale";
static const char* s_versionInfo = "1.0.1";
struct Arguments
{
// Required
std::string in;
std::string out;
// Optional
int x_blockSize = 8;
int y_blockSize = 8;
int taskBlockSide = 64;
int reportingTimeout = 5;
bool help = false;
//! Returns the validity of argument set
bool IsValid() const
{
// arguments are valid only if:
return !in.empty() && !out.empty() && // both in and out are set
!help && // -h/--help is not set
x_blockSize >= 1 && y_blockSize >= 1; // x and y block sizes are positive integers
}
};
void PrintUsage(const Arguments& arguments)
{
if (!arguments.help && !arguments.IsValid())
{
if (arguments.in.empty())
{
std::cout << "Input image path is required!" << std::endl;
}
if (arguments.out.empty())
{
std::cout << "Output image path is required!" << std::endl;
}
if (arguments.x_blockSize < 1)
{
std::cout << "-x/--x-block must be a positive integer" << std::endl;
}
if (arguments.y_blockSize < 1)
{
std::cout << "-y/--y-block must be a positive integer" << std::endl;
}
std::cout << std::endl;
}
if (arguments.help)
{
std::cout << s_appName << " v" << s_versionInfo << std::endl;
std::cout << "Downscales image by reducing blocks in original image to a single pixel of dominant color." << std::endl;
std::cout << std::endl;
std::cout << "Divides given image into multiple task areas. The size of each area is determined by a number of factors:" << std::endl;
std::cout << " - initial image size;" << std::endl;
std::cout << " - number of processing threads;" << std::endl;
std::cout << " - block size;" << std::endl;
std::cout << " - number of blocks inside each task." << std::endl;
std::cout << std::endl;
std::cout << "Each task consists of the following steps:" << std::endl;
std::cout << " 1. Pick a block of pixels" << std::endl;
std::cout << " 2. Find dominant color in this block" << std::endl;
std::cout << " 3. Write dominant color to resulting image" << std::endl;
std::cout << "After all tasks are complete, resulting image is saved as png" << std::endl;
std::cout << std::endl;
}
std::cout << "Usage:" << std::endl;
std::cout << s_appName << " [options] -i/--input INPUT -o/--output OUTPUT" << std::endl;
std::cout << std::endl;
const uint32_t requiredWidth = 32;
std::cout << "Required arguments:" << std::endl;
std::cout << " " << std::left << std::setw(requiredWidth) << "-i INPUT, --input=INPUT" << "path to input image" << std::endl;
std::cout << " " << std::left << std::setw(requiredWidth) << "-o OUTPUT, --output=OUTPUT" << "path to output image" << std::endl;
std::cout << std::endl;
Arguments defaultArgs;
const uint32_t optionalWidth = 32;
std::cout << "Optional arguments:" << std::endl;
std::cout << " " << std::left << std::setw(optionalWidth) << "-h, --help" << "prints detailed help message" << std::endl;
std::cout << " " << std::left << std::setw(optionalWidth) << "-x NUM, --x-block=NUM" << "block size on X axis [default " << defaultArgs.x_blockSize << "]" << std::endl;
std::cout << " " << std::left << std::setw(optionalWidth) << "-y NUM, --y-block=NUM" << "block size on Y axis [default " << defaultArgs.y_blockSize << "]" << std::endl;
std::cout << " " << std::left << std::setw(optionalWidth) << "-t NUM, --task-block-side=NUM" << "maximum number of blocks in any processing task [default " << defaultArgs.taskBlockSide << "]" << std::endl;
std::cout << " " << std::left << std::setw(optionalWidth) << "-r NUM, --reporting-timeout=NUM" << "minimum timeout between log reports in seconds [default " << defaultArgs.reportingTimeout << "]" << std::endl;
}
Arguments ProcessArgs(int argc, char** argv)
{
static struct option options[] = {
{"x-block", required_argument, 0, 'x'},
{"y-block", required_argument, 0, 'y'},
{"input", required_argument, 0, 'i'},
{"output", required_argument, 0, 'o'},
{"task-block-side", required_argument, 0, 't'},
{"reporting-timeout", required_argument, 0, 'r'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
};
Arguments arguments;
while (true)
{
int c = getopt_long(argc, argv, "x:y:i:o:t:r:h", options, 0);
if (c == -1)
{
break;
}
switch (c)
{
case 'x': // x-block
{
arguments.x_blockSize = atoi(optarg);
break;
}
case 'y': // y-block
{
arguments.y_blockSize = atoi(optarg);
break;
}
case 'i': // input
{
arguments.in = std::string(optarg);
break;
}
case 'o': // output
{
arguments.out = std::string(optarg);
break;
}
case 't': // task-block-side
{
arguments.taskBlockSide = atoi(optarg);
break;
}
case 'r': // reporting-timeout
{
arguments.reportingTimeout = atoi(optarg);
break;
}
case 'h': // help
{
arguments.help = true;
break;
}
default:
{
break;
}
}
}
return arguments;
}
int Process(const Arguments& arguments)
{
//! Open the image and check channel count
vips::VImage img;
try
{
img = vips::VImage::new_from_file( arguments.in.c_str() );
}
catch( vips::VError& e )
{
std::cout << "Error occured while opening image " << arguments.in.c_str() << std::endl;
std::cerr << e.what() << std::endl;
return -1;
}
int bandCount = img.bands();
//! If both blocks are 1, we can just save the image
if (arguments.x_blockSize == 1 && arguments.y_blockSize == 1)
{
img.pngsave( (char*) arguments.out.c_str() );
return 0;
}
//! Get image information and estimate how it will be divided
const uint32_t width = img.width();
const uint32_t height = img.height();
const uint32_t x_tiles = width / arguments.x_blockSize;
const uint32_t y_tiles = height / arguments.y_blockSize;
uint32_t totalPixels = width * height;
//! Check how many threads we can run
uint32_t workerCount = std::thread::hardware_concurrency();
//! Make sure it's a multiple of 2
if (workerCount % 2 != 0)
{
workerCount += workerCount % 2;
}
//! If we have too much workers, cut their number until we have enough work
while (workerCount > x_tiles || workerCount > y_tiles)
{
workerCount -= 2;
}
//! If we ended up without workers, bring back one
if (0 == workerCount)
{
workerCount = 1;
}
//! Tasks shall not be too big, so we keep them manageable
int x_sectionsInTask = x_tiles / workerCount;
while (x_sectionsInTask > arguments.taskBlockSide)
{
x_sectionsInTask /= 2;
}
int y_sectionsInTask = y_tiles / workerCount;
while (y_sectionsInTask > arguments.taskBlockSide)
{
y_sectionsInTask /= 2;
}
const uint32_t x_taskSize = x_sectionsInTask * arguments.x_blockSize;
const uint32_t y_taskSize = y_sectionsInTask * arguments.y_blockSize;
const uint32_t x_taskCount = width / x_taskSize;
const uint32_t y_taskCount = height / y_taskSize;
//! Store total number of pixels on the image for the reporting
Reporter::s_taskPixels = x_taskSize * y_taskSize;
Reporter::s_tasksTotal = x_taskCount * y_taskCount;
WorkerPool pool(bandCount, arguments.x_blockSize, arguments.y_blockSize);
std::cout << "Creating " << x_taskCount * y_taskCount << " tasks of size " << x_taskSize << "x" << y_taskSize << std::endl;
std::map<std::pair<uint32_t, uint32_t>, std::vector<uint8_t>> result;
//! Allocate all needed memory
for (uint32_t x_task = 0; x_task < x_taskCount; ++x_task)
{
for (uint32_t y_task = 0; y_task < y_taskCount; ++y_task)
{
result[std::pair<uint32_t, uint32_t>(x_task, y_task)].resize(x_sectionsInTask * y_sectionsInTask * bandCount);
}
}
auto ReportTaskCreationProgress = [&](uint32_t count){
static std::time_t lastTime = std::time(0);
const std::time_t now = std::time(0);
if (now - lastTime > 5)
{
std::cout << "Progress: " << count << "/" << result.size() << std::endl;
lastTime = now;
}
};
//! Create tasks to process each section
for (uint32_t x_task = 0; x_task < x_taskCount; ++x_task)
{
for (uint32_t y_task = 0; y_task < y_taskCount; ++y_task)
{
std::pair<uint32_t, uint32_t> coords(x_task, y_task);
vips::VImage area = img.extract_area(coords.first * x_taskSize,
coords.second * y_taskSize,
x_taskSize,
y_taskSize);
pool.PushTask([=, &result](WorkerPool& worker){ worker.ProcessImage(area, result[std::pair<uint32_t, uint32_t>(x_task, y_task)]); });
ReportTaskCreationProgress(x_task * y_taskCount + y_task);
}
}
std::cout << "Task creation complete" << std::endl;
std::cout << "Total area to be processed: " << width << "x" << height << " (" << totalPixels << "px)" << std::endl;
//! Spawn workers
std::vector<std::thread> workers;
workers.resize(workerCount);
std::cout << "Initializing " << workerCount << " workers" << std::endl;
for (uint32_t i = 0; i < workerCount; ++i)
{
workers[i] = std::thread(&WorkerPool::Worker, &pool);
}
//! Wait for all workers to finish
for (uint32_t i = 0; i < workerCount; ++i)
{
workers[i].join();
}
workers.clear();
std::cout << "Processing complete, preparing resulting image" << std::endl;
//! Prepare the buffer to store final output
std::vector<uint8_t> outBuffer;
outBuffer.resize(x_tiles * y_tiles * bandCount);
vips::VImage outImg = vips::VImage::new_from_memory(outBuffer.data(), outBuffer.size(),
x_tiles, y_tiles, bandCount, img.format());
try
{
//! Go through worker results and place them in resulting image
for (auto& r : result)
{
const std::pair<uint32_t, uint32_t>& coords = r.first;
std::vector<uint8_t>& buffer = r.second;
vips::VImage block = vips::VImage::new_from_memory(buffer.data(), buffer.size(),
x_sectionsInTask, y_sectionsInTask, bandCount, img.format());
outImg = outImg.insert(block, coords.first * x_sectionsInTask, coords.second * y_sectionsInTask);
}
}
catch( vips::VError& e )
{
std::cout << "Error occured while preparing resulting image" << std::endl;
std::cerr << e.what() << std::endl;
return -1;
}
try
{
std::cout << "Saving resulting image" << std::endl;
//! Save the image
outImg.pngsave( (char*) arguments.out.c_str() );
}
catch( vips::VError& e )
{
std::cout << "Error occured while saving resulting image to " << arguments.out.c_str() << std::endl;
std::cerr << e.what() << std::endl;
return -1;
}
return 0;
}
int main(int argc, char** argv)
{
//! Initialize VIPS library
if( VIPS_INIT( argv[0] ) )
{
return -1;
}
std::string in;
std::string out;
bool help = false;
Arguments arguments = ProcessArgs(argc, argv);
if (!arguments.IsValid())
{
PrintUsage(arguments);
return help ? 0 : -1;
}
int retVal = Process(arguments);
//! Deinitialize
vips_shutdown();
if (0 == retVal)
{
//! Report elapsed time
Reporter::ReportElapsedTime();
}
return retVal;
}