A classic problem of synchronizing network and audio threads!
I'll do my best to help you with your questions.
1. When to fill the queue with more samples?
You want to fill the queue when it's not too full and not too empty. A good approach is to maintain a threshold for the queue's occupancy. When the queue's size falls below this threshold, you start filling it with more samples.
Let's define some variables:
Q: the queue's capacity (max number of samples it can hold)
L: the low watermark (threshold for filling the queue, e.g., 25% of Q)
H: the high watermark (threshold for not filling the queue, e.g., 75% of Q)
When the queue's occupancy falls below L, you start filling it with more samples. You can use a simple heuristic like:
- If the queue has less than
L samples, fill it with Q - current_size samples.
2. Heuristic approach and synchronization
A common approach is to use a combination of thresholds and timers. Here are some tips:
- Use a circular buffer (or a ring buffer) for the queue, which allows for efficient insertion and removal of samples.
- Set
L and H based on your specific requirements, such as the audio buffer's size, network latency, and desired smoothness.
- Monitor the queue's occupancy and adjust the filling rate accordingly.
- Consider using a rate controller to adjust the filling rate based on the queue's occupancy and the network thread's performance.
Some popular synchronization approaches:
- Producer-Consumer pattern: the network thread produces samples, and the audio thread consumes them.
- Async Queue : use a lock-free or wait-free queue to reduce contention between threads.
For literature and tutorials, I recommend:
- "Designing Audio Effects Plug-Ins in C++" by Will Pirkle (a great resource for audio programming)
- "Real-Time Systems and Programming Languages" by Alan Burns and Andy Wellings (a comprehensive textbook on real-time systems)
- "Thread Synchronization in Audio Applications" by Martin Leslie (a brief article on synchronization techniques)
3. Stopping playback for resampling
To "stop the playback" without stopping the processBlock() function, you can:
- pause the audio thread: temporarily stop processing audio blocks, and then resume when the resampling is complete.
- insert silence: insert a block of silence (zeros) into the audio buffer, effectively "pausing" the playback.
- async resampling: perform resampling in a separate thread, and then swap the resampled buffer with the current one.
Some popular techniques for seamless resampling:
- Async resampling: resample in a separate thread, and then swap buffers.
- Block-based resampling: resample in blocks, and then insert the resampled blocks into the audio buffer.
Keep in mind that the best approach depends on your specific requirements, such as the type of audio processing, latency constraints, and computational resources.
If you'd like more specific advice or clarification on any of these points, feel free to ask!