[linux-audio-dev] Producer/consumer threads and syncing

New Message Reply About this list Date view Thread view Subject view Author view Other groups

Subject: [linux-audio-dev] Producer/consumer threads and syncing
From: Joakim G. (jocke_AT_gleipnir.com)
Date: Fri Apr 19 2002 - 18:17:54 EEST


Context: Linux/OSS

I have two threads (play_thread and output_thread). The output_thread
write sample chunks of 1024 bytes (from RAM) into a circular (jitter)
buffer (of length 8). The play_thread plays sample chunks from the
same circular buffer.

The question is: How do I keep these two threads in sync?

For now the play_thread opens the audio device in AFMT_U8, 1 channel,
8000Hz (my audio card can manage to open the device in 8018Hz) using 4
fragments a 512 bytes. I use this info to calculate how often the
output_thread should write to the circular buffer, i.e. each 127712us:

1024/(8018*1)*1000000 = 127712us

So far so good.

If I let the play_thread play samples as fast as it can, blocking on
the write(2) system call, it gets _slightly_ to little data to run in
lock step with the output thread. Hmm.

I tried to delay the play_thread using the same 127712 period as the
output_thread, i.e. pseudo code follows:

suspend.tv_sec = 0;
suspend.tv_usec = 127712;

while (1) {
  gettimeofday(&start, NULL);
  ...
  write(audio_fd, ...);
  gettimeofday(&stop, NULL);
  timersub(&stop, &start, &diff); /* macro from <sys/time.h> */
  timersub(&suspend, &diff, &delay);
  usleep(delay.tv_usec);
}

In this case the two threads run in lock step but the playout from the
play_thread is all clicks and garbles.

I tried using SCHED_FIFO just out of desperation. The same.

Any hints and/or comments?

The plan in the long run was to mix several incoming/outgoing udp streams
using a number of threads taking care of mixing/udp in traffic/
udp out traffic/play/recording, on each machine, using gettimeofday to
sync each thread. If I have a problem with the syncing of two threads
within a single UNIX process I will probably have little success with a
more complex scenario though. :-)

Cheers
/Jocke


New Message Reply About this list Date view Thread view Subject view Author view Other groups

This archive was generated by hypermail 2b28 : Fri Apr 19 2002 - 18:08:31 EEST