aboutsummaryrefslogtreecommitdiffstats
path: root/lib/hackrf/hackrf_sink_c.cc
blob: 8ca1b3e8edcb1ce4fc8a2b0e2231f022a16bab97 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
/* -*- c++ -*- */
/*
 * Copyright 2013 Dimitri Stolnikov <horiz0n@gmx.net>
 * Copyright 2014 Hoernchen <la@tfc-server.de>
 *
 * GNU Radio is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3, or (at your option)
 * any later version.
 *
 * GNU Radio is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with GNU Radio; see the file COPYING.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street,
 * Boston, MA 02110-1301, USA.
 */

/*
 * config.h is generated by configure.  It contains the results
 * of probing for features, options etc.  It should be the first
 * file included in your .cc file.
 */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <stdexcept>
#include <iostream>
#include <algorithm>
#ifdef USE_AVX
#include <immintrin.h>
#elif USE_SSE2
#include <emmintrin.h>
#endif

#include <boost/assign.hpp>
#include <boost/format.hpp>
#include <boost/detail/endian.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/thread/thread.hpp>

#include <gnuradio/io_signature.h>

#include "hackrf_sink_c.h"

#include "arg_helpers.h"

using namespace boost::assign;

#define BUF_LEN  (16 * 32 * 512) /* must be multiple of 512 */
#define BUF_NUM   15

#define BYTES_PER_SAMPLE  2 /* HackRF device consumes 8 bit unsigned IQ data */

#define HACKRF_FORMAT_ERROR(ret) \
  boost::str( boost::format("(%d) %s") \
    % ret % hackrf_error_name((enum hackrf_error)ret) ) \

#define HACKRF_THROW_ON_ERROR(ret, msg) \
  if ( ret != HACKRF_SUCCESS )  \
  throw std::runtime_error( boost::str( boost::format(msg " (%d) %s") \
      % ret % hackrf_error_name((enum hackrf_error)ret) ) );

#define HACKRF_FUNC_STR(func, arg) \
  boost::str(boost::format(func "(%d)") % arg) + " has failed"

static inline bool cb_init(circular_buffer_t *cb, size_t capacity, size_t sz)
{
  cb->buffer = malloc(capacity * sz);
  if(cb->buffer == NULL)
    return false; // handle error
  cb->buffer_end = (int8_t *)cb->buffer + capacity * sz;
  cb->capacity = capacity;
  cb->count = 0;
  cb->sz = sz;
  cb->head = cb->buffer;
  cb->tail = cb->buffer;
  return true;
}

static inline void cb_free(circular_buffer_t *cb)
{
  free(cb->buffer);
  cb->buffer = NULL;
  // clear out other fields too, just to be safe
  cb->buffer_end = 0;
  cb->capacity = 0;
  cb->count = 0;
  cb->sz = 0;
  cb->head = 0;
  cb->tail = 0;
}

static inline bool cb_has_room(circular_buffer_t *cb)
{
  if(cb->count == cb->capacity)
    return false;
  return true;
}

static inline bool cb_push_back(circular_buffer_t *cb, const void *item)
{
  if(cb->count == cb->capacity)
    return false; // handle error
  memcpy(cb->head, item, cb->sz);
  cb->head = (int8_t *)cb->head + cb->sz;
  if(cb->head == cb->buffer_end)
    cb->head = cb->buffer;
  cb->count++;
  return true;
}

static inline bool cb_pop_front(circular_buffer_t *cb, void *item)
{
  if(cb->count == 0)
    return false; // handle error
  memcpy(item, cb->tail, cb->sz);
  cb->tail = (int8_t *)cb->tail + cb->sz;
  if(cb->tail == cb->buffer_end)
    cb->tail = cb->buffer;
  cb->count--;
  return true;
}

int hackrf_sink_c::_usage = 0;
boost::mutex hackrf_sink_c::_usage_mutex;

hackrf_sink_c_sptr make_hackrf_sink_c (const std::string & args)
{
  return gnuradio::get_initial_sptr(new hackrf_sink_c (args));
}

/*
 * Specify constraints on number of input and output streams.
 * This info is used to construct the input and output signatures
 * (2nd & 3rd args to gr::block's constructor).  The input and
 * output signatures are used by the runtime system to
 * check that a valid number and type of inputs and outputs
 * are connected to this block.  In this case, we accept
 * only 0 input and 1 output.
 */
static const int MIN_IN = 1;  // mininum number of input streams
static const int MAX_IN = 1;  // maximum number of input streams
static const int MIN_OUT = 0;  // minimum number of output streams
static const int MAX_OUT = 0;  // maximum number of output streams

/*
 * The private constructor
 */
hackrf_sink_c::hackrf_sink_c (const std::string &args)
  : gr::sync_block ("hackrf_sink_c",
        gr::io_signature::make(MIN_IN, MAX_IN, sizeof (gr_complex)),
        gr::io_signature::make(MIN_OUT, MAX_OUT, sizeof (gr_complex))),
    _dev(NULL),
    _buf(NULL),
    _sample_rate(0),
    _center_freq(0),
    _freq_corr(0),
    _auto_gain(false),
    _amp_gain(0),
    _vga_gain(0),
    _bandwidth(0)
{
  int ret;
  std::string *hackrf_serial = NULL;

  dict_t dict = params_to_dict(args);

  if (dict.count("hackrf") && dict["hackrf"].length() > 0)
    hackrf_serial = &dict["hackrf"];

  _buf_num = 0;

  if (dict.count("buffers"))
    _buf_num = boost::lexical_cast< unsigned int >( dict["buffers"] );

  if (0 == _buf_num)
    _buf_num = BUF_NUM;

  {
    boost::mutex::scoped_lock lock( _usage_mutex );

    if ( _usage == 0 )
      hackrf_init(); /* call only once before the first open */

    _usage++;
  }

  _dev = NULL;
#ifdef LIBHACKRF_HAVE_DEVICE_LIST
  if ( hackrf_serial )
    ret = hackrf_open_by_serial( hackrf_serial->c_str(), &_dev );
  else
#endif  
    ret = hackrf_open( &_dev );
  HACKRF_THROW_ON_ERROR(ret, "Failed to open HackRF device")

  uint8_t board_id;
  ret = hackrf_board_id_read( _dev, &board_id );
  HACKRF_THROW_ON_ERROR(ret, "Failed to get HackRF board id")

  char version[40];
  memset(version, 0, sizeof(version));
  ret = hackrf_version_string_read( _dev, version, sizeof(version));
  HACKRF_THROW_ON_ERROR(ret, "Failed to read version string")
#if 0
  read_partid_serialno_t serial_number;
  ret = hackrf_board_partid_serialno_read( _dev, &serial_number );
  HACKRF_THROW_ON_ERROR(ret, "Failed to read serial number")
#endif
  std::cerr << "Using " << hackrf_board_id_name(hackrf_board_id(board_id)) << " "
            << "with firmware " << version << " "
            << std::endl;

  if ( BUF_NUM != _buf_num ) {
    std::cerr << "Using " << _buf_num << " buffers of size " << BUF_LEN << "."
              << std::endl;
  }

  set_center_freq( (get_freq_range().start() + get_freq_range().stop()) / 2.0 );
  set_sample_rate( get_sample_rates().start() );
  set_bandwidth( 0 );

  set_gain( 0 ); /* disable AMP gain stage by default to protect full sprectrum pre-amp from physical damage */

  set_if_gain( 16 ); /* preset to a reasonable default (non-GRC use case) */

  // Check device args to find out if bias/phantom power is desired.
  if ( dict.count("bias_tx") ) {
    bool bias = boost::lexical_cast<bool>( dict["bias_tx"] );
    ret = hackrf_set_antenna_enable(_dev, static_cast<uint8_t>(bias));
    if ( ret != HACKRF_SUCCESS )
    {
      std::cerr << "Failed to apply antenna bias voltage state: " << bias << " " << HACKRF_FORMAT_ERROR(ret) << std::endl;
    }
    else
    {
      std::cerr << (bias ? "Enabled" : "Disabled") << " antenna bias voltage" << std::endl;
    }
  }

  _buf = (int8_t *) malloc( BUF_LEN );

  cb_init( &_cbuf, _buf_num, BUF_LEN );

//  _thread = gr::thread::thread(_hackrf_wait, this);

  ret = hackrf_start_tx( _dev, _hackrf_tx_callback, (void *)this );
  HACKRF_THROW_ON_ERROR(ret, "Failed to start TX streaming")
}

/*
 * Our virtual destructor.
 */
hackrf_sink_c::~hackrf_sink_c ()
{
  if (_dev) {
//    _thread.join();
    int ret = hackrf_stop_tx( _dev );
    HACKRF_THROW_ON_ERROR(ret, "Failed to stop TX streaming")
    ret = hackrf_close( _dev );
    HACKRF_THROW_ON_ERROR(ret, "Failed to close HackRF")
    _dev = NULL;

    {
      boost::mutex::scoped_lock lock( _usage_mutex );

       _usage--;

      if ( _usage == 0 )
        hackrf_exit(); /* call only once after last close */
    }
  }

  free(_buf);
  _buf = NULL;

  cb_free( &_cbuf );
}

int hackrf_sink_c::_hackrf_tx_callback(hackrf_transfer *transfer)
{
  hackrf_sink_c *obj = (hackrf_sink_c *)transfer->tx_ctx;
  return obj->hackrf_tx_callback(transfer->buffer, transfer->valid_length);
}

int hackrf_sink_c::hackrf_tx_callback(unsigned char *buffer, uint32_t length)
{
#if 0
  for (unsigned int i = 0; i < length; ++i) /* simulate noise */
    *buffer++ = rand() % 255;
#else
  {
    boost::mutex::scoped_lock lock( _buf_mutex );

    if ( ! cb_pop_front( &_cbuf, buffer ) ) {
      memset(buffer, 0, length);
      std::cerr << "U" << std::flush;
    } else {
//      std::cerr << "-" << std::flush;
      _buf_cond.notify_one();
    }
  }
#endif
  return 0; // TODO: return -1 on error/stop
}

void hackrf_sink_c::_hackrf_wait(hackrf_sink_c *obj)
{
  obj->hackrf_wait();
}

void hackrf_sink_c::hackrf_wait()
{
}

bool hackrf_sink_c::start()
{
  if ( ! _dev )
    return false;

  _buf_used = 0;
#if 0
  int ret = hackrf_start_tx( _dev, _hackrf_tx_callback, (void *)this );
  if ( ret != HACKRF_SUCCESS ) {
    std::cerr << "Failed to start TX streaming (" << ret << ")" << std::endl;
    return false;
  }
#endif
  return true;
}

bool hackrf_sink_c::stop()
{
  if ( ! _dev )
    return false;
#if 0
  int ret = hackrf_stop_tx( _dev );
  if ( ret != HACKRF_SUCCESS ) {
    std::cerr << "Failed to stop TX streaming (" << ret << ")" << std::endl;
    return false;
  }
#endif
  return true;
}

#ifdef USE_AVX
void convert_avx(const float* inbuf, int8_t* outbuf,const unsigned int count)
{
  __m256 mulme = _mm256_set_ps(127.0f, 127.0f, 127.0f, 127.0f, 127.0f, 127.0f, 127.0f, 127.0f);
  for(unsigned int i=0; i<count;i++){

  __m256i itmp3 = _mm256_cvtps_epi32(_mm256_mul_ps(_mm256_loadu_ps(&inbuf[i*16+0]), mulme));
  __m256i itmp4 = _mm256_cvtps_epi32(_mm256_mul_ps(_mm256_loadu_ps(&inbuf[i*16+8]), mulme));

  __m128i a1 = _mm256_extractf128_si256(itmp3, 1);
  __m128i a0 = _mm256_castsi256_si128(itmp3);
  __m128i a3 = _mm256_extractf128_si256(itmp4, 1);
  __m128i a2 = _mm256_castsi256_si128(itmp4);

  __m128i outshorts1 = _mm_packs_epi32(a0, a1);
  __m128i outshorts2 = _mm_packs_epi32(a2, a3);

  __m128i outbytes = _mm_packs_epi16(outshorts1, outshorts2);

  _mm_storeu_si128 ((__m128i*)&outbuf[i*16], outbytes);
  }
}

#elif USE_SSE2
void convert_sse2(const float* inbuf, int8_t* outbuf,const unsigned int count)
{
  const register __m128 mulme = _mm_set_ps( 127.0f, 127.0f, 127.0f, 127.0f );
  __m128 itmp1,itmp2,itmp3,itmp4;
  __m128i otmp1,otmp2,otmp3,otmp4;

  __m128i outshorts1,outshorts2;
  __m128i outbytes;

  for(unsigned int i=0; i<count;i++){

  itmp1 = _mm_mul_ps(_mm_loadu_ps(&inbuf[i*16+0]), mulme);
  itmp2 = _mm_mul_ps(_mm_loadu_ps(&inbuf[i*16+4]), mulme);
  itmp3 = _mm_mul_ps(_mm_loadu_ps(&inbuf[i*16+8]), mulme);
  itmp4 = _mm_mul_ps(_mm_loadu_ps(&inbuf[i*16+12]), mulme);

  otmp1 = _mm_cvtps_epi32(itmp1);
  otmp2 = _mm_cvtps_epi32(itmp2);
  otmp3 = _mm_cvtps_epi32(itmp3);
  otmp4 = _mm_cvtps_epi32(itmp4);

  outshorts1 = _mm_packs_epi32(otmp1, otmp2);
  outshorts2 = _mm_packs_epi32(otmp3, otmp4);

  outbytes = _mm_packs_epi16(outshorts1, outshorts2);

  _mm_storeu_si128 ((__m128i*)&outbuf[i*16], outbytes);
  }
}
#endif

void convert_default(float* inbuf, int8_t* outbuf,const unsigned int count)
{
  for(unsigned int i=0; i<count;i++){
    outbuf[i]= inbuf[i]*127;
  }
}

int hackrf_sink_c::work( int noutput_items,
                         gr_vector_const_void_star &input_items,
                         gr_vector_void_star &output_items )
{
  const gr_complex *in = (const gr_complex *) input_items[0];

  {
    boost::mutex::scoped_lock lock( _buf_mutex );

    while ( ! cb_has_room(&_cbuf) )
      _buf_cond.wait( lock );
  }

  int8_t *buf = _buf + _buf_used;
  unsigned int prev_buf_used = _buf_used;

  unsigned int remaining = (BUF_LEN-_buf_used)/2; //complex

  unsigned int count = std::min((unsigned int)noutput_items,remaining);
  unsigned int sse_rem = count/8; // 8 complex = 16f==512bit for avx
  unsigned int nosse_rem = count%8; // remainder

#ifdef USE_AVX
  convert_avx((float*)in, buf, sse_rem);
  convert_default((float*)(in+sse_rem*8), buf+(sse_rem*8*2), nosse_rem*2);
#elif USE_SSE2
  convert_sse2((float*)in, buf, sse_rem);
  convert_default((float*)(in+sse_rem*8), buf+(sse_rem*8*2), nosse_rem*2);
#else
  convert_default((float*)in, buf, count*2);
#endif

  _buf_used += (sse_rem*8+nosse_rem)*2;
  int items_consumed = sse_rem*8+nosse_rem;

  if((unsigned int)noutput_items >= remaining) {
    {
      boost::mutex::scoped_lock lock( _buf_mutex );

      if ( ! cb_push_back( &_cbuf, _buf ) ) {
        _buf_used = prev_buf_used;
        items_consumed = 0;
        std::cerr << "O" << std::flush;
      } else {
//        std::cerr << "+" << std::flush;
        _buf_used = 0;
      }
    }
  }

  // Tell runtime system how many input items we consumed on
  // each input stream.
  consume_each(items_consumed);

  // Tell runtime system how many output items we produced.
  return 0;
}

std::vector<std::string> hackrf_sink_c::get_devices()
{
  std::vector<std::string> devices;
  std::string label;
  
  {
    boost::mutex::scoped_lock lock( _usage_mutex );

    if ( _usage == 0 )
      hackrf_init(); /* call only once before the first open */

    _usage++;
  }

#ifdef LIBHACKRF_HAVE_DEVICE_LIST
  hackrf_device_list_t *list = hackrf_device_list();
  
  for (int i = 0; i < list->devicecount; i++) {
    label = "HackRF ";
    label += hackrf_usb_board_id_name( list->usb_board_ids[i] );
    
    std::string args;
    if (list->serial_numbers[i]) {
      std::string serial = boost::lexical_cast< std::string >( list->serial_numbers[i] );
      if (serial.length() > 6)
        serial = serial.substr(serial.length() - 6, 6);
      args = "hackrf=" + serial;
      label += " " + serial;
    } else
      args = "hackrf"; /* will pick the first one, serial number is required for choosing a specific one */

    boost::algorithm::trim(label);

    args += ",label='" + label + "'";
    devices.push_back( args );
  }
  
  hackrf_device_list_free(list);
#else

  int ret;
  hackrf_device *dev = NULL;
  ret = hackrf_open(&dev);
  if ( HACKRF_SUCCESS == ret )
  {
    std::string args = "hackrf=0";

    label = "HackRF";

    uint8_t board_id;
    ret = hackrf_board_id_read( dev, &board_id );
    if ( HACKRF_SUCCESS == ret )
    {
      label += std::string(" ") + hackrf_board_id_name(hackrf_board_id(board_id));
    }

    args += ",label='" + label + "'";
    devices.push_back( args );

    ret = hackrf_close(dev);
  }

#endif

  {
    boost::mutex::scoped_lock lock( _usage_mutex );

     _usage--;

    if ( _usage == 0 )
      hackrf_exit(); /* call only once after last close */
  }

  return devices;
}

size_t hackrf_sink_c::get_num_channels()
{
  return 1;
}

osmosdr::meta_range_t hackrf_sink_c::get_sample_rates()
{
  osmosdr::meta_range_t range;

  /* we only add integer rates here because of better phase noise performance.
   * the user is allowed to request arbitrary (fractional) rates within these
   * boundaries. */

  range += osmosdr::range_t( 8e6 );
  range += osmosdr::range_t( 10e6 );
  range += osmosdr::range_t( 12.5e6 );
  range += osmosdr::range_t( 16e6 );
  range += osmosdr::range_t( 20e6 ); /* confirmed to work on fast machines */

  return range;
}

double hackrf_sink_c::set_sample_rate( double rate )
{
  int ret;

  if (_dev) {
    ret = hackrf_set_sample_rate( _dev, rate );
    if ( HACKRF_SUCCESS == ret ) {
      _sample_rate = rate;
      //set_bandwidth( 0.0 ); /* bandwidth of 0 means automatic filter selection */
    } else {
      HACKRF_THROW_ON_ERROR( ret, HACKRF_FUNC_STR( "hackrf_set_sample_rate", rate ) )
    }
  }

  return get_sample_rate();
}

double hackrf_sink_c::get_sample_rate()
{
  return _sample_rate;
}

osmosdr::freq_range_t hackrf_sink_c::get_freq_range( size_t chan )
{
  osmosdr::freq_range_t range;

  range += osmosdr::range_t( _sample_rate / 2, 7250e6 - _sample_rate / 2 );

  return range;
}

double hackrf_sink_c::set_center_freq( double freq, size_t chan )
{
  int ret;

  #define APPLY_PPM_CORR(val, ppm) ((val) * (1.0 + (ppm) * 0.000001))

  if (_dev) {
    double corr_freq = APPLY_PPM_CORR( freq, _freq_corr );
    ret = hackrf_set_freq( _dev, uint64_t(corr_freq) );
    if ( HACKRF_SUCCESS == ret ) {
      _center_freq = freq;
    } else {
      HACKRF_THROW_ON_ERROR( ret, HACKRF_FUNC_STR( "hackrf_set_freq", corr_freq ) )
    }
  }

  return get_center_freq( chan );
}

double hackrf_sink_c::get_center_freq( size_t chan )
{
  return _center_freq;
}

double hackrf_sink_c::set_freq_corr( double ppm, size_t chan )
{
  _freq_corr = ppm;

  set_center_freq( _center_freq );

  return get_freq_corr( chan );
}

double hackrf_sink_c::get_freq_corr( size_t chan )
{
  return _freq_corr;
}

std::vector<std::string> hackrf_sink_c::get_gain_names( size_t chan )
{
  std::vector< std::string > names;

  names += "RF";
  names += "IF";

  return names;
}

osmosdr::gain_range_t hackrf_sink_c::get_gain_range( size_t chan )
{
  return get_gain_range( "RF", chan );
}

osmosdr::gain_range_t hackrf_sink_c::get_gain_range( const std::string & name, size_t chan )
{
  if ( "RF" == name ) {
    return osmosdr::gain_range_t( 0, 14, 14 );
  }

  if ( "IF" == name ) {
    return osmosdr::gain_range_t( 0, 47, 1 );
  }

  return osmosdr::gain_range_t();
}

bool hackrf_sink_c::set_gain_mode( bool automatic, size_t chan )
{
  _auto_gain = automatic;

  return get_gain_mode(chan);
}

bool hackrf_sink_c::get_gain_mode( size_t chan )
{
  return _auto_gain;
}

double hackrf_sink_c::set_gain( double gain, size_t chan )
{
  int ret;
  osmosdr::gain_range_t rf_gains = get_gain_range( "RF", chan );

  if (_dev) {
    double clip_gain = rf_gains.clip( gain, true );
    uint8_t value = clip_gain == 14.0f ? 1 : 0;

    ret = hackrf_set_amp_enable( _dev, value );
    if ( HACKRF_SUCCESS == ret ) {
      _amp_gain = clip_gain;
    } else {
      HACKRF_THROW_ON_ERROR( ret, HACKRF_FUNC_STR( "hackrf_set_amp_enable", value ) )
    }
  }

  return _amp_gain;
}

double hackrf_sink_c::set_gain( double gain, const std::string & name, size_t chan)
{
  if ( "RF" == name ) {
    return set_gain( gain, chan );
  }

  if ( "IF" == name ) {
    return set_if_gain( gain, chan );
  }

  return set_gain( gain, chan );
}

double hackrf_sink_c::get_gain( size_t chan )
{
  return _amp_gain;
}

double hackrf_sink_c::get_gain( const std::string & name, size_t chan )
{
  if ( "RF" == name ) {
    return get_gain( chan );
  }

  if ( "IF" == name ) {
    return _vga_gain;
  }

  return get_gain( chan );
}

double hackrf_sink_c::set_if_gain( double gain, size_t chan )
{
  int ret;
  osmosdr::gain_range_t if_gains = get_gain_range( "IF", chan );

  if (_dev) {
    double clip_gain = if_gains.clip( gain, true );

    ret = hackrf_set_txvga_gain( _dev, uint32_t(clip_gain) );
    if ( HACKRF_SUCCESS == ret ) {
      _vga_gain = clip_gain;
    } else {
      HACKRF_THROW_ON_ERROR( ret, HACKRF_FUNC_STR( "hackrf_set_txvga_gain", clip_gain ) )
    }
  }

  return _vga_gain;
}

double hackrf_sink_c::set_bb_gain( double gain, size_t chan )
{
  return 0;
}

std::vector< std::string > hackrf_sink_c::get_antennas( size_t chan )
{
  std::vector< std::string > antennas;

  antennas += get_antenna( chan );

  return antennas;
}

std::string hackrf_sink_c::set_antenna( const std::string & antenna, size_t chan )
{
  return get_antenna( chan );
}

std::string hackrf_sink_c::get_antenna( size_t chan )
{
  return "TX/RX";
}

double hackrf_sink_c::set_bandwidth( double bandwidth, size_t chan )
{
  int ret;
//  osmosdr::freq_range_t bandwidths = get_bandwidth_range( chan );

  if ( bandwidth == 0.0 ) /* bandwidth of 0 means automatic filter selection */
    bandwidth = _sample_rate * 0.75; /* select narrower filters to prevent aliasing */

  if ( _dev ) {
    /* compute best default value depending on sample rate (auto filter) */
    uint32_t bw = hackrf_compute_baseband_filter_bw( uint32_t(bandwidth) );
    ret = hackrf_set_baseband_filter_bandwidth( _dev, bw );
    if ( HACKRF_SUCCESS == ret ) {
      _bandwidth = bw;
    } else {
      HACKRF_THROW_ON_ERROR( ret, HACKRF_FUNC_STR( "hackrf_set_baseband_filter_bandwidth", bw ) )
    }
  }

  return _bandwidth;
}

double hackrf_sink_c::get_bandwidth( size_t chan )
{
  return _bandwidth;
}

osmosdr::freq_range_t hackrf_sink_c::get_bandwidth_range( size_t chan )
{
  osmosdr::freq_range_t bandwidths;

  // TODO: read out from libhackrf when an API is available

  bandwidths += osmosdr::range_t( 1750000 );
  bandwidths += osmosdr::range_t( 2500000 );
  bandwidths += osmosdr::range_t( 3500000 );
  bandwidths += osmosdr::range_t( 5000000 );
  bandwidths += osmosdr::range_t( 5500000 );
  bandwidths += osmosdr::range_t( 6000000 );
  bandwidths += osmosdr::range_t( 7000000 );
  bandwidths += osmosdr::range_t( 8000000 );
  bandwidths += osmosdr::range_t( 9000000 );
  bandwidths += osmosdr::range_t( 10000000 );
  bandwidths += osmosdr::range_t( 12000000 );
  bandwidths += osmosdr::range_t( 14000000 );
  bandwidths += osmosdr::range_t( 15000000 );
  bandwidths += osmosdr::range_t( 20000000 );
  bandwidths += osmosdr::range_t( 24000000 );
  bandwidths += osmosdr::range_t( 28000000 );

  return bandwidths;
}