ogl_beamforming

Ultrasound Beamforming Implemented with OpenGL
git clone anongit@rnpnr.xyz:ogl_beamforming.git
Log | Files | Refs | Feed | Submodules | README | LICENSE

beamformer.c (60538B)


      1 /* See LICENSE for license details. */
      2 /* TODO(rnp):
      3  * [ ]: refactor: DecodeMode_None should use a different mapping and optional conversion shader
      4  *      for rf only mode with no filter and demod/filter should gain the OutputFloats flag for iq
      5  *      case and rf mode with filter; this can also be used instead of first pass uniform
      6  * [ ]: refactor: replace UploadRF with just the scratch_rf_size variable,
      7  *      use below to spin wait in library
      8  * [ ]: utilize umonitor/umwait (intel), monitorx/mwaitx (amd), and wfe/sev (aarch64)
      9  *      for power efficient low latency waiting
     10  * [ ]: refactor: split decode into reshape and decode
     11  *      - the check for first pass reshaping is the last non constant check
     12  *        in the shader
     13  *      - this will also remove the need for the channel mapping in the decode shader
     14  * [X]: refactor: ui: reload only shader which is affected by the interaction
     15  * [ ]: BeamformWorkQueue -> BeamformerWorkQueue
     16  * [ ]: need to keep track of gpu memory in some way
     17  *      - want to be able to store more than 16 2D frames but limit 3D frames
     18  *      - maybe keep track of how much gpu memory is committed for beamformed images
     19  *        and use that to determine when to loop back over existing textures
     20  *      - to do this maybe use a circular linked list instead of a flat array
     21  *      - then have a way of querying how many frames are available for a specific point count
     22  * [ ]: bug: reinit cuda on hot-reload
     23  */
     24 
     25 #include "beamformer.h"
     26 
     27 global f32 dt_for_frame;
     28 
     29 #define DECODE_FIRST_PASS_UNIFORM_LOC 1
     30 
     31 #define DAS_LOCAL_SIZE_X  16
     32 #define DAS_LOCAL_SIZE_Y   1
     33 #define DAS_LOCAL_SIZE_Z  16
     34 
     35 #define DAS_VOXEL_OFFSET_UNIFORM_LOC  2
     36 #define DAS_CYCLE_T_UNIFORM_LOC       3
     37 #define DAS_FAST_CHANNEL_UNIFORM_LOC  4
     38 
     39 #define MIN_MAX_MIPS_LEVEL_UNIFORM_LOC 1
     40 #define SUM_PRESCALE_UNIFORM_LOC       1
     41 
     42 #ifndef _DEBUG
     43 #define start_renderdoc_capture(...)
     44 #define end_renderdoc_capture(...)
     45 #else
     46 global renderdoc_start_frame_capture_fn *start_frame_capture;
     47 global renderdoc_end_frame_capture_fn   *end_frame_capture;
     48 #define start_renderdoc_capture(gl) if (start_frame_capture) start_frame_capture(gl, 0)
     49 #define end_renderdoc_capture(gl)   if (end_frame_capture)   end_frame_capture(gl, 0)
     50 #endif
     51 
     52 typedef struct {
     53 	BeamformerFrame *frames;
     54 	u32 capacity;
     55 	u32 offset;
     56 	u32 cursor;
     57 	u32 needed_frames;
     58 } ComputeFrameIterator;
     59 
     60 function void
     61 beamformer_compute_plan_release(BeamformerComputeContext *cc, u32 block)
     62 {
     63 	assert(block < countof(cc->compute_plans));
     64 	BeamformerComputePlan *cp = cc->compute_plans[block];
     65 	if (cp) {
     66 		glDeleteBuffers(countof(cp->ubos), cp->ubos);
     67 		glDeleteTextures(countof(cp->textures), cp->textures);
     68 		for (u32 i = 0; i < countof(cp->filters); i++)
     69 			glDeleteBuffers(1, &cp->filters[i].ssbo);
     70 		cc->compute_plans[block] = 0;
     71 		SLLPushFreelist(cp, cc->compute_plan_freelist);
     72 	}
     73 }
     74 
     75 function BeamformerComputePlan *
     76 beamformer_compute_plan_for_block(BeamformerComputeContext *cc, u32 block, Arena *arena)
     77 {
     78 	assert(block < countof(cc->compute_plans));
     79 	BeamformerComputePlan *result = cc->compute_plans[block];
     80 	if (!result) {
     81 		result = SLLPopFreelist(cc->compute_plan_freelist);
     82 		if (result) zero_struct(result);
     83 		else        result = push_struct(arena, BeamformerComputePlan);
     84 		cc->compute_plans[block] = result;
     85 
     86 		glCreateBuffers(countof(result->ubos), result->ubos);
     87 
     88 		Stream label = arena_stream(*arena);
     89 		#define X(k, t, ...) \
     90 			glNamedBufferStorage(result->ubos[BeamformerComputeUBOKind_##k], sizeof(t), \
     91 			                     0, GL_DYNAMIC_STORAGE_BIT); \
     92 			stream_append_s8(&label, s8(#t "[")); \
     93 			stream_append_u64(&label, block);     \
     94 			stream_append_byte(&label, ']');      \
     95 			glObjectLabel(GL_BUFFER, result->ubos[BeamformerComputeUBOKind_##k], \
     96 			              label.widx, (c8 *)label.data); \
     97 			label.widx = 0;
     98 		BEAMFORMER_COMPUTE_UBO_LIST
     99 		#undef X
    100 
    101 		#define X(_k, t, ...) t,
    102 		GLenum gl_kind[] = {BEAMFORMER_COMPUTE_TEXTURE_LIST_FULL};
    103 		#undef X
    104 		read_only local_persist s8 tex_prefix[] = {
    105 			#define X(k, ...) s8_comp(#k "["),
    106 			BEAMFORMER_COMPUTE_TEXTURE_LIST_FULL
    107 			#undef X
    108 		};
    109 		glCreateTextures(GL_TEXTURE_1D, BeamformerComputeTextureKind_Count - 1, result->textures);
    110 		for (u32 i = 0; i < BeamformerComputeTextureKind_Count - 1; i++) {
    111 			/* TODO(rnp): this could be predicated on channel count for this compute plan */
    112 			glTextureStorage1D(result->textures[i], 1, gl_kind[i], BeamformerMaxChannelCount);
    113 			stream_append_s8(&label, tex_prefix[i]);
    114 			stream_append_u64(&label, block);
    115 			stream_append_byte(&label, ']');
    116 			glObjectLabel(GL_TEXTURE, result->textures[i], label.widx, (c8 *)label.data);
    117 			label.widx = 0;
    118 		}
    119 	}
    120 	return result;
    121 }
    122 
    123 function void
    124 beamformer_filter_update(BeamformerFilter *f, BeamformerFilterKind kind,
    125                          BeamformerFilterParameters fp, u32 block, u32 slot, Arena arena)
    126 {
    127 	#define X(k, ...) s8_comp(#k "Filter"),
    128 	read_only local_persist s8 filter_kinds[] = {BEAMFORMER_FILTER_KIND_LIST(,)};
    129 	#undef X
    130 
    131 	Stream sb = arena_stream(arena);
    132 	stream_append_s8s(&sb, filter_kinds[kind % countof(filter_kinds)], s8("["));
    133 	stream_append_u64(&sb, block);
    134 	stream_append_s8(&sb, s8("]["));
    135 	stream_append_u64(&sb, slot);
    136 	stream_append_byte(&sb, ']');
    137 	s8 label = arena_stream_commit(&arena, &sb);
    138 
    139 	void *filter = 0;
    140 	switch (kind) {
    141 	case BeamformerFilterKind_Kaiser:{
    142 		/* TODO(rnp): this should also support complex */
    143 		/* TODO(rnp): implement this as an IFIR filter instead to reduce computation */
    144 		filter = kaiser_low_pass_filter(&arena, fp.Kaiser.cutoff_frequency, fp.sampling_frequency,
    145 		                                fp.Kaiser.beta, (i32)fp.Kaiser.length);
    146 		f->length     = (i32)fp.Kaiser.length;
    147 		f->time_delay = (f32)f->length / 2.0f / fp.sampling_frequency;
    148 	}break;
    149 	case BeamformerFilterKind_MatchedChirp:{
    150 		typeof(fp.MatchedChirp) *mc = &fp.MatchedChirp;
    151 		f32 fs    = fp.sampling_frequency;
    152 		f->length = (i32)(mc->duration * fs);
    153 		if (fp.complex) {
    154 			filter = baseband_chirp(&arena, mc->min_frequency, mc->max_frequency, fs, f->length, 1, 0.5f);
    155 			f->time_delay = complex_filter_first_moment(filter, f->length, fs);
    156 		} else {
    157 			filter = rf_chirp(&arena, mc->min_frequency, mc->max_frequency, fs, f->length, 1);
    158 			f->time_delay = real_filter_first_moment(filter, f->length, fs);
    159 		}
    160 	}break;
    161 	InvalidDefaultCase;
    162 	}
    163 
    164 	f->kind       = kind;
    165 	f->parameters = fp;
    166 
    167 	glDeleteBuffers(1, &f->ssbo);
    168 	glCreateBuffers(1, &f->ssbo);
    169 	glNamedBufferStorage(f->ssbo, f->length * (i32)sizeof(f32) * (fp.complex? 2 : 1), filter, 0);
    170 	glObjectLabel(GL_BUFFER, f->ssbo, (i32)label.len, (c8 *)label.data);
    171 }
    172 
    173 function ComputeFrameIterator
    174 compute_frame_iterator(BeamformerCtx *ctx, u32 start_index, u32 needed_frames)
    175 {
    176 	start_index = start_index % ARRAY_COUNT(ctx->beamform_frames);
    177 
    178 	ComputeFrameIterator result;
    179 	result.frames        = ctx->beamform_frames;
    180 	result.offset        = start_index;
    181 	result.capacity      = ARRAY_COUNT(ctx->beamform_frames);
    182 	result.cursor        = 0;
    183 	result.needed_frames = needed_frames;
    184 	return result;
    185 }
    186 
    187 function BeamformerFrame *
    188 frame_next(ComputeFrameIterator *bfi)
    189 {
    190 	BeamformerFrame *result = 0;
    191 	if (bfi->cursor != bfi->needed_frames) {
    192 		u32 index = (bfi->offset + bfi->cursor++) % bfi->capacity;
    193 		result    = bfi->frames + index;
    194 	}
    195 	return result;
    196 }
    197 
    198 function b32
    199 beamformer_frame_compatible(BeamformerFrame *f, iv3 dim, GLenum gl_kind)
    200 {
    201 	b32 result = gl_kind == f->gl_kind && iv3_equal(dim, f->dim);
    202 	return result;
    203 }
    204 
    205 function iv3
    206 make_valid_output_points(i32 points[3])
    207 {
    208 	iv3 result;
    209 	result.E[0] = MAX(1, points[0]);
    210 	result.E[1] = MAX(1, points[1]);
    211 	result.E[2] = MAX(1, points[2]);
    212 	return result;
    213 }
    214 
    215 function void
    216 alloc_beamform_frame(GLParams *gp, BeamformerFrame *out, iv3 out_dim, GLenum gl_kind, s8 name, Arena arena)
    217 {
    218 	out->dim = make_valid_output_points(out_dim.E);
    219 	if (gp) {
    220 		out->dim.x = MIN(out->dim.x, gp->max_3d_texture_dim);
    221 		out->dim.y = MIN(out->dim.y, gp->max_3d_texture_dim);
    222 		out->dim.z = MIN(out->dim.z, gp->max_3d_texture_dim);
    223 	}
    224 
    225 	/* NOTE: allocate storage for beamformed output data;
    226 	 * this is shared between compute and fragment shaders */
    227 	u32 max_dim = (u32)MAX(out->dim.x, MAX(out->dim.y, out->dim.z));
    228 	out->mips   = (i32)ctz_u32(round_up_power_of_2(max_dim)) + 1;
    229 
    230 	out->gl_kind = gl_kind;
    231 
    232 	Stream label = arena_stream(arena);
    233 	stream_append_s8(&label, name);
    234 	stream_append_byte(&label, '[');
    235 	stream_append_hex_u64(&label, out->id);
    236 	stream_append_byte(&label, ']');
    237 
    238 	glDeleteTextures(1, &out->texture);
    239 	glCreateTextures(GL_TEXTURE_3D, 1, &out->texture);
    240 	glTextureStorage3D(out->texture, out->mips, gl_kind, out->dim.x, out->dim.y, out->dim.z);
    241 
    242 	glTextureParameteri(out->texture, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    243 	glTextureParameteri(out->texture, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    244 
    245 	LABEL_GL_OBJECT(GL_TEXTURE, out->texture, stream_to_s8(&label));
    246 }
    247 
    248 function void
    249 update_hadamard_texture(BeamformerComputePlan *cp, i32 order, Arena arena)
    250 {
    251 	f32 *hadamard = make_hadamard_transpose(&arena, order);
    252 	if (hadamard) {
    253 		cp->hadamard_order = order;
    254 		u32 *texture = cp->textures + BeamformerComputeTextureKind_Hadamard;
    255 		glDeleteTextures(1, texture);
    256 		glCreateTextures(GL_TEXTURE_2D, 1, texture);
    257 		glTextureStorage2D(*texture, 1, GL_R32F, order, order);
    258 		glTextureSubImage2D(*texture, 0, 0, 0, order, order, GL_RED, GL_FLOAT, hadamard);
    259 
    260 		Stream label = arena_stream(arena);
    261 		stream_append_s8(&label, s8("Hadamard"));
    262 		stream_append_i64(&label, order);
    263 		LABEL_GL_OBJECT(GL_TEXTURE, *texture, stream_to_s8(&label));
    264 	}
    265 }
    266 
    267 function void
    268 alloc_shader_storage(BeamformerCtx *ctx, u32 decoded_data_size, Arena arena)
    269 {
    270 	BeamformerComputeContext *cc = &ctx->compute_context;
    271 	glDeleteBuffers(countof(cc->ping_pong_ssbos), cc->ping_pong_ssbos);
    272 	glCreateBuffers(countof(cc->ping_pong_ssbos), cc->ping_pong_ssbos);
    273 
    274 	cc->ping_pong_ssbo_size = decoded_data_size;
    275 
    276 	Stream label = arena_stream(arena);
    277 	stream_append_s8(&label, s8("PingPongSSBO["));
    278 	i32 s_widx = label.widx;
    279 	for (i32 i = 0; i < countof(cc->ping_pong_ssbos); i++) {
    280 		glNamedBufferStorage(cc->ping_pong_ssbos[i], (iz)decoded_data_size, 0, 0);
    281 		stream_append_i64(&label, i);
    282 		stream_append_byte(&label, ']');
    283 		LABEL_GL_OBJECT(GL_BUFFER, cc->ping_pong_ssbos[i], stream_to_s8(&label));
    284 		stream_reset(&label, s_widx);
    285 	}
    286 
    287 	/* TODO(rnp): (25.08.04) cuda lib is heavily broken atm. First there are multiple RF
    288 	 * buffers and cuda decode shouldn't assume that the data is coming from the rf_buffer
    289 	 * ssbo. Second each parameter block may need a different hadamard matrix so ideally
    290 	 * decode should just take the texture as a parameter. Third, none of these dimensions
    291 	 * need to be pre-known by the library unless its allocating GPU memory which it shouldn't
    292 	 * need to do. For now grab out of parameter block 0 but it is not correct */
    293 	BeamformerParameterBlock *pb = beamformer_parameter_block(ctx->shared_memory.region, 0);
    294 	/* NOTE(rnp): these are stubs when CUDA isn't supported */
    295 	cuda_register_buffers(cc->ping_pong_ssbos, countof(cc->ping_pong_ssbos), cc->rf_buffer.ssbo);
    296 	u32 decoded_data_dimension[3] = {pb->parameters.sample_count, pb->parameters.channel_count, pb->parameters.acquisition_count};
    297 	cuda_init(pb->parameters.raw_data_dimensions, decoded_data_dimension);
    298 }
    299 
    300 function void
    301 push_compute_timing_info(ComputeTimingTable *t, ComputeTimingInfo info)
    302 {
    303 	u32 index = atomic_add_u32(&t->write_index, 1) % countof(t->buffer);
    304 	t->buffer[index] = info;
    305 }
    306 
    307 function b32
    308 fill_frame_compute_work(BeamformerCtx *ctx, BeamformWork *work, BeamformerViewPlaneTag plane,
    309                         u32 parameter_block, b32 indirect)
    310 {
    311 	b32 result = work != 0;
    312 	if (result) {
    313 		u32 frame_id    = atomic_add_u32(&ctx->next_render_frame_index, 1);
    314 		u32 frame_index = frame_id % countof(ctx->beamform_frames);
    315 		work->kind      = indirect? BeamformerWorkKind_ComputeIndirect : BeamformerWorkKind_Compute;
    316 		work->lock      = BeamformerSharedMemoryLockKind_DispatchCompute;
    317 		work->compute_context.parameter_block = parameter_block;
    318 		work->compute_context.frame = ctx->beamform_frames + frame_index;
    319 		work->compute_context.frame->ready_to_present = 0;
    320 		work->compute_context.frame->view_plane_tag   = plane;
    321 		work->compute_context.frame->id               = frame_id;
    322 	}
    323 	return result;
    324 }
    325 
    326 function void
    327 do_sum_shader(BeamformerComputeContext *cc, u32 *in_textures, u32 in_texture_count,
    328               u32 out_texture, iv3 out_data_dim)
    329 {
    330 	/* NOTE: zero output before summing */
    331 	glClearTexImage(out_texture, 0, GL_RED, GL_FLOAT, 0);
    332 	glMemoryBarrier(GL_TEXTURE_UPDATE_BARRIER_BIT);
    333 
    334 	glBindImageTexture(0, out_texture, 0, GL_TRUE, 0, GL_READ_WRITE, GL_RG32F);
    335 	for (u32 i = 0; i < in_texture_count; i++) {
    336 		glBindImageTexture(1, in_textures[i], 0, GL_TRUE, 0, GL_READ_ONLY, GL_RG32F);
    337 		glDispatchCompute(ORONE((u32)out_data_dim.x / 32u),
    338 		                  ORONE((u32)out_data_dim.y),
    339 		                  ORONE((u32)out_data_dim.z / 32u));
    340 		glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
    341 	}
    342 }
    343 
    344 struct compute_cursor {
    345 	iv3 cursor;
    346 	uv3 dispatch;
    347 	iv3 target;
    348 	u32 points_per_dispatch;
    349 	u32 completed_points;
    350 	u32 total_points;
    351 };
    352 
    353 function struct compute_cursor
    354 start_compute_cursor(iv3 dim, u32 max_points)
    355 {
    356 	struct compute_cursor result = {0};
    357 	u32 invocations_per_dispatch = DAS_LOCAL_SIZE_X * DAS_LOCAL_SIZE_Y * DAS_LOCAL_SIZE_Z;
    358 
    359 	result.dispatch.y = MIN(max_points / invocations_per_dispatch, (u32)ceil_f32((f32)dim.y / DAS_LOCAL_SIZE_Y));
    360 
    361 	u32 remaining     = max_points / result.dispatch.y;
    362 	result.dispatch.x = MIN(remaining / invocations_per_dispatch, (u32)ceil_f32((f32)dim.x / DAS_LOCAL_SIZE_X));
    363 	result.dispatch.z = MIN(remaining / (invocations_per_dispatch * result.dispatch.x),
    364 	                        (u32)ceil_f32((f32)dim.z / DAS_LOCAL_SIZE_Z));
    365 
    366 	result.target.x = MAX(dim.x / (i32)result.dispatch.x / DAS_LOCAL_SIZE_X, 1);
    367 	result.target.y = MAX(dim.y / (i32)result.dispatch.y / DAS_LOCAL_SIZE_Y, 1);
    368 	result.target.z = MAX(dim.z / (i32)result.dispatch.z / DAS_LOCAL_SIZE_Z, 1);
    369 
    370 	result.points_per_dispatch = 1;
    371 	result.points_per_dispatch *= result.dispatch.x * DAS_LOCAL_SIZE_X;
    372 	result.points_per_dispatch *= result.dispatch.y * DAS_LOCAL_SIZE_Y;
    373 	result.points_per_dispatch *= result.dispatch.z * DAS_LOCAL_SIZE_Z;
    374 
    375 	result.total_points = (u32)(dim.x * dim.y * dim.z);
    376 
    377 	return result;
    378 }
    379 
    380 function iv3
    381 step_compute_cursor(struct compute_cursor *cursor)
    382 {
    383 	cursor->cursor.x += 1;
    384 	if (cursor->cursor.x >= cursor->target.x) {
    385 		cursor->cursor.x  = 0;
    386 		cursor->cursor.y += 1;
    387 		if (cursor->cursor.y >= cursor->target.y) {
    388 			cursor->cursor.y  = 0;
    389 			cursor->cursor.z += 1;
    390 		}
    391 	}
    392 
    393 	cursor->completed_points += cursor->points_per_dispatch;
    394 
    395 	iv3 result = cursor->cursor;
    396 	result.x *= (i32)cursor->dispatch.x * DAS_LOCAL_SIZE_X;
    397 	result.y *= (i32)cursor->dispatch.y * DAS_LOCAL_SIZE_Y;
    398 	result.z *= (i32)cursor->dispatch.z * DAS_LOCAL_SIZE_Z;
    399 
    400 	return result;
    401 }
    402 
    403 function b32
    404 compute_cursor_finished(struct compute_cursor *cursor)
    405 {
    406 	b32 result = cursor->completed_points >= cursor->total_points;
    407 	return result;
    408 }
    409 
    410 function m4
    411 das_voxel_transform_matrix(BeamformerParameters *bp)
    412 {
    413 	v3 min = v3_from_f32_array(bp->output_min_coordinate);
    414 	v3 max = v3_from_f32_array(bp->output_max_coordinate);
    415 	v3 extent = v3_abs(v3_sub(max, min));
    416 	v3 points = v3_from_iv3(make_valid_output_points(bp->output_points));
    417 
    418 	m4 T1 = m4_translation(v3_scale(v3_sub(points, (v3){{1.0f, 1.0f, 1.0f}}), -0.5f));
    419 	m4 T2 = m4_translation(v3_add(min, v3_scale(extent, 0.5f)));
    420 	m4 S  = m4_scale(v3_div(extent, points));
    421 
    422 	m4 R;
    423 	switch (bp->das_shader_id) {
    424 	case BeamformerAcquisitionKind_FORCES:
    425 	case BeamformerAcquisitionKind_UFORCES:
    426 	case BeamformerAcquisitionKind_Flash:
    427 	{
    428 		R = m4_identity();
    429 		S.c[1].E[1]  = 0;
    430 		T2.c[3].E[1] = 0;
    431 	}break;
    432 	case BeamformerAcquisitionKind_HERO_PA:
    433 	case BeamformerAcquisitionKind_HERCULES:
    434 	case BeamformerAcquisitionKind_UHERCULES:
    435 	case BeamformerAcquisitionKind_RCA_TPW:
    436 	case BeamformerAcquisitionKind_RCA_VLS:
    437 	{
    438 		R = m4_rotation_about_z(bp->beamform_plane ? 0.0f : 0.25f);
    439 		if (!(points.x > 1 && points.y > 1 && points.z > 1))
    440 			T2.c[3].E[1] = bp->off_axis_pos;
    441 	}break;
    442 	default:{ R = m4_identity(); }break;
    443 	}
    444 	m4 result = m4_mul(R, m4_mul(T2, m4_mul(S, T1)));
    445 	return result;
    446 }
    447 
    448 function void
    449 plan_compute_pipeline(BeamformerComputePlan *cp, BeamformerParameterBlock *pb)
    450 {
    451 	b32 run_cuda_hilbert = 0;
    452 	b32 demodulate       = 0;
    453 
    454 	for (u32 i = 0; i < pb->pipeline.shader_count; i++) {
    455 		switch (pb->pipeline.shaders[i]) {
    456 		case BeamformerShaderKind_CudaHilbert:{ run_cuda_hilbert = 1; }break;
    457 		case BeamformerShaderKind_Demodulate:{  demodulate = 1;       }break;
    458 		default:{}break;
    459 		}
    460 	}
    461 
    462 	if (demodulate) run_cuda_hilbert = 0;
    463 
    464 	cp->iq_pipeline = demodulate || run_cuda_hilbert;
    465 
    466 	f32 sampling_frequency = pb->parameters.sampling_frequency;
    467 	u32 decimation_rate = MAX(pb->parameters.decimation_rate, 1);
    468 	u32 sample_count    = pb->parameters.sample_count;
    469 	if (demodulate) {
    470 		sample_count       /= (2 * decimation_rate);
    471 		sampling_frequency /= 2 * (f32)decimation_rate;
    472 	}
    473 
    474 	cp->rf_size = sample_count * pb->parameters.channel_count * pb->parameters.acquisition_count;
    475 	if (cp->iq_pipeline) cp->rf_size *= 8;
    476 	else                 cp->rf_size *= 4;
    477 
    478 	u32 das_sample_stride   = 1;
    479 	u32 das_transmit_stride = sample_count;
    480 	u32 das_channel_stride  = sample_count * pb->parameters.acquisition_count;
    481 
    482 	f32 time_offset = pb->parameters.time_offset;
    483 
    484 	BeamformerDataKind data_kind = pb->pipeline.data_kind;
    485 	cp->pipeline.shader_count = 0;
    486 	for (u32 i = 0; i < pb->pipeline.shader_count; i++) {
    487 		BeamformerShaderParameters *sp = pb->pipeline.parameters + i;
    488 		u32 slot   = cp->pipeline.shader_count;
    489 		u32 shader = pb->pipeline.shaders[i];
    490 		b32 commit = 0;
    491 
    492 		BeamformerShaderDescriptor *ld = cp->shader_descriptors + slot - 1;
    493 		BeamformerShaderDescriptor *sd = cp->shader_descriptors + slot;
    494 		zero_struct(sd);
    495 
    496 		switch (shader) {
    497 		case BeamformerShaderKind_CudaHilbert:{ commit = run_cuda_hilbert; }break;
    498 		case BeamformerShaderKind_Decode:{
    499 			/* TODO(rnp): rework decode first and demodulate after */
    500 			b32 first = slot == 0;
    501 
    502 			sd->bake.data_kind = data_kind;
    503 			if (!first) {
    504 				if (data_kind == BeamformerDataKind_Int16) {
    505 					sd->bake.data_kind = BeamformerDataKind_Int16Complex;
    506 				} else {
    507 					sd->bake.data_kind = BeamformerDataKind_Float32Complex;
    508 				}
    509 			}
    510 
    511 			BeamformerShaderKind *last_shader = cp->pipeline.shaders + slot - 1;
    512 			assert(first || ((*last_shader == BeamformerShaderKind_Demodulate ||
    513 			                  *last_shader == BeamformerShaderKind_Filter)));
    514 
    515 			BeamformerShaderDecodeBakeParameters *db = &sd->bake.Decode;
    516 			db->decode_mode    = pb->parameters.decode_mode;
    517 			db->transmit_count = pb->parameters.acquisition_count;
    518 
    519 			db->input_sample_stride    = first? 1                                     : ld->bake.Filter.output_sample_stride;
    520 			db->input_channel_stride   = first? pb->parameters.raw_data_dimensions[0] : ld->bake.Filter.output_channel_stride;
    521 			db->input_transmit_stride  = first? pb->parameters.sample_count           : 1;
    522 
    523 			db->output_sample_stride   = das_sample_stride;
    524 			db->output_channel_stride  = das_channel_stride;
    525 			db->output_transmit_stride = das_transmit_stride;
    526 			if (first) {
    527 				db->output_channel_stride  *= decimation_rate;
    528 				db->output_transmit_stride *= decimation_rate;
    529 			}
    530 
    531 			if (run_cuda_hilbert) sd->bake.flags |= BeamformerShaderDecodeFlags_DilateOutput;
    532 
    533 			if (db->decode_mode == BeamformerDecodeMode_None) {
    534 				db->transmits_processed = 1;
    535 				sd->layout.x = 64;
    536 				sd->layout.y = 1;
    537 				sd->layout.z = 1;
    538 			} else if (db->transmit_count > 40) {
    539 				sd->bake.flags |= BeamformerShaderDecodeFlags_UseSharedMemory;
    540 				db->transmits_processed = 2;
    541 
    542 				b32 use_16z  = db->transmit_count == 80 || db->transmit_count == 96 || db->transmit_count == 160;
    543 				sd->layout.x = 4;
    544 				sd->layout.y = 1;
    545 				sd->layout.z = use_16z? 16 : 32;
    546 			} else {
    547 				db->transmits_processed = db->transmit_count;
    548 				/* NOTE(rnp): register caching. using more threads will cause the compiler to do
    549 				 * contortions to avoid spilling registers. using less gives higher performance */
    550 				/* TODO(rnp): may need to be adjusted to 16 on NVIDIA */
    551 				sd->layout.x = 32;
    552 				sd->layout.y = 1;
    553 				sd->layout.z = 1;
    554 			}
    555 
    556 			sd->dispatch.x = (u32)ceil_f32((f32)sample_count                     / (f32)sd->layout.x);
    557 			sd->dispatch.y = (u32)ceil_f32((f32)pb->parameters.channel_count     / (f32)sd->layout.y);
    558 			sd->dispatch.z = (u32)ceil_f32((f32)pb->parameters.acquisition_count / (f32)sd->layout.z / (f32)db->transmits_processed);
    559 
    560 			if (first) sd->dispatch.x *= decimation_rate;
    561 
    562 			/* NOTE(rnp): decode 2 samples per dispatch when data is i16 */
    563 			if (first && data_kind == BeamformerDataKind_Int16)
    564 				sd->dispatch.x = (u32)ceil_f32((f32)sd->dispatch.x / 2);
    565 
    566 			commit = 1;
    567 		}break;
    568 		case BeamformerShaderKind_Demodulate:
    569 		case BeamformerShaderKind_Filter:
    570 		{
    571 			b32 first = slot == 0;
    572 			b32 demod = shader == BeamformerShaderKind_Demodulate;
    573 			BeamformerFilter *f = cp->filters + sp->filter_slot;
    574 
    575 			time_offset += f->time_delay;
    576 
    577 			BeamformerShaderFilterBakeParameters *fb = &sd->bake.Filter;
    578 			fb->filter_length = (u32)f->length;
    579 			if (demod)                 sd->bake.flags |= BeamformerShaderFilterFlags_Demodulate;
    580 			if (f->parameters.complex) sd->bake.flags |= BeamformerShaderFilterFlags_ComplexFilter;
    581 			if (first)                 sd->bake.flags |= BeamformerShaderFilterFlags_MapChannels;
    582 
    583 			sd->bake.data_kind = data_kind;
    584 			if (!first) sd->bake.data_kind = BeamformerDataKind_Float32;
    585 
    586 			/* NOTE(rnp): when we are demodulating we pretend that the sampler was alternating
    587 			 * between sampling the I portion and the Q portion of an IQ signal. Therefore there
    588 			 * is an implicit decimation factor of 2 which must always be included. All code here
    589 			 * assumes that the signal was sampled in such a way that supports this operation.
    590 			 * To recover IQ[n] from the sampled data (RF[n]) we do the following:
    591 			 *   I[n]  = RF[n]
    592 			 *   Q[n]  = RF[n + 1]
    593 			 *   IQ[n] = I[n] - j*Q[n]
    594 			 */
    595 			if (demod) {
    596 				fb->demodulation_frequency = pb->parameters.demodulation_frequency;
    597 				fb->sampling_frequency     = pb->parameters.sampling_frequency / 2;
    598 				fb->decimation_rate        = decimation_rate;
    599 				fb->sample_count           = pb->parameters.sample_count;
    600 
    601 				if (first) {
    602 					fb->input_channel_stride  = pb->parameters.raw_data_dimensions[0] / 2;
    603 					fb->input_sample_stride   = 1;
    604 					fb->input_transmit_stride = pb->parameters.sample_count / 2;
    605 
    606 					/* NOTE(rnp): output optimized layout for decoding */
    607 					fb->output_channel_stride  = das_channel_stride;
    608 					fb->output_sample_stride   = pb->parameters.acquisition_count;
    609 					fb->output_transmit_stride = 1;
    610 				} else {
    611 					assert(cp->pipeline.shaders[slot - 1] == BeamformerShaderKind_Decode);
    612 					fb->input_channel_stride  = ld->bake.Decode.output_channel_stride;
    613 					fb->input_sample_stride   = ld->bake.Decode.output_sample_stride;
    614 					fb->input_transmit_stride = ld->bake.Decode.output_transmit_stride;
    615 
    616 					fb->output_channel_stride  = das_channel_stride;
    617 					fb->output_sample_stride   = das_sample_stride;
    618 					fb->output_transmit_stride = das_transmit_stride;
    619 				}
    620 			} else {
    621 				fb->decimation_rate        = 1;
    622 				fb->output_channel_stride  = sample_count * pb->parameters.acquisition_count;
    623 				fb->output_sample_stride   = 1;
    624 				fb->output_transmit_stride = sample_count;
    625 				fb->input_channel_stride   = sample_count * pb->parameters.acquisition_count;
    626 				fb->input_sample_stride    = 1;
    627 				fb->input_transmit_stride  = sample_count;
    628 				fb->sample_count           = sample_count;
    629 			}
    630 
    631 			/* TODO(rnp): filter may need a different dispatch layout */
    632 			sd->layout.x   = 128;
    633 			sd->layout.y   = 1;
    634 			sd->layout.z   = 1;
    635 			sd->dispatch.x = (u32)ceil_f32((f32)sample_count                     / (f32)sd->layout.x);
    636 			sd->dispatch.y = (u32)ceil_f32((f32)pb->parameters.channel_count     / (f32)sd->layout.y);
    637 			sd->dispatch.z = (u32)ceil_f32((f32)pb->parameters.acquisition_count / (f32)sd->layout.z);
    638 
    639 			commit = 1;
    640 		}break;
    641 		case BeamformerShaderKind_DAS:{
    642 			sd->bake.data_kind = BeamformerDataKind_Float32;
    643 			if (cp->iq_pipeline)
    644 				sd->bake.data_kind = BeamformerDataKind_Float32Complex;
    645 
    646 			BeamformerShaderDASBakeParameters *db = &sd->bake.DAS;
    647 			BeamformerDASUBO *du = &cp->das_ubo_data;
    648 			du->voxel_transform = das_voxel_transform_matrix(&pb->parameters);
    649 			mem_copy(du->xdc_transform.E,     pb->parameters.xdc_transform,     sizeof(du->xdc_transform));
    650 			mem_copy(du->xdc_element_pitch.E, pb->parameters.xdc_element_pitch, sizeof(du->xdc_element_pitch));
    651 			db->sampling_frequency     = sampling_frequency;
    652 			db->demodulation_frequency = pb->parameters.demodulation_frequency;
    653 			db->speed_of_sound         = pb->parameters.speed_of_sound;
    654 			db->time_offset            = time_offset;
    655 			db->f_number               = pb->parameters.f_number;
    656 			db->acquisition_kind       = pb->parameters.das_shader_id;
    657 			db->sample_count           = sample_count;
    658 			db->channel_count          = pb->parameters.channel_count;
    659 			db->acquisition_count      = pb->parameters.acquisition_count;
    660 			db->interpolation_mode     = pb->parameters.interpolation_mode;
    661 			db->transmit_angle         = pb->parameters.focal_vector[0];
    662 			db->focus_depth            = pb->parameters.focal_vector[1];
    663 			db->transmit_receive_orientation = pb->parameters.transmit_receive_orientation;
    664 
    665 			if (pb->parameters.single_focus)        sd->bake.flags |= BeamformerShaderDASFlags_SingleFocus;
    666 			if (pb->parameters.single_orientation)  sd->bake.flags |= BeamformerShaderDASFlags_SingleOrientation;
    667 			if (pb->parameters.coherency_weighting) sd->bake.flags |= BeamformerShaderDASFlags_CoherencyWeighting;
    668 			else                                    sd->bake.flags |= BeamformerShaderDASFlags_Fast;
    669 
    670 			u32 id = pb->parameters.das_shader_id;
    671 			if (id == BeamformerAcquisitionKind_UFORCES || id == BeamformerAcquisitionKind_UHERCULES)
    672 				sd->bake.flags |= BeamformerShaderDASFlags_Sparse;
    673 
    674 			sd->layout.x = DAS_LOCAL_SIZE_X;
    675 			sd->layout.y = DAS_LOCAL_SIZE_Y;
    676 			sd->layout.z = DAS_LOCAL_SIZE_Z;
    677 
    678 			commit = 1;
    679 		}break;
    680 		default:{ commit = 1; }break;
    681 		}
    682 
    683 		if (commit) {
    684 			u32 index = cp->pipeline.shader_count++;
    685 			cp->pipeline.shaders[index]    = shader;
    686 			cp->pipeline.parameters[index] = *sp;
    687 		}
    688 	}
    689 	cp->pipeline.data_kind = data_kind;
    690 }
    691 
    692 function void
    693 stream_push_shader_header(Stream *s, BeamformerShaderKind shader_kind, s8 header)
    694 {
    695 	stream_append_s8s(s, s8("#version 460 core\n\n"), header);
    696 
    697 	switch (shader_kind) {
    698 	case BeamformerShaderKind_DAS:{
    699 		stream_append_s8(s, s8(""
    700 		"layout(location = " str(DAS_VOXEL_OFFSET_UNIFORM_LOC) ") uniform ivec3 u_voxel_offset;\n"
    701 		"layout(location = " str(DAS_CYCLE_T_UNIFORM_LOC)      ") uniform uint  u_cycle_t;\n"
    702 		"layout(location = " str(DAS_FAST_CHANNEL_UNIFORM_LOC) ") uniform int   u_channel;\n\n"
    703 		));
    704 	}break;
    705 	case BeamformerShaderKind_Decode:{
    706 		stream_append_s8s(s, s8(""
    707 		"layout(location = " str(DECODE_FIRST_PASS_UNIFORM_LOC) ") uniform bool u_first_pass;\n\n"
    708 		));
    709 	}break;
    710 	case BeamformerShaderKind_MinMax:{
    711 		stream_append_s8(s, s8("layout(location = " str(MIN_MAX_MIPS_LEVEL_UNIFORM_LOC)
    712 		                       ") uniform int u_mip_map;\n\n"));
    713 	}break;
    714 	case BeamformerShaderKind_Sum:{
    715 		stream_append_s8(s, s8("layout(location = " str(SUM_PRESCALE_UNIFORM_LOC)
    716 		                       ") uniform float u_sum_prescale = 1.0;\n\n"));
    717 	}break;
    718 	default:{}break;
    719 	}
    720 }
    721 
    722 function void
    723 load_compute_shader(BeamformerCtx *ctx, BeamformerComputePlan *cp, u32 shader_slot, Arena arena)
    724 {
    725 	read_only local_persist s8 compute_headers[BeamformerShaderKind_ComputeCount] = {
    726 		/* X(name, type, gltype) */
    727 		#define X(name, t, gltype) "\t" #gltype " " #name ";\n"
    728 		[BeamformerShaderKind_DAS] = s8_comp("layout(std140, binding = 0) uniform parameters {\n"
    729 			BEAMFORMER_DAS_UBO_PARAM_LIST
    730 			"};\n\n"
    731 		),
    732 		#undef X
    733 	};
    734 
    735 	BeamformerShaderKind shader = cp->pipeline.shaders[shader_slot];
    736 
    737 	u32 program          = 0;
    738 	i32 reloadable_index = beamformer_shader_reloadable_index_by_shader[shader];
    739 	if (reloadable_index != -1) {
    740 		BeamformerShaderKind base_shader = beamformer_reloadable_shader_kinds[reloadable_index];
    741 		s8 path;
    742 		if (!BakeShaders)
    743 			path = push_s8_from_parts(&arena, ctx->os.path_separator, s8("shaders"),
    744 		                            beamformer_reloadable_shader_files[reloadable_index]);
    745 
    746 		Stream shader_stream = arena_stream(arena);
    747 		stream_push_shader_header(&shader_stream, base_shader, compute_headers[base_shader]);
    748 
    749 		i32  header_vector_length = beamformer_shader_header_vector_lengths[reloadable_index];
    750 		i32 *header_vector        = beamformer_shader_header_vectors[reloadable_index];
    751 		for (i32 index = 0; index < header_vector_length; index++)
    752 			stream_append_s8(&shader_stream, beamformer_shader_global_header_strings[header_vector[index]]);
    753 
    754 		if (beamformer_shader_bake_parameter_counts[reloadable_index]) {
    755 			i32 count = beamformer_shader_bake_parameter_counts[reloadable_index];
    756 			BeamformerShaderDescriptor *sd = cp->shader_descriptors + shader_slot;
    757 
    758 			if (sd->layout.x != 0) {
    759 				stream_append_s8(&shader_stream,  s8("layout(local_size_x = "));
    760 				stream_append_u64(&shader_stream, sd->layout.x);
    761 				stream_append_s8(&shader_stream,  s8(", local_size_y = "));
    762 				stream_append_u64(&shader_stream, sd->layout.y);
    763 				stream_append_s8(&shader_stream,  s8(", local_size_z = "));
    764 				stream_append_u64(&shader_stream, sd->layout.z);
    765 				stream_append_s8(&shader_stream,  s8(") in;\n\n"));
    766 			}
    767 
    768 			u32 *parameters = (u32 *)&sd->bake;
    769 			s8  *names      = beamformer_shader_bake_parameter_names[reloadable_index];
    770 			u8  *is_float   = beamformer_shader_bake_parameter_is_float[reloadable_index];
    771 			for (i32 index = 0; index < count; index++) {
    772 				stream_append_s8s(&shader_stream, s8("#define "), names[index],
    773 				                  is_float[index]? s8(" uintBitsToFloat") : s8(" "), s8("(0x"));
    774 				stream_append_hex_u64(&shader_stream, parameters[index]);
    775 				stream_append_s8(&shader_stream, s8(")\n"));
    776 			}
    777 
    778 			stream_append_s8(&shader_stream, s8("#define DataKind (0x"));
    779 			stream_append_hex_u64(&shader_stream, sd->bake.data_kind);
    780 			stream_append_s8(&shader_stream, s8(")\n\n"));
    781 
    782 			s8  *flag_names = beamformer_shader_flag_strings[reloadable_index];
    783 			u32  flag_count = beamformer_shader_flag_strings_count[reloadable_index];
    784 			u32  flags      = sd->bake.flags;
    785 			for (u32 bit = 0; bit < flag_count; bit++) {
    786 				stream_append_s8s(&shader_stream, s8("#define "), flag_names[bit],
    787 				                  (flags & (1 << bit))? s8(" 1") : s8(" 0"), s8("\n"));
    788 			}
    789 		}
    790 
    791 		stream_append_s8(&shader_stream, s8("\n#line 1\n"));
    792 
    793 		s8 shader_text;
    794 		if (BakeShaders) {
    795 			stream_append_s8(&shader_stream, beamformer_shader_data[reloadable_index]);
    796 			shader_text = arena_stream_commit(&arena, &shader_stream);
    797 		} else {
    798 			shader_text  = arena_stream_commit(&arena, &shader_stream);
    799 			s8 file_text = os_read_whole_file(&arena, (c8 *)path.data);
    800 
    801 			assert(shader_text.data + shader_text.len == file_text.data);
    802 			shader_text.len += file_text.len;
    803 		}
    804 
    805 		/* TODO(rnp): instance name */
    806 		s8 shader_name = beamformer_shader_names[shader];
    807 		program = load_shader(&ctx->os, arena, &shader_text, (u32 []){GL_COMPUTE_SHADER}, 1, shader_name);
    808 	}
    809 
    810 	glDeleteProgram(cp->programs[shader_slot]);
    811 	cp->programs[shader_slot] = program;
    812 }
    813 
    814 function void
    815 beamformer_commit_parameter_block(BeamformerCtx *ctx, BeamformerComputePlan *cp, u32 block, Arena arena)
    816 {
    817 	BeamformerParameterBlock *pb = beamformer_parameter_block_lock(&ctx->shared_memory, block, -1);
    818 	for EachBit(pb->dirty_regions, region) {
    819 		switch (region) {
    820 		case BeamformerParameterBlockRegion_ComputePipeline:
    821 		case BeamformerParameterBlockRegion_Parameters:
    822 		{
    823 			plan_compute_pipeline(cp, pb);
    824 
    825 			/* NOTE(rnp): these are both handled by plan_compute_pipeline() */
    826 			u32 mask = 1 << BeamformerParameterBlockRegion_ComputePipeline |
    827 			           1 << BeamformerParameterBlockRegion_Parameters;
    828 			pb->dirty_regions &= ~mask;
    829 
    830 			for (u32 shader_slot = 0; shader_slot < cp->pipeline.shader_count; shader_slot++) {
    831 				u128 hash = u128_hash_from_data(cp->shader_descriptors + shader_slot, sizeof(BeamformerShaderDescriptor));
    832 				if (!u128_equal(hash, cp->shader_hashes[shader_slot]))
    833 					cp->dirty_programs |= 1 << shader_slot;
    834 				cp->shader_hashes[shader_slot] = hash;
    835 			}
    836 
    837 			#define X(k, t, v) glNamedBufferSubData(cp->ubos[BeamformerComputeUBOKind_##k], \
    838 			                                        0, sizeof(t), &cp->v ## _ubo_data);
    839 			BEAMFORMER_COMPUTE_UBO_LIST
    840 			#undef X
    841 
    842 			cp->acquisition_count = pb->parameters.acquisition_count;
    843 			cp->acquisition_kind  = pb->parameters.das_shader_id;
    844 
    845 			u32 decoded_data_size = cp->rf_size;
    846 			if (ctx->compute_context.ping_pong_ssbo_size < decoded_data_size)
    847 				alloc_shader_storage(ctx, decoded_data_size, arena);
    848 
    849 			if (cp->hadamard_order != (i32)cp->acquisition_count)
    850 				update_hadamard_texture(cp, (i32)cp->acquisition_count, arena);
    851 
    852 			cp->min_coordinate = v3_from_f32_array(pb->parameters.output_min_coordinate);
    853 			cp->max_coordinate = v3_from_f32_array(pb->parameters.output_max_coordinate);
    854 
    855 			cp->output_points  = make_valid_output_points(pb->parameters.output_points);
    856 			cp->average_frames = pb->parameters.output_points[3];
    857 
    858 			GLenum gl_kind = cp->iq_pipeline ? GL_RG32F : GL_R32F;
    859 			if (cp->average_frames > 1 && !beamformer_frame_compatible(ctx->averaged_frames + 0, cp->output_points, gl_kind)) {
    860 				alloc_beamform_frame(&ctx->gl, ctx->averaged_frames + 0, cp->output_points, gl_kind, s8("Averaged Frame"), arena);
    861 				alloc_beamform_frame(&ctx->gl, ctx->averaged_frames + 1, cp->output_points, gl_kind, s8("Averaged Frame"), arena);
    862 			}
    863 		}break;
    864 		case BeamformerParameterBlockRegion_ChannelMapping:{
    865 			cuda_set_channel_mapping(pb->channel_mapping);
    866 		} /* FALLTHROUGH */
    867 		case BeamformerParameterBlockRegion_FocalVectors:
    868 		case BeamformerParameterBlockRegion_SparseElements:
    869 		case BeamformerParameterBlockRegion_TransmitReceiveOrientations:
    870 		{
    871 			BeamformerComputeTextureKind texture_kind = 0;
    872 			u32 pixel_type = 0, texture_format = 0;
    873 			switch (region) {
    874 			#define X(kind, _gl, tf, pt, ...) \
    875 			case BeamformerParameterBlockRegion_## kind:{            \
    876 				texture_kind   = BeamformerComputeTextureKind_## kind; \
    877 				texture_format = tf;                                   \
    878 				pixel_type     = pt;                                   \
    879 			}break;
    880 			BEAMFORMER_COMPUTE_TEXTURE_LIST
    881 			#undef X
    882 			InvalidDefaultCase;
    883 			}
    884 			glTextureSubImage1D(cp->textures[texture_kind], 0, 0, BeamformerMaxChannelCount,
    885 			                    texture_format, pixel_type,
    886 			                    (u8 *)pb + BeamformerParameterBlockRegionOffsets[region]);
    887 		}break;
    888 		}
    889 	}
    890 	beamformer_parameter_block_unlock(&ctx->shared_memory, block);
    891 }
    892 
    893 function void
    894 do_compute_shader(BeamformerCtx *ctx, BeamformerComputePlan *cp, BeamformerFrame *frame,
    895                   BeamformerShaderKind shader, u32 shader_slot, BeamformerShaderParameters *sp, Arena arena)
    896 {
    897 	BeamformerComputeContext *cc = &ctx->compute_context;
    898 
    899 	u32 program = cp->programs[shader_slot];
    900 	glUseProgram(program);
    901 
    902 	u32 output_ssbo_idx = !cc->last_output_ssbo_index;
    903 	u32 input_ssbo_idx  = cc->last_output_ssbo_index;
    904 
    905 	uv3 dispatch = cp->shader_descriptors[shader_slot].dispatch;
    906 	switch (shader) {
    907 	case BeamformerShaderKind_Decode:{
    908 		glBindImageTexture(0, cp->textures[BeamformerComputeTextureKind_Hadamard], 0, 0, 0, GL_READ_ONLY, GL_R32F);
    909 
    910 		if (shader_slot == 0) {
    911 			glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, cc->ping_pong_ssbos[input_ssbo_idx]);
    912 			glBindImageTexture(1, cp->textures[BeamformerComputeTextureKind_ChannelMapping], 0, 0, 0, GL_READ_ONLY, GL_R16I);
    913 			glProgramUniform1ui(program, DECODE_FIRST_PASS_UNIFORM_LOC, 1);
    914 
    915 			glDispatchCompute(dispatch.x, dispatch.y, dispatch.z);
    916 			glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT);
    917 		}
    918 
    919 		glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, cc->ping_pong_ssbos[input_ssbo_idx]);
    920 		glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, cc->ping_pong_ssbos[output_ssbo_idx]);
    921 
    922 		glProgramUniform1ui(program, DECODE_FIRST_PASS_UNIFORM_LOC, 0);
    923 
    924 		glDispatchCompute(dispatch.x, dispatch.y, dispatch.z);
    925 		glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT);
    926 
    927 		cc->last_output_ssbo_index = !cc->last_output_ssbo_index;
    928 	}break;
    929 	case BeamformerShaderKind_CudaDecode:{
    930 		cuda_decode(0, output_ssbo_idx, 0);
    931 		cc->last_output_ssbo_index = !cc->last_output_ssbo_index;
    932 	}break;
    933 	case BeamformerShaderKind_CudaHilbert:{
    934 		cuda_hilbert(input_ssbo_idx, output_ssbo_idx);
    935 		cc->last_output_ssbo_index = !cc->last_output_ssbo_index;
    936 	}break;
    937 	case BeamformerShaderKind_Filter:
    938 	case BeamformerShaderKind_Demodulate:
    939 	{
    940 		b32 map_channels = (cp->shader_descriptors[shader_slot].bake.flags & BeamformerShaderFilterFlags_MapChannels) != 0;
    941 
    942 		glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, cc->ping_pong_ssbos[output_ssbo_idx]);
    943 		glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, cp->filters[sp->filter_slot].ssbo);
    944 
    945 		if (!map_channels)
    946 			glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, cc->ping_pong_ssbos[input_ssbo_idx]);
    947 		else
    948 			glBindImageTexture(1, cp->textures[BeamformerComputeTextureKind_ChannelMapping], 0, 0, 0, GL_READ_ONLY, GL_R16I);
    949 
    950 		glDispatchCompute(dispatch.x, dispatch.y, dispatch.z);
    951 		glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT);
    952 
    953 		cc->last_output_ssbo_index = !cc->last_output_ssbo_index;
    954 	}break;
    955 	case BeamformerShaderKind_MinMax:{
    956 		for (i32 i = 1; i < frame->mips; i++) {
    957 			glBindImageTexture(0, frame->texture, i - 1, GL_TRUE, 0, GL_READ_ONLY,  GL_RG32F);
    958 			glBindImageTexture(1, frame->texture, i - 0, GL_TRUE, 0, GL_WRITE_ONLY, GL_RG32F);
    959 			glProgramUniform1i(program, MIN_MAX_MIPS_LEVEL_UNIFORM_LOC, i);
    960 
    961 			u32 width  = (u32)frame->dim.x >> i;
    962 			u32 height = (u32)frame->dim.y >> i;
    963 			u32 depth  = (u32)frame->dim.z >> i;
    964 			glDispatchCompute(ORONE(width / 32), ORONE(height), ORONE(depth / 32));
    965 			glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
    966 		}
    967 	}break;
    968 	case BeamformerShaderKind_DAS:{
    969 		local_persist u32 das_cycle_t = 0;
    970 
    971 		BeamformerShaderBakeParameters *bp = &cp->shader_descriptors[shader_slot].bake;
    972 		b32 fast   = (bp->flags & BeamformerShaderDASFlags_Fast)   != 0;
    973 		b32 sparse = (bp->flags & BeamformerShaderDASFlags_Sparse) != 0;
    974 
    975 		if (fast) {
    976 			glClearTexImage(frame->texture, 0, GL_RED, GL_FLOAT, 0);
    977 			glMemoryBarrier(GL_TEXTURE_UPDATE_BARRIER_BIT);
    978 			glBindImageTexture(0, frame->texture, 0, GL_TRUE, 0, GL_READ_WRITE, cp->iq_pipeline ? GL_RG32F : GL_R32F);
    979 		} else {
    980 			glBindImageTexture(0, frame->texture, 0, GL_TRUE, 0, GL_WRITE_ONLY, cp->iq_pipeline ? GL_RG32F : GL_R32F);
    981 		}
    982 
    983 		u32 sparse_texture = cp->textures[BeamformerComputeTextureKind_SparseElements];
    984 		if (!sparse) sparse_texture = 0;
    985 
    986 		glBindBufferBase(GL_UNIFORM_BUFFER, 0, cp->ubos[BeamformerComputeUBOKind_DAS]);
    987 		glBindBufferRange(GL_SHADER_STORAGE_BUFFER, 1, cc->ping_pong_ssbos[input_ssbo_idx], 0, cp->rf_size);
    988 		glBindImageTexture(1, sparse_texture, 0, 0, 0, GL_READ_ONLY, GL_R16I);
    989 		glBindImageTexture(2, cp->textures[BeamformerComputeTextureKind_FocalVectors], 0, 0, 0, GL_READ_ONLY, GL_RG32F);
    990 		glBindImageTexture(3, cp->textures[BeamformerComputeTextureKind_TransmitReceiveOrientations], 0, 0, 0, GL_READ_ONLY, GL_R8I);
    991 
    992 		glProgramUniform1ui(program, DAS_CYCLE_T_UNIFORM_LOC, das_cycle_t++);
    993 
    994 		if (fast) {
    995 			i32 loop_end;
    996 			if (bp->DAS.acquisition_kind == BeamformerAcquisitionKind_RCA_VLS ||
    997 			    bp->DAS.acquisition_kind == BeamformerAcquisitionKind_RCA_TPW)
    998 			{
    999 				/* NOTE(rnp): to avoid repeatedly sampling the whole focal vectors
   1000 				 * texture we loop over transmits for VLS/TPW */
   1001 				loop_end = (i32)bp->DAS.acquisition_count;
   1002 			} else {
   1003 				loop_end = (i32)bp->DAS.channel_count;
   1004 			}
   1005 			f32 percent_per_step = 1.0f / (f32)loop_end;
   1006 			cc->processing_progress = -percent_per_step;
   1007 			for (i32 index = 0; index < loop_end; index++) {
   1008 				cc->processing_progress += percent_per_step;
   1009 				/* IMPORTANT(rnp): prevents OS from coalescing and killing our shader */
   1010 				glFinish();
   1011 				glProgramUniform1i(program, DAS_FAST_CHANNEL_UNIFORM_LOC, index);
   1012 				glDispatchCompute((u32)ceil_f32((f32)frame->dim.x / DAS_LOCAL_SIZE_X),
   1013 				                  (u32)ceil_f32((f32)frame->dim.y / DAS_LOCAL_SIZE_Y),
   1014 				                  (u32)ceil_f32((f32)frame->dim.z / DAS_LOCAL_SIZE_Z));
   1015 				glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
   1016 			}
   1017 		} else {
   1018 			#if 1
   1019 			/* TODO(rnp): compute max_points_per_dispatch based on something like a
   1020 			 * transmit_count * channel_count product */
   1021 			u32 max_points_per_dispatch = KB(64);
   1022 			struct compute_cursor cursor = start_compute_cursor(frame->dim, max_points_per_dispatch);
   1023 			f32 percent_per_step = (f32)cursor.points_per_dispatch / (f32)cursor.total_points;
   1024 			cc->processing_progress = -percent_per_step;
   1025 			for (iv3 offset = {0};
   1026 			     !compute_cursor_finished(&cursor);
   1027 			     offset = step_compute_cursor(&cursor))
   1028 			{
   1029 				cc->processing_progress += percent_per_step;
   1030 				/* IMPORTANT(rnp): prevents OS from coalescing and killing our shader */
   1031 				glFinish();
   1032 				glProgramUniform3iv(program, DAS_VOXEL_OFFSET_UNIFORM_LOC, 1, offset.E);
   1033 				glDispatchCompute(cursor.dispatch.x, cursor.dispatch.y, cursor.dispatch.z);
   1034 			}
   1035 			#else
   1036 			/* NOTE(rnp): use this for testing tiling code. The performance of the above path
   1037 			 * should be the same as this path if everything is working correctly */
   1038 			iv3 compute_dim_offset = {0};
   1039 			glProgramUniform3iv(program, DAS_VOXEL_OFFSET_UNIFORM_LOC, 1, compute_dim_offset.E);
   1040 			glDispatchCompute((u32)ceil_f32((f32)dim.x / DAS_LOCAL_SIZE_X),
   1041 			                  (u32)ceil_f32((f32)dim.y / DAS_LOCAL_SIZE_Y),
   1042 			                  (u32)ceil_f32((f32)dim.z / DAS_LOCAL_SIZE_Z));
   1043 			#endif
   1044 		}
   1045 		glMemoryBarrier(GL_TEXTURE_UPDATE_BARRIER_BIT|GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
   1046 	}break;
   1047 	case BeamformerShaderKind_Sum:{
   1048 		u32 aframe_index = ctx->averaged_frame_index % ARRAY_COUNT(ctx->averaged_frames);
   1049 		BeamformerFrame *aframe = ctx->averaged_frames + aframe_index;
   1050 		aframe->id              = ctx->averaged_frame_index;
   1051 		atomic_store_u32(&aframe->ready_to_present, 0);
   1052 		/* TODO(rnp): hack we need a better way of specifying which frames to sum;
   1053 		 * this is fine for rolling averaging but what if we want to do something else */
   1054 		assert(frame >= ctx->beamform_frames);
   1055 		assert(frame < ctx->beamform_frames + countof(ctx->beamform_frames));
   1056 		u32 base_index   = (u32)(frame - ctx->beamform_frames);
   1057 		u32 to_average   = (u32)cp->average_frames;
   1058 		u32 frame_count  = 0;
   1059 		u32 *in_textures = push_array(&arena, u32, BeamformerMaxSavedFrames);
   1060 		ComputeFrameIterator cfi = compute_frame_iterator(ctx, 1 + base_index - to_average, to_average);
   1061 		for (BeamformerFrame *it = frame_next(&cfi); it; it = frame_next(&cfi))
   1062 			in_textures[frame_count++] = it->texture;
   1063 
   1064 		assert(to_average == frame_count);
   1065 
   1066 		glProgramUniform1f(program, SUM_PRESCALE_UNIFORM_LOC, 1 / (f32)frame_count);
   1067 		do_sum_shader(cc, in_textures, frame_count, aframe->texture, aframe->dim);
   1068 		aframe->min_coordinate   = frame->min_coordinate;
   1069 		aframe->max_coordinate   = frame->max_coordinate;
   1070 		aframe->compound_count   = frame->compound_count;
   1071 		aframe->acquisition_kind = frame->acquisition_kind;
   1072 	}break;
   1073 	InvalidDefaultCase;
   1074 	}
   1075 }
   1076 
   1077 function s8
   1078 shader_text_with_header(s8 header, s8 filepath, b32 has_file, BeamformerShaderKind shader_kind, Arena *arena)
   1079 {
   1080 	Stream sb = arena_stream(*arena);
   1081 	stream_push_shader_header(&sb, shader_kind, header);
   1082 	stream_append_s8(&sb, s8("\n#line 1\n"));
   1083 
   1084 	s8 result;
   1085 	if (BakeShaders) {
   1086 		/* TODO(rnp): better handling of shaders with no backing file */
   1087 		if (has_file) {
   1088 			i32 reloadable_index = beamformer_shader_reloadable_index_by_shader[shader_kind];
   1089 			stream_append_s8(&sb, beamformer_shader_data[reloadable_index]);
   1090 		}
   1091 		result = arena_stream_commit(arena, &sb);
   1092 	} else {
   1093 		result = arena_stream_commit(arena, &sb);
   1094 		if (has_file) {
   1095 			s8 file = os_read_whole_file(arena, (c8 *)filepath.data);
   1096 			assert(file.data == result.data + result.len);
   1097 			result.len += file.len;
   1098 		}
   1099 	}
   1100 
   1101 	return result;
   1102 }
   1103 
   1104 /* NOTE(rnp): currently this function is only handling rendering shaders.
   1105  * look at load_compute_shader for compute shaders */
   1106 DEBUG_EXPORT BEAMFORMER_RELOAD_SHADER_FN(beamformer_reload_shader)
   1107 {
   1108 	BeamformerCtx        *ctx  = src->beamformer_context;
   1109 	BeamformerShaderKind  kind = beamformer_reloadable_shader_kinds[src->reloadable_info_index];
   1110 	assert(kind == BeamformerShaderKind_Render3D);
   1111 
   1112 	i32 shader_count = 1;
   1113 	ShaderReloadContext *link = src->link;
   1114 	while (link != src) { shader_count++; link = link->link; }
   1115 
   1116 	s8  *shader_texts = push_array(&arena, s8,  shader_count);
   1117 	u32 *shader_types = push_array(&arena, u32, shader_count);
   1118 
   1119 	i32 index = 0;
   1120 	do {
   1121 		b32 has_file = link->reloadable_info_index >= 0;
   1122 		shader_texts[index] = shader_text_with_header(link->header, path, has_file, kind, &arena);
   1123 		shader_types[index] = link->gl_type;
   1124 		index++;
   1125 		link = link->link;
   1126 	} while (link != src);
   1127 
   1128 	u32 *shader = &ctx->frame_view_render_context.shader;
   1129 	glDeleteProgram(*shader);
   1130 	*shader = load_shader(&ctx->os, arena, shader_texts, shader_types, shader_count, shader_name);
   1131 	ctx->frame_view_render_context.updated = 1;
   1132 
   1133 	return 1;
   1134 }
   1135 
   1136 function void
   1137 complete_queue(BeamformerCtx *ctx, BeamformWorkQueue *q, Arena *arena, iptr gl_context)
   1138 {
   1139 	BeamformerComputeContext *cs = &ctx->compute_context;
   1140 	BeamformerSharedMemory   *sm = ctx->shared_memory.region;
   1141 
   1142 	BeamformWork *work = beamform_work_queue_pop(q);
   1143 	while (work) {
   1144 		b32 can_commit = 1;
   1145 		switch (work->kind) {
   1146 		case BeamformerWorkKind_ReloadShader:{
   1147 			u32 reserved_blocks = sm->reserved_parameter_blocks;
   1148 			for (u32 block = 0; block < reserved_blocks; block++) {
   1149 				BeamformerComputePlan *cp = beamformer_compute_plan_for_block(cs, block, arena);
   1150 				for (u32 slot = 0; slot < cp->pipeline.shader_count; slot++) {
   1151 					i32 shader_index = beamformer_shader_reloadable_index_by_shader[cp->pipeline.shaders[slot]];
   1152 					if (beamformer_reloadable_shader_kinds[shader_index] == work->reload_shader)
   1153 						cp->dirty_programs |= 1 << slot;
   1154 				}
   1155 			}
   1156 
   1157 			if (ctx->latest_frame && !sm->live_imaging_parameters.active) {
   1158 				fill_frame_compute_work(ctx, work, ctx->latest_frame->view_plane_tag,
   1159 				                        ctx->latest_frame->parameter_block, 0);
   1160 				can_commit = 0;
   1161 			}
   1162 		}break;
   1163 		case BeamformerWorkKind_ExportBuffer:{
   1164 			/* TODO(rnp): better way of handling DispatchCompute barrier */
   1165 			post_sync_barrier(&ctx->shared_memory, BeamformerSharedMemoryLockKind_DispatchCompute, sm->locks);
   1166 			os_shared_memory_region_lock(&ctx->shared_memory, sm->locks, (i32)work->lock, (u32)-1);
   1167 			BeamformerExportContext *ec = &work->export_context;
   1168 			switch (ec->kind) {
   1169 			case BeamformerExportKind_BeamformedData:{
   1170 				BeamformerFrame *frame = ctx->latest_frame;
   1171 				if (frame) {
   1172 					assert(frame->ready_to_present);
   1173 					u32 texture  = frame->texture;
   1174 					iv3 dim      = frame->dim;
   1175 					u32 out_size = (u32)dim.x * (u32)dim.y * (u32)dim.z * 2 * sizeof(f32);
   1176 					if (out_size <= ec->size) {
   1177 						glGetTextureImage(texture, 0, GL_RG, GL_FLOAT, (i32)out_size,
   1178 						                  beamformer_shared_memory_scratch_arena(sm).beg);
   1179 					}
   1180 				}
   1181 			}break;
   1182 			case BeamformerExportKind_Stats:{
   1183 				ComputeTimingTable *table = ctx->compute_timing_table;
   1184 				/* NOTE(rnp): do a little spin to let this finish updating */
   1185 				spin_wait(table->write_index != atomic_load_u32(&table->read_index));
   1186 				ComputeShaderStats *stats = ctx->compute_shader_stats;
   1187 				if (sizeof(stats->table) <= ec->size)
   1188 					mem_copy(beamformer_shared_memory_scratch_arena(sm).beg, &stats->table, sizeof(stats->table));
   1189 			}break;
   1190 			InvalidDefaultCase;
   1191 			}
   1192 			os_shared_memory_region_unlock(&ctx->shared_memory, sm->locks, (i32)work->lock);
   1193 			post_sync_barrier(&ctx->shared_memory, BeamformerSharedMemoryLockKind_ExportSync, sm->locks);
   1194 		}break;
   1195 		case BeamformerWorkKind_CreateFilter:{
   1196 			/* TODO(rnp): this should probably get deleted and moved to lazy loading */
   1197 			BeamformerCreateFilterContext *fctx = &work->create_filter_context;
   1198 			u32 block = fctx->parameter_block;
   1199 			u32 slot  = fctx->filter_slot;
   1200 			BeamformerComputePlan *cp = beamformer_compute_plan_for_block(cs, block, arena);
   1201 			beamformer_filter_update(cp->filters + slot, fctx->kind, fctx->parameters, block, slot, *arena);
   1202 		}break;
   1203 		case BeamformerWorkKind_ComputeIndirect:{
   1204 			fill_frame_compute_work(ctx, work, work->compute_indirect_context.view_plane,
   1205 			                        work->compute_indirect_context.parameter_block, 1);
   1206 		} /* FALLTHROUGH */
   1207 		case BeamformerWorkKind_Compute:{
   1208 			DEBUG_DECL(glClearNamedBufferData(cs->ping_pong_ssbos[0], GL_RG32F, GL_RG, GL_FLOAT, 0);)
   1209 			DEBUG_DECL(glClearNamedBufferData(cs->ping_pong_ssbos[1], GL_RG32F, GL_RG, GL_FLOAT, 0);)
   1210 			DEBUG_DECL(glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT);)
   1211 
   1212 			push_compute_timing_info(ctx->compute_timing_table,
   1213 			                         (ComputeTimingInfo){.kind = ComputeTimingInfoKind_ComputeFrameBegin});
   1214 
   1215 			BeamformerComputePlan *cp = beamformer_compute_plan_for_block(cs, work->compute_context.parameter_block, arena);
   1216 			if (beamformer_parameter_block_dirty(sm, work->compute_context.parameter_block)) {
   1217 				u32 block = work->compute_context.parameter_block;
   1218 				beamformer_commit_parameter_block(ctx, cp, block, *arena);
   1219 				atomic_store_u32(&ctx->ui_dirty_parameter_blocks, (u32)(ctx->beamform_work_queue != q) << block);
   1220 			}
   1221 
   1222 			post_sync_barrier(&ctx->shared_memory, work->lock, sm->locks);
   1223 
   1224 			u32 dirty_programs = atomic_swap_u32(&cp->dirty_programs, 0);
   1225 			static_assert(ISPOWEROF2(BeamformerMaxComputeShaderStages),
   1226 			              "max compute shader stages must be power of 2");
   1227 			assert((dirty_programs & ~((u32)BeamformerMaxComputeShaderStages - 1)) == 0);
   1228 			for EachBit(dirty_programs, slot)
   1229 				load_compute_shader(ctx, cp, (u32)slot, *arena);
   1230 
   1231 			atomic_store_u32(&cs->processing_compute, 1);
   1232 			start_renderdoc_capture(gl_context);
   1233 
   1234 			BeamformerFrame *frame = work->compute_context.frame;
   1235 
   1236 			GLenum gl_kind = cp->iq_pipeline ? GL_RG32F : GL_R32F;
   1237 			if (!beamformer_frame_compatible(frame, cp->output_points, gl_kind))
   1238 				alloc_beamform_frame(&ctx->gl, frame, cp->output_points, gl_kind, s8("Beamformed_Data"), *arena);
   1239 
   1240 			frame->min_coordinate   = cp->min_coordinate;
   1241 			frame->max_coordinate   = cp->max_coordinate;
   1242 			frame->acquisition_kind = cp->acquisition_kind;
   1243 			frame->compound_count   = cp->acquisition_count;
   1244 
   1245 			BeamformerComputeContext  *cc       = &ctx->compute_context;
   1246 			BeamformerComputePipeline *pipeline = &cp->pipeline;
   1247 			/* NOTE(rnp): first stage requires access to raw data buffer directly so we break
   1248 			 * it out into a separate step. This way data can get released as soon as possible */
   1249 			if (pipeline->shader_count > 0) {
   1250 				BeamformerRFBuffer *rf = &cs->rf_buffer;
   1251 				u32 slot = rf->compute_index % countof(rf->compute_syncs);
   1252 
   1253 				if (work->kind == BeamformerWorkKind_ComputeIndirect) {
   1254 					/* NOTE(rnp): compute indirect is used when uploading data. if compute thread
   1255 					 * preempts upload it must wait for the fence to exist. then it must tell the
   1256 					 * GPU to wait for upload to complete before it can start compute */
   1257 					spin_wait(!atomic_load_u64(rf->upload_syncs + slot));
   1258 
   1259 					glWaitSync(rf->upload_syncs[slot], 0, GL_TIMEOUT_IGNORED);
   1260 					glDeleteSync(rf->upload_syncs[slot]);
   1261 					rf->compute_index++;
   1262 				} else {
   1263 					slot = (rf->compute_index - 1) % countof(rf->compute_syncs);
   1264 				}
   1265 
   1266 				glBindBufferRange(GL_SHADER_STORAGE_BUFFER, 1, rf->ssbo, slot * rf->active_rf_size, rf->active_rf_size);
   1267 
   1268 				glBeginQuery(GL_TIME_ELAPSED, cc->shader_timer_ids[0]);
   1269 				do_compute_shader(ctx, cp, frame, pipeline->shaders[0], 0, pipeline->parameters + 0, *arena);
   1270 				glEndQuery(GL_TIME_ELAPSED);
   1271 
   1272 				if (work->kind == BeamformerWorkKind_ComputeIndirect) {
   1273 					atomic_store_u64(rf->compute_syncs + slot, glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0));
   1274 					atomic_store_u64(rf->upload_syncs + slot,  0);
   1275 				}
   1276 			}
   1277 
   1278 			b32 did_sum_shader = 0;
   1279 			for (u32 i = 1; i < pipeline->shader_count; i++) {
   1280 				did_sum_shader |= pipeline->shaders[i] == BeamformerShaderKind_Sum;
   1281 				glBeginQuery(GL_TIME_ELAPSED, cc->shader_timer_ids[i]);
   1282 				do_compute_shader(ctx, cp, frame, pipeline->shaders[i], i, pipeline->parameters + i, *arena);
   1283 				glEndQuery(GL_TIME_ELAPSED);
   1284 			}
   1285 
   1286 			/* NOTE(rnp): the first of these blocks until work completes */
   1287 			for (u32 i = 0; i < pipeline->shader_count; i++) {
   1288 				ComputeTimingInfo info = {0};
   1289 				info.kind   = ComputeTimingInfoKind_Shader;
   1290 				info.shader = pipeline->shaders[i];
   1291 				glGetQueryObjectui64v(cc->shader_timer_ids[i], GL_QUERY_RESULT, &info.timer_count);
   1292 				push_compute_timing_info(ctx->compute_timing_table, info);
   1293 			}
   1294 			cs->processing_progress = 1;
   1295 
   1296 			frame->ready_to_present = 1;
   1297 			if (did_sum_shader) {
   1298 				u32 aframe_index = ((ctx->averaged_frame_index++) % countof(ctx->averaged_frames));
   1299 				ctx->averaged_frames[aframe_index].view_plane_tag  = frame->view_plane_tag;
   1300 				ctx->averaged_frames[aframe_index].ready_to_present = 1;
   1301 				atomic_store_u64((u64 *)&ctx->latest_frame, (u64)(ctx->averaged_frames + aframe_index));
   1302 			} else {
   1303 				atomic_store_u64((u64 *)&ctx->latest_frame, (u64)frame);
   1304 			}
   1305 			cs->processing_compute  = 0;
   1306 
   1307 			push_compute_timing_info(ctx->compute_timing_table,
   1308 			                         (ComputeTimingInfo){.kind = ComputeTimingInfoKind_ComputeFrameEnd});
   1309 
   1310 			end_renderdoc_capture(gl_context);
   1311 		}break;
   1312 		InvalidDefaultCase;
   1313 		}
   1314 
   1315 		if (can_commit) {
   1316 			beamform_work_queue_pop_commit(q);
   1317 			work = beamform_work_queue_pop(q);
   1318 		}
   1319 	}
   1320 }
   1321 
   1322 function void
   1323 coalesce_timing_table(ComputeTimingTable *t, ComputeShaderStats *stats)
   1324 {
   1325 	/* TODO(rnp): we do not currently do anything to handle the potential for a half written
   1326 	 * info item. this could result in garbage entries but they shouldn't really matter */
   1327 
   1328 	u32 target = atomic_load_u32(&t->write_index);
   1329 	u32 stats_index = (stats->latest_frame_index + 1) % countof(stats->table.times);
   1330 
   1331 	static_assert(BeamformerShaderKind_Count + 1 <= 32, "timing coalescence bitfield test");
   1332 	u32 seen_info_test = 0;
   1333 
   1334 	while (t->read_index != target) {
   1335 		ComputeTimingInfo info = t->buffer[t->read_index % countof(t->buffer)];
   1336 		switch (info.kind) {
   1337 		case ComputeTimingInfoKind_ComputeFrameBegin:{
   1338 			assert(t->compute_frame_active == 0);
   1339 			t->compute_frame_active = 1;
   1340 			/* NOTE(rnp): allow multiple instances of same shader to accumulate */
   1341 			mem_clear(stats->table.times[stats_index], 0, sizeof(stats->table.times[stats_index]));
   1342 		}break;
   1343 		case ComputeTimingInfoKind_ComputeFrameEnd:{
   1344 			assert(t->compute_frame_active == 1);
   1345 			t->compute_frame_active = 0;
   1346 			stats->latest_frame_index = stats_index;
   1347 			stats_index = (stats_index + 1) % countof(stats->table.times);
   1348 		}break;
   1349 		case ComputeTimingInfoKind_Shader:{
   1350 			stats->table.times[stats_index][info.shader] += (f32)info.timer_count / 1.0e9f;
   1351 			seen_info_test |= (1u << info.shader);
   1352 		}break;
   1353 		case ComputeTimingInfoKind_RF_Data:{
   1354 			stats->latest_rf_index = (stats->latest_rf_index + 1) % countof(stats->table.rf_time_deltas);
   1355 			f32 delta = (f32)(info.timer_count - stats->last_rf_timer_count) / 1.0e9f;
   1356 			stats->table.rf_time_deltas[stats->latest_rf_index] = delta;
   1357 			stats->last_rf_timer_count = info.timer_count;
   1358 			seen_info_test |= (1 << BeamformerShaderKind_Count);
   1359 		}break;
   1360 		}
   1361 		/* NOTE(rnp): do this at the end so that stats table is always in a consistent state */
   1362 		atomic_add_u32(&t->read_index, 1);
   1363 	}
   1364 
   1365 	if (seen_info_test) {
   1366 		for EachEnumValue(BeamformerShaderKind, shader) {
   1367 			if (seen_info_test & (1 << shader)) {
   1368 				f32 sum = 0;
   1369 				for EachElement(stats->table.times, i)
   1370 					sum += stats->table.times[i][shader];
   1371 				stats->average_times[shader] = sum / countof(stats->table.times);
   1372 			}
   1373 		}
   1374 
   1375 		if (seen_info_test & (1 << BeamformerShaderKind_Count)) {
   1376 			f32 sum = 0;
   1377 			for EachElement(stats->table.rf_time_deltas, i)
   1378 				sum += stats->table.rf_time_deltas[i];
   1379 			stats->rf_time_delta_average = sum / countof(stats->table.rf_time_deltas);
   1380 		}
   1381 	}
   1382 }
   1383 
   1384 DEBUG_EXPORT BEAMFORMER_COMPLETE_COMPUTE_FN(beamformer_complete_compute)
   1385 {
   1386 	BeamformerCtx *ctx         = (BeamformerCtx *)user_context;
   1387 	BeamformerSharedMemory *sm = ctx->shared_memory.region;
   1388 	complete_queue(ctx, &sm->external_work_queue, arena, gl_context);
   1389 	complete_queue(ctx, ctx->beamform_work_queue, arena, gl_context);
   1390 }
   1391 
   1392 function void
   1393 beamformer_rf_buffer_allocate(BeamformerRFBuffer *rf, u32 rf_size, Arena arena)
   1394 {
   1395 	assert((rf_size % 64) == 0);
   1396 	glDeleteBuffers(1, &rf->ssbo);
   1397 	glCreateBuffers(1, &rf->ssbo);
   1398 
   1399 	glNamedBufferStorage(rf->ssbo, countof(rf->compute_syncs) * rf_size, 0,
   1400 	                     GL_DYNAMIC_STORAGE_BIT|GL_MAP_WRITE_BIT);
   1401 	LABEL_GL_OBJECT(GL_BUFFER, rf->ssbo, s8("Raw_RF_SSBO"));
   1402 	rf->size = rf_size;
   1403 }
   1404 
   1405 DEBUG_EXPORT BEAMFORMER_RF_UPLOAD_FN(beamformer_rf_upload)
   1406 {
   1407 	BeamformerSharedMemory *sm = ctx->shared_memory->region;
   1408 
   1409 	BeamformerSharedMemoryLockKind scratch_lock = BeamformerSharedMemoryLockKind_ScratchSpace;
   1410 	BeamformerSharedMemoryLockKind upload_lock  = BeamformerSharedMemoryLockKind_UploadRF;
   1411 	u32 scratch_rf_size;
   1412 	if (atomic_load_u32(sm->locks + upload_lock) &&
   1413 	    (scratch_rf_size = atomic_swap_u32(&sm->scratch_rf_size, 0)) &&
   1414 	    os_shared_memory_region_lock(ctx->shared_memory, sm->locks, (i32)scratch_lock, (u32)-1))
   1415 	{
   1416 		BeamformerRFBuffer *rf = ctx->rf_buffer;
   1417 		rf->active_rf_size = (u32)round_up_to(scratch_rf_size, 64);
   1418 		if (rf->size < rf->active_rf_size)
   1419 			beamformer_rf_buffer_allocate(rf, rf->active_rf_size, arena);
   1420 
   1421 		u32 slot = rf->insertion_index++ % countof(rf->compute_syncs);
   1422 
   1423 		/* NOTE(rnp): if the rest of the code is functioning then the first
   1424 		 * time the compute thread processes an upload it must have gone
   1425 		 * through this path. therefore it is safe to spin until it gets processed */
   1426 		spin_wait(atomic_load_u64(rf->upload_syncs + slot));
   1427 
   1428 		if (atomic_load_u64(rf->compute_syncs + slot)) {
   1429 			GLenum sync_result = glClientWaitSync(rf->compute_syncs[slot], 0, 1000000000);
   1430 			if (sync_result == GL_TIMEOUT_EXPIRED || sync_result == GL_WAIT_FAILED) {
   1431 				// TODO(rnp): what do?
   1432 			}
   1433 			glDeleteSync(rf->compute_syncs[slot]);
   1434 		}
   1435 
   1436 		/* NOTE(rnp): nVidia's drivers really don't play nice with persistant mapping,
   1437 		 * at least when it is a big as this one wants to be. mapping and unmapping the
   1438 		 * desired range each time doesn't seem to introduce any performance hit */
   1439 		u32 access = GL_MAP_WRITE_BIT|GL_MAP_FLUSH_EXPLICIT_BIT|GL_MAP_UNSYNCHRONIZED_BIT;
   1440 		u8 *buffer = glMapNamedBufferRange(rf->ssbo, slot * rf->active_rf_size, (i32)rf->active_rf_size, access);
   1441 
   1442 		mem_copy(buffer, beamformer_shared_memory_scratch_arena(sm).beg, rf->active_rf_size);
   1443 		os_shared_memory_region_unlock(ctx->shared_memory, sm->locks, (i32)scratch_lock);
   1444 		post_sync_barrier(ctx->shared_memory, upload_lock, sm->locks);
   1445 
   1446 		glFlushMappedNamedBufferRange(rf->ssbo, 0, (i32)rf->active_rf_size);
   1447 		glUnmapNamedBuffer(rf->ssbo);
   1448 
   1449 		atomic_store_u64(rf->upload_syncs + slot,  glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0));
   1450 		atomic_store_u64(rf->compute_syncs + slot, 0);
   1451 
   1452 		os_wake_waiters(ctx->compute_worker_sync);
   1453 
   1454 		ComputeTimingInfo info = {.kind = ComputeTimingInfoKind_RF_Data};
   1455 		glGetQueryObjectui64v(rf->data_timestamp_query, GL_QUERY_RESULT, &info.timer_count);
   1456 		glQueryCounter(rf->data_timestamp_query, GL_TIMESTAMP);
   1457 		push_compute_timing_info(ctx->compute_timing_table, info);
   1458 	}
   1459 }
   1460 
   1461 #include "ui.c"
   1462 
   1463 DEBUG_EXPORT BEAMFORMER_FRAME_STEP_FN(beamformer_frame_step)
   1464 {
   1465 	dt_for_frame = input->dt;
   1466 
   1467 	if (IsWindowResized()) {
   1468 		ctx->window_size.h = GetScreenHeight();
   1469 		ctx->window_size.w = GetScreenWidth();
   1470 	}
   1471 
   1472 	coalesce_timing_table(ctx->compute_timing_table, ctx->compute_shader_stats);
   1473 
   1474 	if (input->executable_reloaded) {
   1475 		ui_init(ctx, ctx->ui_backing_store);
   1476 		DEBUG_DECL(start_frame_capture = ctx->os.start_frame_capture);
   1477 		DEBUG_DECL(end_frame_capture   = ctx->os.end_frame_capture);
   1478 	}
   1479 
   1480 	BeamformerSharedMemory *sm = ctx->shared_memory.region;
   1481 	if (atomic_load_u32(sm->locks + BeamformerSharedMemoryLockKind_UploadRF))
   1482 		os_wake_waiters(&ctx->os.upload_worker.sync_variable);
   1483 
   1484 	BeamformerFrame        *frame = ctx->latest_frame;
   1485 	BeamformerViewPlaneTag  tag   = frame? frame->view_plane_tag : 0;
   1486 	draw_ui(ctx, input, frame, tag);
   1487 
   1488 	ctx->frame_view_render_context.updated = 0;
   1489 
   1490 	if (WindowShouldClose())
   1491 		ctx->should_exit = 1;
   1492 }
   1493 
   1494 /* NOTE(rnp): functions defined in these shouldn't be visible to the whole program */
   1495 #if _DEBUG
   1496   #if OS_LINUX
   1497     #include "os_linux.c"
   1498   #elif OS_WINDOWS
   1499     #include "os_win32.c"
   1500   #endif
   1501 #endif