denoising.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924
  1. /*
  2. * Copyright 2011-2018 Blender Foundation
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "render/denoising.h"
  17. #include "kernel/filter/filter_defines.h"
  18. #include "util/util_foreach.h"
  19. #include "util/util_map.h"
  20. #include "util/util_system.h"
  21. #include "util/util_time.h"
  22. #include <OpenImageIO/filesystem.h>
  23. CCL_NAMESPACE_BEGIN
  24. /* Utility Functions */
  25. static void print_progress(int num, int total, int frame, int num_frames)
  26. {
  27. const char *label = "Denoise Frame ";
  28. int cols = system_console_width();
  29. cols -= strlen(label);
  30. int len = 1;
  31. for (int x = total; x > 9; x /= 10) {
  32. len++;
  33. }
  34. int bars = cols - 2 * len - 6;
  35. printf("\r%s", label);
  36. if (num_frames > 1) {
  37. int frame_len = 1;
  38. for (int x = num_frames - 1; x > 9; x /= 10) {
  39. frame_len++;
  40. }
  41. bars -= frame_len + 2;
  42. printf("%*d ", frame_len, frame);
  43. }
  44. int v = int(float(num) * bars / total);
  45. printf("[");
  46. for (int i = 0; i < v; i++) {
  47. printf("=");
  48. }
  49. if (v < bars) {
  50. printf(">");
  51. }
  52. for (int i = v + 1; i < bars; i++) {
  53. printf(" ");
  54. }
  55. printf(string_printf("] %%%dd / %d", len, total).c_str(), num);
  56. fflush(stdout);
  57. }
  58. /* Splits in at its last dot, setting suffix to the part after the dot and in to the part before
  59. * it. Returns whether a dot was found. */
  60. static bool split_last_dot(string &in, string &suffix)
  61. {
  62. size_t pos = in.rfind(".");
  63. if (pos == string::npos) {
  64. return false;
  65. }
  66. suffix = in.substr(pos + 1);
  67. in = in.substr(0, pos);
  68. return true;
  69. }
  70. /* Separate channel names as generated by Blender.
  71. * If views is true:
  72. * Inputs are expected in the form RenderLayer.Pass.View.Channel, sets renderlayer to
  73. * "RenderLayer.View" Otherwise: Inputs are expected in the form RenderLayer.Pass.Channel */
  74. static bool parse_channel_name(
  75. string name, string &renderlayer, string &pass, string &channel, bool multiview_channels)
  76. {
  77. if (!split_last_dot(name, channel)) {
  78. return false;
  79. }
  80. string view;
  81. if (multiview_channels && !split_last_dot(name, view)) {
  82. return false;
  83. }
  84. if (!split_last_dot(name, pass)) {
  85. return false;
  86. }
  87. renderlayer = name;
  88. if (multiview_channels) {
  89. renderlayer += "." + view;
  90. }
  91. return true;
  92. }
  93. /* Channel Mapping */
  94. struct ChannelMapping {
  95. int channel;
  96. string name;
  97. };
  98. static void fill_mapping(vector<ChannelMapping> &map, int pos, string name, string channels)
  99. {
  100. for (const char *chan = channels.c_str(); *chan; chan++) {
  101. map.push_back({pos++, name + "." + *chan});
  102. }
  103. }
  104. static const int INPUT_NUM_CHANNELS = 15;
  105. static const int INPUT_DENOISING_DEPTH = 0;
  106. static const int INPUT_DENOISING_NORMAL = 1;
  107. static const int INPUT_DENOISING_SHADOWING = 4;
  108. static const int INPUT_DENOISING_ALBEDO = 5;
  109. static const int INPUT_NOISY_IMAGE = 8;
  110. static const int INPUT_DENOISING_VARIANCE = 11;
  111. static const int INPUT_DENOISING_INTENSITY = 14;
  112. static vector<ChannelMapping> input_channels()
  113. {
  114. vector<ChannelMapping> map;
  115. fill_mapping(map, INPUT_DENOISING_DEPTH, "Denoising Depth", "Z");
  116. fill_mapping(map, INPUT_DENOISING_NORMAL, "Denoising Normal", "XYZ");
  117. fill_mapping(map, INPUT_DENOISING_SHADOWING, "Denoising Shadowing", "X");
  118. fill_mapping(map, INPUT_DENOISING_ALBEDO, "Denoising Albedo", "RGB");
  119. fill_mapping(map, INPUT_NOISY_IMAGE, "Noisy Image", "RGB");
  120. fill_mapping(map, INPUT_DENOISING_VARIANCE, "Denoising Variance", "RGB");
  121. fill_mapping(map, INPUT_DENOISING_INTENSITY, "Denoising Intensity", "X");
  122. return map;
  123. }
  124. static const int OUTPUT_NUM_CHANNELS = 3;
  125. static vector<ChannelMapping> output_channels()
  126. {
  127. vector<ChannelMapping> map;
  128. fill_mapping(map, 0, "Combined", "RGB");
  129. return map;
  130. }
  131. /* Renderlayer Handling */
  132. bool DenoiseImageLayer::detect_denoising_channels()
  133. {
  134. /* Map device input to image channels. */
  135. input_to_image_channel.clear();
  136. input_to_image_channel.resize(INPUT_NUM_CHANNELS, -1);
  137. foreach (const ChannelMapping &mapping, input_channels()) {
  138. vector<string>::iterator i = find(channels.begin(), channels.end(), mapping.name);
  139. if (i == channels.end()) {
  140. return false;
  141. }
  142. size_t input_channel = mapping.channel;
  143. size_t layer_channel = i - channels.begin();
  144. input_to_image_channel[input_channel] = layer_to_image_channel[layer_channel];
  145. }
  146. /* Map device output to image channels. */
  147. output_to_image_channel.clear();
  148. output_to_image_channel.resize(OUTPUT_NUM_CHANNELS, -1);
  149. foreach (const ChannelMapping &mapping, output_channels()) {
  150. vector<string>::iterator i = find(channels.begin(), channels.end(), mapping.name);
  151. if (i == channels.end()) {
  152. return false;
  153. }
  154. size_t output_channel = mapping.channel;
  155. size_t layer_channel = i - channels.begin();
  156. output_to_image_channel[output_channel] = layer_to_image_channel[layer_channel];
  157. }
  158. /* Check that all buffer channels are correctly set. */
  159. for (int i = 0; i < INPUT_NUM_CHANNELS; i++) {
  160. assert(input_to_image_channel[i] >= 0);
  161. }
  162. for (int i = 0; i < OUTPUT_NUM_CHANNELS; i++) {
  163. assert(output_to_image_channel[i] >= 0);
  164. }
  165. return true;
  166. }
  167. bool DenoiseImageLayer::match_channels(int neighbor,
  168. const std::vector<string> &channelnames,
  169. const std::vector<string> &neighbor_channelnames)
  170. {
  171. neighbor_input_to_image_channel.resize(neighbor + 1);
  172. vector<int> &mapping = neighbor_input_to_image_channel[neighbor];
  173. assert(mapping.size() == 0);
  174. mapping.resize(input_to_image_channel.size(), -1);
  175. for (int i = 0; i < input_to_image_channel.size(); i++) {
  176. const string &channel = channelnames[input_to_image_channel[i]];
  177. std::vector<string>::const_iterator frame_channel = find(
  178. neighbor_channelnames.begin(), neighbor_channelnames.end(), channel);
  179. if (frame_channel == neighbor_channelnames.end()) {
  180. return false;
  181. }
  182. mapping[i] = frame_channel - neighbor_channelnames.begin();
  183. }
  184. return true;
  185. }
  186. /* Denoise Task */
  187. DenoiseTask::DenoiseTask(Device *device,
  188. Denoiser *denoiser,
  189. int frame,
  190. const vector<int> &neighbor_frames)
  191. : denoiser(denoiser),
  192. device(device),
  193. frame(frame),
  194. neighbor_frames(neighbor_frames),
  195. current_layer(0),
  196. input_pixels(device, "filter input buffer", MEM_READ_ONLY),
  197. num_tiles(0)
  198. {
  199. image.samples = denoiser->samples_override;
  200. }
  201. DenoiseTask::~DenoiseTask()
  202. {
  203. free();
  204. }
  205. /* Device callbacks */
  206. bool DenoiseTask::acquire_tile(Device *device, Device *tile_device, RenderTile &tile)
  207. {
  208. thread_scoped_lock tile_lock(tiles_mutex);
  209. if (tiles.empty()) {
  210. return false;
  211. }
  212. tile = tiles.front();
  213. tiles.pop_front();
  214. device->map_tile(tile_device, tile);
  215. print_progress(num_tiles - tiles.size(), num_tiles, frame, denoiser->num_frames);
  216. return true;
  217. }
  218. /* Mapping tiles is required for regular rendering since each tile has its separate memory
  219. * which may be allocated on a different device.
  220. * For standalone denoising, there is a single memory that is present on all devices, so the only
  221. * thing that needs to be done here is to specify the surrounding tile geometry.
  222. *
  223. * However, since there is only one large memory, the denoised result has to be written to
  224. * a different buffer to avoid having to copy an entire horizontal slice of the image. */
  225. void DenoiseTask::map_neighboring_tiles(RenderTile *tiles, Device *tile_device)
  226. {
  227. /* Fill tile information. */
  228. for (int i = 0; i < 9; i++) {
  229. if (i == 4) {
  230. continue;
  231. }
  232. int dx = (i % 3) - 1;
  233. int dy = (i / 3) - 1;
  234. tiles[i].x = clamp(tiles[4].x + dx * denoiser->tile_size.x, 0, image.width);
  235. tiles[i].w = clamp(tiles[4].x + (dx + 1) * denoiser->tile_size.x, 0, image.width) - tiles[i].x;
  236. tiles[i].y = clamp(tiles[4].y + dy * denoiser->tile_size.y, 0, image.height);
  237. tiles[i].h = clamp(tiles[4].y + (dy + 1) * denoiser->tile_size.y, 0, image.height) -
  238. tiles[i].y;
  239. tiles[i].buffer = tiles[4].buffer;
  240. tiles[i].offset = tiles[4].offset;
  241. tiles[i].stride = image.width;
  242. }
  243. /* Allocate output buffer. */
  244. device_vector<float> *output_mem = new device_vector<float>(
  245. tile_device, "denoising_output", MEM_READ_WRITE);
  246. output_mem->alloc(OUTPUT_NUM_CHANNELS * tiles[4].w * tiles[4].h);
  247. /* Fill output buffer with noisy image, assumed by kernel_filter_finalize
  248. * when skipping denoising of some pixels. */
  249. float *result = output_mem->data();
  250. float *in = &image.pixels[image.num_channels * (tiles[4].y * image.width + tiles[4].x)];
  251. const DenoiseImageLayer &layer = image.layers[current_layer];
  252. const int *input_to_image_channel = layer.input_to_image_channel.data();
  253. for (int y = 0; y < tiles[4].h; y++) {
  254. for (int x = 0; x < tiles[4].w; x++, result += OUTPUT_NUM_CHANNELS) {
  255. for (int i = 0; i < OUTPUT_NUM_CHANNELS; i++) {
  256. result[i] = in[image.num_channels * x + input_to_image_channel[INPUT_NOISY_IMAGE + i]];
  257. }
  258. }
  259. in += image.num_channels * image.width;
  260. }
  261. output_mem->copy_to_device();
  262. /* Fill output tile info. */
  263. tiles[9] = tiles[4];
  264. tiles[9].buffer = output_mem->device_pointer;
  265. tiles[9].stride = tiles[9].w;
  266. tiles[9].offset -= tiles[9].x + tiles[9].y * tiles[9].stride;
  267. thread_scoped_lock output_lock(output_mutex);
  268. assert(output_pixels.count(tiles[4].tile_index) == 0);
  269. output_pixels[tiles[9].tile_index] = output_mem;
  270. }
  271. void DenoiseTask::unmap_neighboring_tiles(RenderTile *tiles)
  272. {
  273. thread_scoped_lock output_lock(output_mutex);
  274. assert(output_pixels.count(tiles[4].tile_index) == 1);
  275. device_vector<float> *output_mem = output_pixels[tiles[9].tile_index];
  276. output_pixels.erase(tiles[4].tile_index);
  277. output_lock.unlock();
  278. /* Copy denoised pixels from device. */
  279. output_mem->copy_from_device(0, OUTPUT_NUM_CHANNELS * tiles[9].w, tiles[9].h);
  280. float *result = output_mem->data();
  281. float *out = &image.pixels[image.num_channels * (tiles[9].y * image.width + tiles[9].x)];
  282. const DenoiseImageLayer &layer = image.layers[current_layer];
  283. const int *output_to_image_channel = layer.output_to_image_channel.data();
  284. for (int y = 0; y < tiles[9].h; y++) {
  285. for (int x = 0; x < tiles[9].w; x++, result += OUTPUT_NUM_CHANNELS) {
  286. for (int i = 0; i < OUTPUT_NUM_CHANNELS; i++) {
  287. out[image.num_channels * x + output_to_image_channel[i]] = result[i];
  288. }
  289. }
  290. out += image.num_channels * image.width;
  291. }
  292. /* Free device buffer. */
  293. output_mem->free();
  294. delete output_mem;
  295. }
  296. void DenoiseTask::release_tile()
  297. {
  298. }
  299. bool DenoiseTask::get_cancel()
  300. {
  301. return false;
  302. }
  303. void DenoiseTask::create_task(DeviceTask &task)
  304. {
  305. /* Callback functions. */
  306. task.acquire_tile = function_bind(&DenoiseTask::acquire_tile, this, device, _1, _2);
  307. task.map_neighbor_tiles = function_bind(&DenoiseTask::map_neighboring_tiles, this, _1, _2);
  308. task.unmap_neighbor_tiles = function_bind(&DenoiseTask::unmap_neighboring_tiles, this, _1);
  309. task.release_tile = function_bind(&DenoiseTask::release_tile, this);
  310. task.get_cancel = function_bind(&DenoiseTask::get_cancel, this);
  311. /* Denoising parameters. */
  312. task.denoising = denoiser->params;
  313. task.denoising_do_filter = true;
  314. task.denoising_write_passes = false;
  315. task.denoising_from_render = false;
  316. task.denoising_frames.resize(neighbor_frames.size());
  317. for (int i = 0; i < neighbor_frames.size(); i++) {
  318. task.denoising_frames[i] = neighbor_frames[i] - frame;
  319. }
  320. /* Buffer parameters. */
  321. task.pass_stride = INPUT_NUM_CHANNELS;
  322. task.target_pass_stride = OUTPUT_NUM_CHANNELS;
  323. task.pass_denoising_data = 0;
  324. task.pass_denoising_clean = -1;
  325. task.frame_stride = image.width * image.height * INPUT_NUM_CHANNELS;
  326. /* Create tiles. */
  327. thread_scoped_lock tile_lock(tiles_mutex);
  328. thread_scoped_lock output_lock(output_mutex);
  329. tiles.clear();
  330. assert(output_pixels.empty());
  331. output_pixels.clear();
  332. int tiles_x = divide_up(image.width, denoiser->tile_size.x);
  333. int tiles_y = divide_up(image.height, denoiser->tile_size.y);
  334. for (int ty = 0; ty < tiles_y; ty++) {
  335. for (int tx = 0; tx < tiles_x; tx++) {
  336. RenderTile tile;
  337. tile.x = tx * denoiser->tile_size.x;
  338. tile.y = ty * denoiser->tile_size.y;
  339. tile.w = min(image.width - tile.x, denoiser->tile_size.x);
  340. tile.h = min(image.height - tile.y, denoiser->tile_size.y);
  341. tile.start_sample = 0;
  342. tile.num_samples = image.layers[current_layer].samples;
  343. tile.sample = 0;
  344. tile.offset = 0;
  345. tile.stride = image.width;
  346. tile.tile_index = ty * tiles_x + tx;
  347. tile.task = RenderTile::DENOISE;
  348. tile.buffers = NULL;
  349. tile.buffer = input_pixels.device_pointer;
  350. tiles.push_back(tile);
  351. }
  352. }
  353. num_tiles = tiles.size();
  354. }
  355. /* Denoiser Operations */
  356. bool DenoiseTask::load_input_pixels(int layer)
  357. {
  358. int w = image.width;
  359. int h = image.height;
  360. int num_pixels = image.width * image.height;
  361. int frame_stride = num_pixels * INPUT_NUM_CHANNELS;
  362. /* Load center image */
  363. DenoiseImageLayer &image_layer = image.layers[layer];
  364. float *buffer_data = input_pixels.data();
  365. image.read_pixels(image_layer, buffer_data);
  366. buffer_data += frame_stride;
  367. /* Load neighbor images */
  368. for (int i = 0; i < image.in_neighbors.size(); i++) {
  369. if (!image.read_neighbor_pixels(i, image_layer, buffer_data)) {
  370. error = "Failed to read neighbor frame pixels";
  371. return false;
  372. }
  373. buffer_data += frame_stride;
  374. }
  375. /* Preprocess */
  376. buffer_data = input_pixels.data();
  377. for (int neighbor = 0; neighbor < image.in_neighbors.size() + 1; neighbor++) {
  378. /* Clamp */
  379. if (denoiser->params.clamp_input) {
  380. for (int i = 0; i < num_pixels * INPUT_NUM_CHANNELS; i++) {
  381. buffer_data[i] = clamp(buffer_data[i], -1e8f, 1e8f);
  382. }
  383. }
  384. /* Box blur */
  385. int r = 5 * denoiser->params.radius;
  386. float *data = buffer_data + 14;
  387. array<float> temp(num_pixels);
  388. for (int y = 0; y < h; y++) {
  389. for (int x = 0; x < w; x++) {
  390. int n = 0;
  391. float sum = 0.0f;
  392. for (int dx = max(x - r, 0); dx < min(x + r + 1, w); dx++, n++) {
  393. sum += data[INPUT_NUM_CHANNELS * (y * w + dx)];
  394. }
  395. temp[y * w + x] = sum / n;
  396. }
  397. }
  398. for (int y = 0; y < h; y++) {
  399. for (int x = 0; x < w; x++) {
  400. int n = 0;
  401. float sum = 0.0f;
  402. for (int dy = max(y - r, 0); dy < min(y + r + 1, h); dy++, n++) {
  403. sum += temp[dy * w + x];
  404. }
  405. data[INPUT_NUM_CHANNELS * (y * w + x)] = sum / n;
  406. }
  407. }
  408. /* Highlight compression */
  409. data = buffer_data + 8;
  410. for (int y = 0; y < h; y++) {
  411. for (int x = 0; x < w; x++) {
  412. int idx = INPUT_NUM_CHANNELS * (y * w + x);
  413. float3 color = make_float3(data[idx], data[idx + 1], data[idx + 2]);
  414. color = color_highlight_compress(color, NULL);
  415. data[idx] = color.x;
  416. data[idx + 1] = color.y;
  417. data[idx + 2] = color.z;
  418. }
  419. }
  420. buffer_data += frame_stride;
  421. }
  422. /* Copy to device */
  423. input_pixels.copy_to_device();
  424. return true;
  425. }
  426. /* Task stages */
  427. bool DenoiseTask::load()
  428. {
  429. string center_filepath = denoiser->input[frame];
  430. if (!image.load(center_filepath, error)) {
  431. return false;
  432. }
  433. if (!image.load_neighbors(denoiser->input, neighbor_frames, error)) {
  434. return false;
  435. }
  436. if (image.layers.empty()) {
  437. error = "No image layers found to denoise in " + center_filepath;
  438. return false;
  439. }
  440. /* Allocate device buffer. */
  441. int num_frames = image.in_neighbors.size() + 1;
  442. input_pixels.alloc(image.width * INPUT_NUM_CHANNELS, image.height * num_frames);
  443. input_pixels.zero_to_device();
  444. /* Read pixels for first layer. */
  445. current_layer = 0;
  446. if (!load_input_pixels(current_layer)) {
  447. return false;
  448. }
  449. return true;
  450. }
  451. bool DenoiseTask::exec()
  452. {
  453. for (current_layer = 0; current_layer < image.layers.size(); current_layer++) {
  454. /* Read pixels for secondary layers, first was already loaded. */
  455. if (current_layer > 0) {
  456. if (!load_input_pixels(current_layer)) {
  457. return false;
  458. }
  459. }
  460. /* Run task on device. */
  461. DeviceTask task(DeviceTask::RENDER);
  462. create_task(task);
  463. device->task_add(task);
  464. device->task_wait();
  465. printf("\n");
  466. }
  467. return true;
  468. }
  469. bool DenoiseTask::save()
  470. {
  471. bool ok = image.save_output(denoiser->output[frame], error);
  472. free();
  473. return ok;
  474. }
  475. void DenoiseTask::free()
  476. {
  477. image.free();
  478. input_pixels.free();
  479. assert(output_pixels.empty());
  480. }
  481. /* Denoise Image Storage */
  482. DenoiseImage::DenoiseImage()
  483. {
  484. width = 0;
  485. height = 0;
  486. num_channels = 0;
  487. samples = 0;
  488. }
  489. DenoiseImage::~DenoiseImage()
  490. {
  491. free();
  492. }
  493. void DenoiseImage::close_input()
  494. {
  495. in_neighbors.clear();
  496. }
  497. void DenoiseImage::free()
  498. {
  499. close_input();
  500. pixels.clear();
  501. }
  502. bool DenoiseImage::parse_channels(const ImageSpec &in_spec, string &error)
  503. {
  504. const std::vector<string> &channels = in_spec.channelnames;
  505. const ParamValue *multiview = in_spec.find_attribute("multiView");
  506. const bool multiview_channels = (multiview && multiview->type().basetype == TypeDesc::STRING &&
  507. multiview->type().arraylen >= 2);
  508. layers.clear();
  509. /* Loop over all the channels in the file, parse their name and sort them
  510. * by RenderLayer.
  511. * Channels that can't be parsed are directly passed through to the output. */
  512. map<string, DenoiseImageLayer> file_layers;
  513. for (int i = 0; i < channels.size(); i++) {
  514. string layer, pass, channel;
  515. if (parse_channel_name(channels[i], layer, pass, channel, multiview_channels)) {
  516. file_layers[layer].channels.push_back(pass + "." + channel);
  517. file_layers[layer].layer_to_image_channel.push_back(i);
  518. }
  519. }
  520. /* Loop over all detected RenderLayers, check whether they contain a full set of input channels.
  521. * Any channels that won't be processed internally are also passed through. */
  522. for (map<string, DenoiseImageLayer>::iterator i = file_layers.begin(); i != file_layers.end();
  523. ++i) {
  524. const string &name = i->first;
  525. DenoiseImageLayer &layer = i->second;
  526. /* Check for full pass set. */
  527. if (!layer.detect_denoising_channels()) {
  528. continue;
  529. }
  530. layer.name = name;
  531. layer.samples = samples;
  532. /* If the sample value isn't set yet, check if there is a layer-specific one in the input file.
  533. */
  534. if (layer.samples < 1) {
  535. string sample_string = in_spec.get_string_attribute("cycles." + name + ".samples", "");
  536. if (sample_string != "") {
  537. if (!sscanf(sample_string.c_str(), "%d", &layer.samples)) {
  538. error = "Failed to parse samples metadata: " + sample_string;
  539. return false;
  540. }
  541. }
  542. }
  543. if (layer.samples < 1) {
  544. error = string_printf(
  545. "No sample number specified in the file for layer %s or on the command line",
  546. name.c_str());
  547. return false;
  548. }
  549. layers.push_back(layer);
  550. }
  551. return true;
  552. }
  553. void DenoiseImage::read_pixels(const DenoiseImageLayer &layer, float *input_pixels)
  554. {
  555. /* Pixels from center file have already been loaded into pixels.
  556. * We copy a subset into the device input buffer with channels reshuffled. */
  557. const int *input_to_image_channel = layer.input_to_image_channel.data();
  558. for (int i = 0; i < width * height; i++) {
  559. for (int j = 0; j < INPUT_NUM_CHANNELS; j++) {
  560. int image_channel = input_to_image_channel[j];
  561. input_pixels[i * INPUT_NUM_CHANNELS + j] =
  562. pixels[((size_t)i) * num_channels + image_channel];
  563. }
  564. }
  565. }
  566. bool DenoiseImage::read_neighbor_pixels(int neighbor,
  567. const DenoiseImageLayer &layer,
  568. float *input_pixels)
  569. {
  570. /* Load pixels from neighboring frames, and copy them into device buffer
  571. * with channels reshuffled. */
  572. size_t num_pixels = (size_t)width * (size_t)height;
  573. array<float> neighbor_pixels(num_pixels * num_channels);
  574. if (!in_neighbors[neighbor]->read_image(TypeDesc::FLOAT, neighbor_pixels.data())) {
  575. return false;
  576. }
  577. const int *input_to_image_channel = layer.neighbor_input_to_image_channel[neighbor].data();
  578. for (int i = 0; i < width * height; i++) {
  579. for (int j = 0; j < INPUT_NUM_CHANNELS; j++) {
  580. int image_channel = input_to_image_channel[j];
  581. input_pixels[i * INPUT_NUM_CHANNELS + j] =
  582. neighbor_pixels[((size_t)i) * num_channels + image_channel];
  583. }
  584. }
  585. return true;
  586. }
  587. bool DenoiseImage::load(const string &in_filepath, string &error)
  588. {
  589. if (!Filesystem::is_regular(in_filepath)) {
  590. error = "Couldn't find file: " + in_filepath;
  591. return false;
  592. }
  593. unique_ptr<ImageInput> in(ImageInput::open(in_filepath));
  594. if (!in) {
  595. error = "Couldn't open file: " + in_filepath;
  596. return false;
  597. }
  598. in_spec = in->spec();
  599. width = in_spec.width;
  600. height = in_spec.height;
  601. num_channels = in_spec.nchannels;
  602. if (!parse_channels(in_spec, error)) {
  603. return false;
  604. }
  605. if (layers.size() == 0) {
  606. error = "Could not find a render layer containing denoising info";
  607. return false;
  608. }
  609. size_t num_pixels = (size_t)width * (size_t)height;
  610. pixels.resize(num_pixels * num_channels);
  611. /* Read all channels into buffer. Reading all channels at once is faster
  612. * than individually due to interleaved EXR channel storage. */
  613. if (!in->read_image(TypeDesc::FLOAT, pixels.data())) {
  614. error = "Failed to read image: " + in_filepath;
  615. return false;
  616. }
  617. return true;
  618. }
  619. bool DenoiseImage::load_neighbors(const vector<string> &filepaths,
  620. const vector<int> &frames,
  621. string &error)
  622. {
  623. if (frames.size() > DENOISE_MAX_FRAMES - 1) {
  624. error = string_printf("Maximum number of neighbors (%d) exceeded\n", DENOISE_MAX_FRAMES - 1);
  625. return false;
  626. }
  627. for (int neighbor = 0; neighbor < frames.size(); neighbor++) {
  628. int frame = frames[neighbor];
  629. const string &filepath = filepaths[frame];
  630. if (!Filesystem::is_regular(filepath)) {
  631. error = "Couldn't find neighbor frame: " + filepath;
  632. return false;
  633. }
  634. unique_ptr<ImageInput> in_neighbor(ImageInput::open(filepath));
  635. if (!in_neighbor) {
  636. error = "Couldn't open neighbor frame: " + filepath;
  637. return false;
  638. }
  639. const ImageSpec &neighbor_spec = in_neighbor->spec();
  640. if (neighbor_spec.width != width || neighbor_spec.height != height) {
  641. error = "Neighbor frame has different dimensions: " + filepath;
  642. return false;
  643. }
  644. foreach (DenoiseImageLayer &layer, layers) {
  645. if (!layer.match_channels(neighbor, in_spec.channelnames, neighbor_spec.channelnames)) {
  646. error = "Neighbor frame misses denoising data passes: " + filepath;
  647. return false;
  648. }
  649. }
  650. in_neighbors.push_back(std::move(in_neighbor));
  651. }
  652. return true;
  653. }
  654. bool DenoiseImage::save_output(const string &out_filepath, string &error)
  655. {
  656. /* Save image with identical dimensions, channels and metadata. */
  657. ImageSpec out_spec = in_spec;
  658. /* Ensure that the output frame contains sample information even if the input didn't. */
  659. for (int i = 0; i < layers.size(); i++) {
  660. string name = "cycles." + layers[i].name + ".samples";
  661. if (!out_spec.find_attribute(name, TypeDesc::STRING)) {
  662. out_spec.attribute(name, TypeDesc::STRING, string_printf("%d", layers[i].samples));
  663. }
  664. }
  665. /* We don't need input anymore at this point, and will possibly
  666. * overwrite the same file. */
  667. close_input();
  668. /* Write to temporary file path, so we denoise images in place and don't
  669. * risk destroying files when something goes wrong in file saving. */
  670. string extension = OIIO::Filesystem::extension(out_filepath);
  671. string unique_name = ".denoise-tmp-" + OIIO::Filesystem::unique_path();
  672. string tmp_filepath = out_filepath + unique_name + extension;
  673. unique_ptr<ImageOutput> out(ImageOutput::create(tmp_filepath));
  674. if (!out) {
  675. error = "Failed to open temporary file " + tmp_filepath + " for writing";
  676. return false;
  677. }
  678. /* Open temporary file and write image buffers. */
  679. if (!out->open(tmp_filepath, out_spec)) {
  680. error = "Failed to open file " + tmp_filepath + " for writing: " + out->geterror();
  681. return false;
  682. }
  683. bool ok = true;
  684. if (!out->write_image(TypeDesc::FLOAT, pixels.data())) {
  685. error = "Failed to write to file " + tmp_filepath + ": " + out->geterror();
  686. ok = false;
  687. }
  688. if (!out->close()) {
  689. error = "Failed to save to file " + tmp_filepath + ": " + out->geterror();
  690. ok = false;
  691. }
  692. out.reset();
  693. /* Copy temporary file to outputput filepath. */
  694. string rename_error;
  695. if (ok && !OIIO::Filesystem::rename(tmp_filepath, out_filepath, rename_error)) {
  696. error = "Failed to move denoised image to " + out_filepath + ": " + rename_error;
  697. ok = false;
  698. }
  699. if (!ok) {
  700. OIIO::Filesystem::remove(tmp_filepath);
  701. }
  702. return ok;
  703. }
  704. /* File pattern handling and outer loop over frames */
  705. Denoiser::Denoiser(DeviceInfo &device_info)
  706. {
  707. samples_override = 0;
  708. tile_size = make_int2(64, 64);
  709. num_frames = 0;
  710. /* Initialize task scheduler. */
  711. TaskScheduler::init();
  712. /* Initialize device. */
  713. DeviceRequestedFeatures req;
  714. device = Device::create(device_info, stats, profiler, true);
  715. device->load_kernels(req);
  716. }
  717. Denoiser::~Denoiser()
  718. {
  719. delete device;
  720. TaskScheduler::exit();
  721. }
  722. bool Denoiser::run()
  723. {
  724. assert(input.size() == output.size());
  725. num_frames = output.size();
  726. for (int frame = 0; frame < num_frames; frame++) {
  727. /* Skip empty output paths. */
  728. if (output[frame].empty()) {
  729. continue;
  730. }
  731. /* Determine neighbor frame numbers that should be used for filtering. */
  732. vector<int> neighbor_frames;
  733. for (int f = frame - params.neighbor_frames; f <= frame + params.neighbor_frames; f++) {
  734. if (f >= 0 && f < num_frames && f != frame) {
  735. neighbor_frames.push_back(f);
  736. }
  737. }
  738. /* Execute task. */
  739. DenoiseTask task(device, this, frame, neighbor_frames);
  740. if (!task.load()) {
  741. error = task.error;
  742. return false;
  743. }
  744. if (!task.exec()) {
  745. error = task.error;
  746. return false;
  747. }
  748. if (!task.save()) {
  749. error = task.error;
  750. return false;
  751. }
  752. task.free();
  753. }
  754. return true;
  755. }
  756. CCL_NAMESPACE_END