Blender V5.0
denoising.cpp
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2011-2022 Blender Foundation
2 *
3 * SPDX-License-Identifier: Apache-2.0 */
4
5#include "session/denoising.h"
6#include "device/cpu/device.h"
7
9#include "util/map.h"
10#include "util/task.h"
11
12#include <OpenImageIO/filesystem.h>
13
15
16/* Utility Functions */
17
18/* Splits in at its last dot, setting suffix to the part after the dot and in to the part before
19 * it. Returns whether a dot was found. */
20static bool split_last_dot(string &in, string &suffix)
21{
22 const size_t pos = in.rfind(".");
23 if (pos == string::npos) {
24 return false;
25 }
26 suffix = in.substr(pos + 1);
27 in = in.substr(0, pos);
28 return true;
29}
30
31/* Separate channel names as generated by Blender.
32 * If views is true:
33 * Inputs are expected in the form RenderLayer.Pass.View.Channel, sets renderlayer to
34 * "RenderLayer.View" Otherwise: Inputs are expected in the form RenderLayer.Pass.Channel */
36 string name, string &renderlayer, string &pass, string &channel, bool multiview_channels)
37{
38 if (!split_last_dot(name, channel)) {
39 return false;
40 }
41 string view;
42 if (multiview_channels && !split_last_dot(name, view)) {
43 return false;
44 }
45 if (!split_last_dot(name, pass)) {
46 return false;
47 }
48 renderlayer = name;
49
50 if (multiview_channels) {
51 renderlayer += "." + view;
52 }
53
54 return true;
55}
56
57/* Channel Mapping */
58
61 string name;
62};
63
64static void fill_mapping(vector<ChannelMapping> &map, int pos, string name, string channels)
65{
66 for (const char *chan = channels.c_str(); *chan; chan++) {
67 map.push_back({pos++, name + "." + *chan});
68 }
69}
70
71static const int INPUT_NUM_CHANNELS = 13;
72static const int INPUT_NOISY_IMAGE = 0;
73static const int INPUT_DENOISING_NORMAL = 3;
74static const int INPUT_DENOISING_ALBEDO = 6;
75static const int INPUT_MOTION = 9;
77{
79 fill_mapping(map, INPUT_NOISY_IMAGE, "Combined", "RGB");
80 fill_mapping(map, INPUT_DENOISING_NORMAL, "Denoising Normal", "XYZ");
81 fill_mapping(map, INPUT_DENOISING_ALBEDO, "Denoising Albedo", "RGB");
82 fill_mapping(map, INPUT_MOTION, "Vector", "XYZW");
83 return map;
84}
85
86static const int OUTPUT_NUM_CHANNELS = 3;
88{
90 fill_mapping(map, 0, "Combined", "RGB");
91 return map;
92}
93
94/* Render-layer Handling. */
95
97{
98 /* Map device input to image channels. */
101
102 for (const ChannelMapping &mapping : input_channels()) {
103 const vector<string>::iterator i = find(channels.begin(), channels.end(), mapping.name);
104 if (i == channels.end()) {
105 return false;
106 }
107
108 const size_t input_channel = mapping.channel;
109 const size_t layer_channel = i - channels.begin();
110 input_to_image_channel[input_channel] = layer_to_image_channel[layer_channel];
111 }
112
113 /* Map device output to image channels. */
116
117 for (const ChannelMapping &mapping : output_channels()) {
118 const vector<string>::iterator i = find(channels.begin(), channels.end(), mapping.name);
119 if (i == channels.end()) {
120 return false;
121 }
122
123 const size_t output_channel = mapping.channel;
124 const size_t layer_channel = i - channels.begin();
125 output_to_image_channel[output_channel] = layer_to_image_channel[layer_channel];
126 }
127
128 /* Check that all buffer channels are correctly set. */
129 for (int i = 0; i < INPUT_NUM_CHANNELS; i++) {
131 }
132 for (int i = 0; i < OUTPUT_NUM_CHANNELS; i++) {
134 }
135
136 return true;
137}
138
139bool DenoiseImageLayer::match_channels(const std::vector<string> &channelnames,
140 const std::vector<string> &neighbor_channelnames)
141{
143
144 assert(mapping.empty());
145 mapping.resize(output_to_image_channel.size(), -1);
146
147 for (int i = 0; i < output_to_image_channel.size(); i++) {
148 const string &channel = channelnames[output_to_image_channel[i]];
149 const std::vector<string>::const_iterator frame_channel = find(
150 neighbor_channelnames.begin(), neighbor_channelnames.end(), channel);
151
152 if (frame_channel == neighbor_channelnames.end()) {
153 return false;
154 }
155
156 mapping[i] = frame_channel - neighbor_channelnames.begin();
157 }
158
159 return true;
160}
161
162/* Denoise Task */
163
168
173
174/* Denoiser Operations */
175
177{
178 /* Load center image */
179 const DenoiseImageLayer &image_layer = image.layers[layer];
180
181 float *buffer_data = buffers.buffer.data();
182 image.read_pixels(image_layer, buffers.params, buffer_data);
183
184 /* Load previous image */
185 if (frame > 0 && !image.read_previous_pixels(image_layer, buffers.params, buffer_data)) {
186 error = "Failed to read neighbor frame pixels";
187 return false;
188 }
189
190 /* Copy to device */
191 buffers.buffer.copy_to_device();
192
193 return true;
194}
195
196/* Task stages */
197
199 PassType type,
201{
202 unique_ptr<Pass> pass = make_unique<Pass>();
203 pass->set_type(type);
204 pass->set_mode(mode);
205
206 passes.push_back(std::move(pass));
207}
208
210{
211 const string center_filepath = denoiser->input[frame];
212 if (!image.load(center_filepath, error)) {
213 return false;
214 }
215
216 /* Use previous frame output as input for subsequent frames. */
217 if (frame > 0 && !image.load_previous(denoiser->output[frame - 1], error)) {
218 return false;
219 }
220
221 if (image.layers.empty()) {
222 error = "No image layers found to denoise in " + center_filepath;
223 return false;
224 }
225
226 /* Enable temporal denoising for frames after the first (which will use the output from the
227 * previous frames). */
228 DenoiseParams params = denoiser->denoiser->get_params();
229 params.temporally_stable = frame > 0;
230 denoiser->denoiser->set_params(params);
231
232 /* Allocate device buffer. */
240
241 BufferParams buffer_params;
242 buffer_params.width = image.width;
243 buffer_params.height = image.height;
244 buffer_params.full_x = 0;
245 buffer_params.full_y = 0;
246 buffer_params.full_width = image.width;
247 buffer_params.full_height = image.height;
248 buffer_params.update_passes(passes);
249
250 passes.clear();
251
252 buffers.reset(buffer_params);
253
254 /* Read pixels for first layer. */
255 current_layer = 0;
257 return false;
258 }
259
260 return true;
261}
262
264{
265 for (current_layer = 0; current_layer < image.layers.size(); current_layer++) {
266 /* Read pixels for secondary layers, first was already loaded. */
267 if (current_layer > 0) {
269 return false;
270 }
271 }
272
273 /* Run task on device. */
274 denoiser->denoiser->denoise_buffer(buffers.params, &buffers, 1, true);
275
276 /* Copy denoised pixels from device. */
277 buffers.buffer.copy_from_device();
278
279 float *result = buffers.buffer.data();
280 float *out = image.pixels.data();
281
282 const DenoiseImageLayer &layer = image.layers[current_layer];
283 const int *output_to_image_channel = layer.output_to_image_channel.data();
284
285 for (int y = 0; y < image.height; y++) {
286 for (int x = 0; x < image.width; x++, result += buffers.params.pass_stride) {
287 for (int j = 0; j < OUTPUT_NUM_CHANNELS; j++) {
288 const int offset = buffers.params.get_pass_offset(PASS_COMBINED, PassMode::DENOISED);
289 const int image_channel = output_to_image_channel[j];
290 out[image.num_channels * x + image_channel] = result[offset + j];
291 }
292 }
293 out += image.num_channels * image.width;
294 }
295 }
296
297 return true;
298}
299
301{
302 const bool ok = image.save_output(denoiser->output[frame], error);
303 free();
304 return ok;
305}
306
308{
309 image.free();
310 buffers.buffer.free();
311}
312
313/* Denoise Image Storage */
314
316{
317 width = 0;
318 height = 0;
319 num_channels = 0;
320 samples = 0;
321}
322
327
329{
330 in_previous.reset();
331}
332
334{
335 close_input();
336 pixels.clear();
337}
338
339bool DenoiseImage::parse_channels(const ImageSpec &in_spec, string &error)
340{
341 const std::vector<string> &channels = in_spec.channelnames;
342 const ParamValue *multiview = in_spec.find_attribute("multiView");
343 const bool multiview_channels = (multiview && multiview->type().basetype == TypeDesc::STRING &&
344 multiview->type().arraylen >= 2);
345
346 layers.clear();
347
348 /* Loop over all the channels in the file, parse their name and sort them
349 * by RenderLayer.
350 * Channels that can't be parsed are directly passed through to the output. */
351 map<string, DenoiseImageLayer> file_layers;
352 for (int i = 0; i < channels.size(); i++) {
353 string layer;
354 string pass;
355 string channel;
356 if (parse_channel_name(channels[i], layer, pass, channel, multiview_channels)) {
357 file_layers[layer].channels.push_back(pass + "." + channel);
358 file_layers[layer].layer_to_image_channel.push_back(i);
359 }
360 }
361
362 /* Loop over all detected RenderLayers, check whether they contain a full set of input channels.
363 * Any channels that won't be processed internally are also passed through. */
364 for (map<string, DenoiseImageLayer>::iterator i = file_layers.begin(); i != file_layers.end();
365 ++i)
366 {
367 const string &name = i->first;
368 DenoiseImageLayer &layer = i->second;
369
370 /* Check for full pass set. */
371 if (!layer.detect_denoising_channels()) {
372 continue;
373 }
374
375 layer.name = name;
376 layer.samples = samples;
377
378 /* If the sample value isn't set yet, check if there is a layer-specific one in the input file.
379 */
380 if (layer.samples < 1) {
381 const string sample_string = in_spec.get_string_attribute("cycles." + name + ".samples", "");
382 if (!sample_string.empty()) {
383 if (!sscanf(sample_string.c_str(), "%d", &layer.samples)) {
384 error = "Failed to parse samples metadata: " + sample_string;
385 return false;
386 }
387 }
388 }
389
390 if (layer.samples < 1) {
392 "No sample number specified in the file for layer %s or on the command line",
393 name.c_str());
394 return false;
395 }
396
397 layers.push_back(layer);
398 }
399
400 return true;
401}
402
404 const BufferParams &params,
405 float *input_pixels)
406{
407 /* Pixels from center file have already been loaded into pixels.
408 * We copy a subset into the device input buffer with channels reshuffled. */
409 const int *input_to_image_channel = layer.input_to_image_channel.data();
410
411 for (int i = 0; i < width * height; i++) {
412 for (int j = 0; j < 3; ++j) {
413 const int offset = params.get_pass_offset(PASS_COMBINED);
414 const int image_channel = input_to_image_channel[INPUT_NOISY_IMAGE + j];
415 input_pixels[i * params.pass_stride + offset + j] =
416 pixels[((size_t)i) * num_channels + image_channel];
417 }
418 for (int j = 0; j < 3; ++j) {
419 const int offset = params.get_pass_offset(PASS_DENOISING_NORMAL);
420 const int image_channel = input_to_image_channel[INPUT_DENOISING_NORMAL + j];
421 input_pixels[i * params.pass_stride + offset + j] =
422 pixels[((size_t)i) * num_channels + image_channel];
423 }
424 for (int j = 0; j < 3; ++j) {
425 const int offset = params.get_pass_offset(PASS_DENOISING_ALBEDO);
426 const int image_channel = input_to_image_channel[INPUT_DENOISING_ALBEDO + j];
427 input_pixels[i * params.pass_stride + offset + j] =
428 pixels[((size_t)i) * num_channels + image_channel];
429 }
430 for (int j = 0; j < 4; ++j) {
431 const int offset = params.get_pass_offset(PASS_MOTION);
432 const int image_channel = input_to_image_channel[INPUT_MOTION + j];
433 input_pixels[i * params.pass_stride + offset + j] =
434 pixels[((size_t)i) * num_channels + image_channel];
435 }
436 }
437}
438
440 const BufferParams &params,
441 float *input_pixels)
442{
443 /* Load pixels from neighboring frames, and copy them into device buffer
444 * with channels reshuffled. */
445 const size_t num_pixels = (size_t)width * (size_t)height;
446 const int num_channels = in_previous->spec().nchannels;
447
448 array<float> neighbor_pixels(num_pixels * num_channels);
449
450 if (!in_previous->read_image(0, 0, 0, num_channels, TypeDesc::FLOAT, neighbor_pixels.data())) {
451 return false;
452 }
453
454 const int *output_to_image_channel = layer.previous_output_to_image_channel.data();
455
456 for (int i = 0; i < width * height; i++) {
457 for (int j = 0; j < 3; ++j) {
458 const int offset = params.get_pass_offset(PASS_DENOISING_PREVIOUS);
459 const int image_channel = output_to_image_channel[j];
460 input_pixels[i * params.pass_stride + offset + j] =
461 neighbor_pixels[((size_t)i) * num_channels + image_channel];
462 }
463 }
464
465 return true;
466}
467
468bool DenoiseImage::load(const string &in_filepath, string &error)
469{
470 if (!Filesystem::is_regular(in_filepath)) {
471 error = "Couldn't find file: " + in_filepath;
472 return false;
473 }
474
475 unique_ptr<ImageInput> in(ImageInput::open(in_filepath));
476 if (!in) {
477 error = "Couldn't open file: " + in_filepath;
478 return false;
479 }
480
481 in_spec = in->spec();
482 width = in_spec.width;
483 height = in_spec.height;
484 num_channels = in_spec.nchannels;
485
487 return false;
488 }
489
490 if (layers.empty()) {
491 error = "Could not find a render layer containing denoising data and motion vector passes";
492 return false;
493 }
494
495 const size_t num_pixels = (size_t)width * (size_t)height;
496 pixels.resize(num_pixels * num_channels);
497
498 /* Read all channels into buffer. Reading all channels at once is faster
499 * than individually due to interleaved EXR channel storage. */
500 if (!in->read_image(0, 0, 0, num_channels, TypeDesc::FLOAT, pixels.data())) {
501 error = "Failed to read image: " + in_filepath;
502 return false;
503 }
504
505 return true;
506}
507
508bool DenoiseImage::load_previous(const string &filepath, string &error)
509{
510 if (!Filesystem::is_regular(filepath)) {
511 error = "Couldn't find neighbor frame: " + filepath;
512 return false;
513 }
514
515 unique_ptr<ImageInput> in_neighbor(ImageInput::open(filepath));
516 if (!in_neighbor) {
517 error = "Couldn't open neighbor frame: " + filepath;
518 return false;
519 }
520
521 const ImageSpec &neighbor_spec = in_neighbor->spec();
522 if (neighbor_spec.width != width || neighbor_spec.height != height) {
523 error = "Neighbor frame has different dimensions: " + filepath;
524 return false;
525 }
526
527 for (DenoiseImageLayer &layer : layers) {
528 if (!layer.match_channels(in_spec.channelnames, neighbor_spec.channelnames)) {
529 error = "Neighbor frame misses denoising data passes: " + filepath;
530 return false;
531 }
532 }
533
534 in_previous = std::move(in_neighbor);
535
536 return true;
537}
538
539bool DenoiseImage::save_output(const string &out_filepath, string &error)
540{
541 /* Save image with identical dimensions, channels and metadata. */
542 ImageSpec out_spec = in_spec;
543
544 /* Ensure that the output frame contains sample information even if the input didn't. */
545 for (int i = 0; i < layers.size(); i++) {
546 const string name = "cycles." + layers[i].name + ".samples";
547 if (!out_spec.find_attribute(name, TypeDesc::STRING)) {
548 out_spec.attribute(name, TypeDesc::STRING, string_printf("%d", layers[i].samples));
549 }
550 }
551
552 /* We don't need input anymore at this point, and will possibly
553 * overwrite the same file. */
554 close_input();
555
556 /* Write to temporary file path, so we denoise images in place and don't
557 * risk destroying files when something goes wrong in file saving. */
558 const string extension = OIIO::Filesystem::extension(out_filepath);
559 const string unique_name = ".denoise-tmp-" + OIIO::Filesystem::unique_path();
560 const string tmp_filepath = out_filepath + unique_name + extension;
561 unique_ptr<ImageOutput> out(ImageOutput::create(tmp_filepath));
562
563 if (!out) {
564 error = "Failed to open temporary file " + tmp_filepath + " for writing";
565 return false;
566 }
567
568 /* Open temporary file and write image buffers. */
569 if (!out->open(tmp_filepath, out_spec)) {
570 error = "Failed to open file " + tmp_filepath + " for writing: " + out->geterror();
571 return false;
572 }
573
574 bool ok = true;
575 if (!out->write_image(TypeDesc::FLOAT, pixels.data())) {
576 error = "Failed to write to file " + tmp_filepath + ": " + out->geterror();
577 ok = false;
578 }
579
580 if (!out->close()) {
581 error = "Failed to save to file " + tmp_filepath + ": " + out->geterror();
582 ok = false;
583 }
584
585 out.reset();
586
587 /* Copy temporary file to output filepath. */
588 string rename_error;
589 if (ok && !OIIO::Filesystem::rename(tmp_filepath, out_filepath, rename_error)) {
590 error = "Failed to move denoised image to " + out_filepath + ": " + rename_error;
591 ok = false;
592 }
593
594 if (!ok) {
595 OIIO::Filesystem::remove(tmp_filepath);
596 }
597
598 return ok;
599}
600
601/* File pattern handling and outer loop over frames */
602
604{
605 /* Initialize task scheduler. */
607
608 /* Initialize device. */
609 device = Device::create(denoiser_device_info, stats, profiler, true);
610 device->load_kernels(KERNEL_FEATURE_DENOISING);
611
612 vector<DeviceInfo> cpu_devices;
613 device_cpu_info(cpu_devices);
614 cpu_device = device_cpu_create(cpu_devices[0], device->stats, device->profiler, true);
615
617 if (denoiser) {
618 denoiser->load_kernels(nullptr);
619 }
620}
621
623{
624 denoiser.reset();
625 device.reset();
627}
628
630{
631 assert(input.size() == output.size());
632
633 const int num_frames = output.size();
634
635 if (!denoiser) {
636 error = "Failed to create denoiser";
637 return false;
638 }
639
640 for (int frame = 0; frame < num_frames; frame++) {
641 /* Skip empty output paths. */
642 if (output[frame].empty()) {
643 continue;
644 }
645
646 /* Execute task. */
647 DenoiseTask task(device.get(), this, frame);
648 if (!task.load()) {
649 error = task.error;
650 return false;
651 }
652
653 if (!task.exec()) {
654 error = task.error;
655 return false;
656 }
657
658 if (!task.save()) {
659 error = task.error;
660 return false;
661 }
662
663 task.free();
664 }
665
666 return true;
667}
668
static AppView * view
int full_width
Definition buffers.h:85
int full_height
Definition buffers.h:86
NODE_DECLARE int width
Definition buffers.h:70
void update_passes()
Definition buffers.cpp:117
void read_pixels(const DenoiseImageLayer &layer, const BufferParams &params, float *input_pixels)
bool parse_channels(const ImageSpec &in_spec, string &error)
void close_input()
array< float > pixels
Definition denoising.h:102
vector< DenoiseImageLayer > layers
Definition denoising.h:109
bool read_previous_pixels(const DenoiseImageLayer &layer, const BufferParams &params, float *input_pixels)
int num_channels
Definition denoising.h:96
bool load(const string &in_filepath, string &error)
unique_ptr< ImageInput > in_previous
Definition denoising.h:106
bool load_previous(const string &in_filepath, string &error)
bool save_output(const string &out_filepath, string &error)
ImageSpec in_spec
Definition denoising.h:105
DenoiserPipeline * denoiser
Definition denoising.h:157
RenderBuffers buffers
Definition denoising.h:167
bool load_input_pixels(const int layer)
DenoiseTask(Device *device, DenoiserPipeline *denoiser, const int frame)
string error
Definition denoising.h:153
Device * device
Definition denoising.h:158
int current_layer
Definition denoising.h:165
DenoiseImage image
Definition denoising.h:164
std::unique_ptr< Denoiser > denoiser
Definition denoising.h:52
friend class DenoiseTask
Definition denoising.h:46
DenoiserPipeline(DeviceInfo &denoiser_device_info, const DenoiseParams &params)
unique_ptr< Device > cpu_device
Definition denoising.h:51
unique_ptr< Device > device
Definition denoising.h:50
vector< string > input
Definition denoising.h:39
Profiler profiler
Definition denoising.h:49
vector< string > output
Definition denoising.h:43
static unique_ptr< Denoiser > create(Device *denoiser_device, Device *cpu_fallback_device, const DenoiseParams &params, const GraphicsInteropDevice &interop_device)
Definition denoiser.cpp:148
static unique_ptr< Device > create(const DeviceInfo &info, Stats &stats, Profiler &profiler, bool headless)
static void exit()
Definition task.cpp:81
static void init(const int num_threads=0)
Definition task.cpp:60
void push_back(unique_ptr< T > &&value)
static const int INPUT_NOISY_IMAGE
Definition denoising.cpp:72
static const int OUTPUT_NUM_CHANNELS
Definition denoising.cpp:86
static void fill_mapping(vector< ChannelMapping > &map, int pos, string name, string channels)
Definition denoising.cpp:64
static bool parse_channel_name(string name, string &renderlayer, string &pass, string &channel, bool multiview_channels)
Definition denoising.cpp:35
static CCL_NAMESPACE_BEGIN bool split_last_dot(string &in, string &suffix)
Definition denoising.cpp:20
static const int INPUT_DENOISING_ALBEDO
Definition denoising.cpp:74
static vector< ChannelMapping > output_channels()
Definition denoising.cpp:87
static const int INPUT_DENOISING_NORMAL
Definition denoising.cpp:73
static const int INPUT_NUM_CHANNELS
Definition denoising.cpp:71
static const int INPUT_MOTION
Definition denoising.cpp:75
static void add_pass(unique_ptr_vector< Pass > &passes, PassType type, PassMode mode=PassMode::NOISY)
static vector< ChannelMapping > input_channels()
Definition denoising.cpp:76
void device_cpu_info(vector< DeviceInfo > &devices)
CCL_NAMESPACE_BEGIN unique_ptr< Device > device_cpu_create(const DeviceInfo &info, Stats &stats, Profiler &profiler, bool headless)
#define KERNEL_FEATURE_DENOISING
#define CCL_NAMESPACE_END
uint pos
#define assert(assertion)
#define in
#define out
uiWidgetBaseParameters params[MAX_WIDGET_BASE_BATCH]
PassType
@ PASS_DENOISING_NORMAL
@ PASS_MOTION
@ PASS_COMBINED
@ PASS_DENOISING_ALBEDO
@ PASS_DENOISING_PREVIOUS
static void error(const char *str)
static void unique_name(bNode *node)
PassMode
Definition pass.h:20
@ DENOISED
Definition pass.h:22
@ NOISY
Definition pass.h:21
const char * name
CCL_NAMESPACE_BEGIN string string_printf(const char *format,...)
Definition string.cpp:23
vector< int > previous_output_to_image_channel
Definition denoising.h:75
vector< int > input_to_image_channel
Definition denoising.h:68
bool match_channels(const std::vector< string > &channelnames, const std::vector< string > &neighbor_channelnames)
bool detect_denoising_channels()
Definition denoising.cpp:96
vector< int > output_to_image_channel
Definition denoising.h:72
vector< string > channels
Definition denoising.h:60
vector< int > layer_to_image_channel
Definition denoising.h:62
i
Definition text_draw.cc:230