ogl_beamforming

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

beamformer.c (61111B)


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