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 2, 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>
39 gr_nanosleep(struct timespec *ts)
41 struct timespec *req = ts;
43 int r = nanosleep(req, &rem);
44 while (r < 0 && errno == EINTR){
46 r = nanosleep(req, &rem);
49 perror ("gr_nanosleep");
54 gr_make_throttle(size_t itemsize, double samples_per_sec)
56 return gr_throttle_sptr(new gr_throttle(itemsize, samples_per_sec));
59 gr_throttle::gr_throttle(size_t itemsize, double samples_per_sec)
60 : gr_sync_block("throttle",
61 gr_make_io_signature(1, 1, itemsize),
62 gr_make_io_signature(1, 1, itemsize)),
63 d_itemsize(itemsize), d_samples_per_sec(samples_per_sec),
66 #ifdef HAVE_GETTIMEOFDAY
67 gettimeofday(&d_start, 0);
71 gr_throttle::~gr_throttle()
76 gr_throttle::work (int noutput_items,
77 gr_vector_const_void_star &input_items,
78 gr_vector_void_star &output_items)
80 const char *in = (const char *) input_items[0];
81 char *out = (char *) output_items[0];
83 #if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_NANOSLEEP)
85 // If our average sample rate exceeds our target sample rate,
86 // delay long enough to reduce to our target rate.
89 gettimeofday(&now, 0);
90 long t_usec = now.tv_usec - d_start.tv_usec;
91 long t_sec = now.tv_sec - d_start.tv_sec;
92 double t = (double)t_sec + (double)t_usec * 1e-6;
93 if (t < 1e-6) // avoid unlikely divide by zero
96 double actual_samples_per_sec = d_total_samples / t;
97 if (actual_samples_per_sec > d_samples_per_sec){ // need to delay
98 double delay = d_total_samples / d_samples_per_sec - t;
100 ts.tv_sec = (time_t)floor(delay);
101 ts.tv_nsec = (long)((delay - floor(delay)) * 1e9);
106 memcpy(out, in, noutput_items * d_itemsize);
107 d_total_samples += noutput_items;
108 return noutput_items;