1 /*
2  * Copyright © 2017 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  */
23 
24 #include "nir/nir.h"
25 #include "nir/nir_builder.h"
26 #include "nir/nir_vulkan.h"
27 #include "radv_private.h"
28 #include "radv_shader.h"
29 #include "vk_format.h"
30 
31 struct ycbcr_state {
32    nir_builder *builder;
33    nir_ssa_def *image_size;
34    nir_tex_instr *origin_tex;
35    nir_deref_instr *tex_deref;
36    const struct radv_sampler_ycbcr_conversion *conversion;
37    bool unnormalized_coordinates;
38 };
39 
40 static nir_ssa_def *
get_texture_size(struct ycbcr_state * state,nir_deref_instr * texture)41 get_texture_size(struct ycbcr_state *state, nir_deref_instr *texture)
42 {
43    nir_builder *b = state->builder;
44    const struct glsl_type *type = texture->type;
45    nir_tex_instr *tex = nir_tex_instr_create(b->shader, 1);
46 
47    tex->op = nir_texop_txs;
48    tex->sampler_dim = glsl_get_sampler_dim(type);
49    tex->is_array = glsl_sampler_type_is_array(type);
50    tex->is_shadow = glsl_sampler_type_is_shadow(type);
51    tex->dest_type = nir_type_int32;
52 
53    tex->src[0].src_type = nir_tex_src_texture_deref;
54    tex->src[0].src = nir_src_for_ssa(&texture->dest.ssa);
55 
56    nir_ssa_dest_init(&tex->instr, &tex->dest, nir_tex_instr_dest_size(tex), 32, NULL);
57    nir_builder_instr_insert(b, &tex->instr);
58 
59    return nir_i2f32(b, &tex->dest.ssa);
60 }
61 
62 static nir_ssa_def *
implicit_downsampled_coord(nir_builder * b,nir_ssa_def * value,nir_ssa_def * max_value,int div_scale)63 implicit_downsampled_coord(nir_builder *b, nir_ssa_def *value, nir_ssa_def *max_value,
64                            int div_scale)
65 {
66    return nir_fadd(
67       b, value,
68       nir_fdiv(b, nir_imm_float(b, 1.0f), nir_fmul(b, nir_imm_float(b, div_scale), max_value)));
69 }
70 
71 static nir_ssa_def *
implicit_downsampled_coord_unnormalized(nir_builder * b,nir_ssa_def * value,int div_scale)72 implicit_downsampled_coord_unnormalized(nir_builder *b, nir_ssa_def *value, int div_scale)
73 {
74    return nir_fadd(
75       b, value,
76       nir_imm_float(b, 1.0f / (float)div_scale));
77 }
78 
79 static nir_ssa_def *
implicit_downsampled_coords(struct ycbcr_state * state,nir_ssa_def * old_coords)80 implicit_downsampled_coords(struct ycbcr_state *state, nir_ssa_def *old_coords)
81 {
82    nir_builder *b = state->builder;
83    const struct radv_sampler_ycbcr_conversion *conversion = state->conversion;
84    nir_ssa_def *image_size = NULL;
85    nir_ssa_def *comp[4] = {
86       NULL,
87    };
88    enum pipe_video_chroma_format chroma_format =
89       pipe_format_to_chroma_format(vk_format_to_pipe_format(state->conversion->format));
90    const unsigned divisors[2] = {chroma_format <= PIPE_VIDEO_CHROMA_FORMAT_422 ? 2 : 1,
91                                  chroma_format <= PIPE_VIDEO_CHROMA_FORMAT_420 ? 2 : 1};
92 
93    for (int c = 0; c < old_coords->num_components; c++) {
94       comp[c] = nir_channel(b, old_coords, c);
95 
96       if (c < ARRAY_SIZE(divisors) && divisors[c] > 1) {
97          if (state->unnormalized_coordinates)
98             comp[c] = nir_fdiv(b, comp[c], nir_imm_float(b, divisors[c]));
99 
100          if (conversion->chroma_offsets[c] == VK_CHROMA_LOCATION_COSITED_EVEN) {
101             if (state->unnormalized_coordinates) {
102                comp[c] = implicit_downsampled_coord_unnormalized(b, comp[c], divisors[c]);
103             } else {
104                if (!image_size)
105                   image_size = get_texture_size(state, state->tex_deref);
106 
107                comp[c] = implicit_downsampled_coord(b, comp[c], nir_channel(b, image_size, c), divisors[c]);
108             }
109          }
110       }
111    }
112 
113    return nir_vec(b, comp, old_coords->num_components);
114 }
115 
116 static nir_ssa_def *
create_plane_tex_instr_implicit(struct ycbcr_state * state,uint32_t plane)117 create_plane_tex_instr_implicit(struct ycbcr_state *state, uint32_t plane)
118 {
119    nir_builder *b = state->builder;
120    nir_tex_instr *old_tex = state->origin_tex;
121    nir_tex_instr *tex = nir_tex_instr_create(b->shader, old_tex->num_srcs + 1);
122    for (uint32_t i = 0; i < old_tex->num_srcs; i++) {
123       tex->src[i].src_type = old_tex->src[i].src_type;
124 
125       switch (old_tex->src[i].src_type) {
126       case nir_tex_src_coord:
127          if (plane && true /*state->conversion->chroma_reconstruction*/) {
128             assert(old_tex->src[i].src.is_ssa);
129             tex->src[i].src =
130                nir_src_for_ssa(implicit_downsampled_coords(state, old_tex->src[i].src.ssa));
131             break;
132          }
133       FALLTHROUGH;
134       default:
135          nir_src_copy(&tex->src[i].src, &old_tex->src[i].src);
136          break;
137       }
138    }
139 
140    tex->src[tex->num_srcs - 1].src = nir_src_for_ssa(nir_imm_int(b, plane));
141    tex->src[tex->num_srcs - 1].src_type = nir_tex_src_plane;
142 
143    tex->sampler_dim = old_tex->sampler_dim;
144    tex->dest_type = old_tex->dest_type;
145    tex->is_array = old_tex->is_array;
146 
147    tex->op = old_tex->op;
148    tex->coord_components = old_tex->coord_components;
149    tex->is_new_style_shadow = old_tex->is_new_style_shadow;
150    tex->component = old_tex->component;
151 
152    tex->texture_index = old_tex->texture_index;
153    tex->sampler_index = old_tex->sampler_index;
154 
155    nir_ssa_dest_init(&tex->instr, &tex->dest, old_tex->dest.ssa.num_components,
156                      nir_dest_bit_size(old_tex->dest), NULL);
157    nir_builder_instr_insert(b, &tex->instr);
158 
159    return &tex->dest.ssa;
160 }
161 
162 struct swizzle_info {
163    unsigned plane[4];
164    unsigned swizzle[4];
165 };
166 
167 static struct swizzle_info
get_plane_swizzles(VkFormat format)168 get_plane_swizzles(VkFormat format)
169 {
170    int planes = vk_format_get_plane_count(format);
171    switch (planes) {
172    case 3:
173       return (struct swizzle_info){{2, 0, 1, 0}, {0, 0, 0, 3}};
174    case 2:
175       return (struct swizzle_info){{1, 0, 1, 0}, {1, 0, 0, 3}};
176    case 1:
177       return (struct swizzle_info){{0, 0, 0, 0}, {0, 1, 2, 3}};
178    default:
179       unreachable("unhandled plane count for ycbcr swizzling");
180    }
181 }
182 
183 static nir_ssa_def *
build_swizzled_components(nir_builder * builder,VkFormat format,VkComponentMapping mapping,nir_ssa_def ** plane_values)184 build_swizzled_components(nir_builder *builder, VkFormat format, VkComponentMapping mapping,
185                           nir_ssa_def **plane_values)
186 {
187    struct swizzle_info plane_swizzle = get_plane_swizzles(format);
188    enum pipe_swizzle swizzles[4];
189    nir_ssa_def *values[4];
190 
191    vk_format_compose_swizzles(&mapping, (const unsigned char[4]){0, 1, 2, 3}, swizzles);
192 
193    nir_ssa_def *zero = nir_imm_float(builder, 0.0f);
194    nir_ssa_def *one = nir_imm_float(builder, 1.0f);
195 
196    for (unsigned i = 0; i < 4; ++i) {
197       switch (swizzles[i]) {
198       case PIPE_SWIZZLE_X:
199       case PIPE_SWIZZLE_Y:
200       case PIPE_SWIZZLE_Z:
201       case PIPE_SWIZZLE_W: {
202          unsigned channel = swizzles[i] - PIPE_SWIZZLE_X;
203          values[i] = nir_channel(builder, plane_values[plane_swizzle.plane[channel]],
204                                  plane_swizzle.swizzle[channel]);
205          break;
206       }
207       case PIPE_SWIZZLE_0:
208          values[i] = zero;
209          break;
210       case PIPE_SWIZZLE_1:
211          values[i] = one;
212          break;
213       default:
214          unreachable("unhandled swizzle");
215       }
216    }
217    return nir_vec(builder, values, 4);
218 }
219 
220 static bool
try_lower_tex_ycbcr(const struct radv_pipeline_layout * layout,nir_builder * builder,nir_tex_instr * tex)221 try_lower_tex_ycbcr(const struct radv_pipeline_layout *layout, nir_builder *builder,
222                     nir_tex_instr *tex)
223 {
224    int deref_src_idx = nir_tex_instr_src_index(tex, nir_tex_src_texture_deref);
225    assert(deref_src_idx >= 0);
226    nir_deref_instr *deref = nir_src_as_deref(tex->src[deref_src_idx].src);
227 
228    nir_variable *var = nir_deref_instr_get_variable(deref);
229    const struct radv_descriptor_set_layout *set_layout =
230       layout->set[var->data.descriptor_set].layout;
231    const struct radv_descriptor_set_binding_layout *binding =
232       &set_layout->binding[var->data.binding];
233    const struct radv_sampler_ycbcr_conversion *ycbcr_samplers =
234       radv_immutable_ycbcr_samplers(set_layout, var->data.binding);
235 
236    if (!ycbcr_samplers)
237       return false;
238 
239    assert(binding->immutable_samplers_offset);
240    const uint32_t *immutable_samplers =
241       radv_immutable_samplers(set_layout, binding);
242 
243    /* For the following instructions, we don't apply any change and let the
244     * instruction apply to the first plane.
245     */
246    if (tex->op == nir_texop_txs || tex->op == nir_texop_query_levels || tex->op == nir_texop_lod)
247       return false;
248 
249    assert(tex->texture_index == 0);
250    unsigned array_index = 0;
251    if (deref->deref_type != nir_deref_type_var) {
252       assert(deref->deref_type == nir_deref_type_array);
253       if (!nir_src_is_const(deref->arr.index))
254          return false;
255       array_index = nir_src_as_uint(deref->arr.index);
256       array_index = MIN2(array_index, binding->array_size - 1);
257    }
258    const struct radv_sampler_ycbcr_conversion *ycbcr_sampler = ycbcr_samplers + array_index;
259 
260    if (ycbcr_sampler->format == VK_FORMAT_UNDEFINED)
261       return false;
262 
263    bool unnormalized_coordinates = immutable_samplers[4 * array_index + 0] & S_008F30_FORCE_UNNORMALIZED(1);
264 
265    struct ycbcr_state state = {
266       .builder = builder,
267       .origin_tex = tex,
268       .tex_deref = deref,
269       .conversion = ycbcr_sampler,
270       .unnormalized_coordinates = unnormalized_coordinates,
271    };
272 
273    builder->cursor = nir_before_instr(&tex->instr);
274 
275    VkFormat format = state.conversion->format;
276    const int plane_count = vk_format_get_plane_count(format);
277    nir_ssa_def *plane_values[3];
278 
279    for (int p = 0; p < plane_count; ++p) {
280       plane_values[p] = create_plane_tex_instr_implicit(&state, p);
281    }
282 
283    nir_ssa_def *result =
284       build_swizzled_components(builder, format, ycbcr_sampler->components, plane_values);
285    if (state.conversion->ycbcr_model != VK_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY) {
286       VkFormat first_format = vk_format_get_plane_format(format, 0);
287       uint32_t bits =
288          vk_format_get_component_bits(first_format, UTIL_FORMAT_COLORSPACE_RGB, PIPE_SWIZZLE_X);
289       /* TODO: swizzle and bpcs */
290       uint32_t bpcs[3] = {bits, bits, bits};
291       result = nir_convert_ycbcr_to_rgb(builder, state.conversion->ycbcr_model,
292                                         state.conversion->ycbcr_range, result, bpcs);
293    }
294 
295    nir_ssa_def_rewrite_uses(&tex->dest.ssa, result);
296    nir_instr_remove(&tex->instr);
297 
298    return true;
299 }
300 
301 bool
radv_nir_lower_ycbcr_textures(nir_shader * shader,const struct radv_pipeline_layout * layout)302 radv_nir_lower_ycbcr_textures(nir_shader *shader, const struct radv_pipeline_layout *layout)
303 {
304    bool progress = false;
305 
306    nir_foreach_function (function, shader) {
307       if (!function->impl)
308          continue;
309 
310       bool function_progress = false;
311       nir_builder builder;
312       nir_builder_init(&builder, function->impl);
313 
314       nir_foreach_block (block, function->impl) {
315          nir_foreach_instr_safe (instr, block) {
316             if (instr->type != nir_instr_type_tex)
317                continue;
318 
319             nir_tex_instr *tex = nir_instr_as_tex(instr);
320             function_progress |= try_lower_tex_ycbcr(layout, &builder, tex);
321          }
322       }
323 
324       if (function_progress) {
325          nir_metadata_preserve(function->impl, nir_metadata_block_index | nir_metadata_dominance);
326       }
327 
328       progress |= function_progress;
329    }
330 
331    return progress;
332 }
333