3 * Copyright 2005 Free Software Foundation, Inc.
5 * This file is part of GNU Radio
7 * GNU Radio is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3, or (at your option)
12 * GNU Radio is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with GNU Radio; see the file COPYING. If not, write to
19 * the Free Software Foundation, Inc., 51 Franklin Street,
20 * Boston, MA 02110-1301, USA.
27 #include <gr_throttle.h>
28 #include <gr_io_signature.h>
36 #if !defined(HAVE_NANOSLEEP) && defined(HAVE_SSLEEP)
43 gr_nanosleep(struct timespec *ts)
45 struct timespec *req = ts;
47 int r = nanosleep(req, &rem);
48 while (r < 0 && errno == EINTR){
50 r = nanosleep(req, &rem);
53 perror ("gr_nanosleep");
58 gr_make_throttle(size_t itemsize, double samples_per_sec)
60 return gr_throttle_sptr(new gr_throttle(itemsize, samples_per_sec));
63 gr_throttle::gr_throttle(size_t itemsize, double samples_per_sec)
64 : gr_sync_block("throttle",
65 gr_make_io_signature(1, 1, itemsize),
66 gr_make_io_signature(1, 1, itemsize)),
67 d_itemsize(itemsize), d_samples_per_sec(samples_per_sec),
70 #ifdef HAVE_GETTIMEOFDAY
71 gettimeofday(&d_start, 0);
75 gr_throttle::~gr_throttle()
80 gr_throttle::work (int noutput_items,
81 gr_vector_const_void_star &input_items,
82 gr_vector_void_star &output_items)
84 const char *in = (const char *) input_items[0];
85 char *out = (char *) output_items[0];
87 #if defined(HAVE_GETTIMEOFDAY)
89 // If our average sample rate exceeds our target sample rate,
90 // delay long enough to reduce to our target rate.
93 gettimeofday(&now, 0);
94 long t_usec = now.tv_usec - d_start.tv_usec;
95 long t_sec = now.tv_sec - d_start.tv_sec;
96 double t = (double)t_sec + (double)t_usec * 1e-6;
97 if (t < 1e-6) // avoid unlikely divide by zero
100 double actual_samples_per_sec = d_total_samples / t;
101 if (actual_samples_per_sec > d_samples_per_sec){ // need to delay
102 double delay = d_total_samples / d_samples_per_sec - t;
103 #ifdef HAVE_NANOSLEEP
105 ts.tv_sec = (time_t)floor(delay);
106 ts.tv_nsec = (long)((delay - floor(delay)) * 1e9);
109 Sleep( (DWORD)(delay*1000) );
114 memcpy(out, in, noutput_items * d_itemsize);
115 d_total_samples += noutput_items;
116 return noutput_items;