soapysdr 0.5.0

Library wrapping SoapySDR, a hardware abstraction layer for many software defined radio devices, including rtl-sdr, HackRF, USRP, LimeSDR, BladeRF, and Airspy.
Documentation
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
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
pub use soapysdr_sys::SoapySDRRange as Range;
use soapysdr_sys::*;
use std::ffi::{CStr, CString};
use std::marker::PhantomData;
use std::os::raw::c_void;
use std::os::raw::{c_char, c_int};
use std::slice;
use std::sync::Arc;

use super::{ArgInfo, Args, Format, StreamSample};
use crate::arginfo::arg_info_from_c;

/// An error code from SoapySDR
#[repr(i32)]
#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)]
#[non_exhaustive]
pub enum ErrorCode {
    /// Returned when read has a timeout.
    Timeout = -1,

    /// Returned for non-specific stream errors.
    StreamError = -2,

    /// Returned when read has data corruption.
    /// For example, the driver saw a malformed packet.
    Corruption = -3,

    /// Returned when read has an overflow condition.
    /// For example, and internal buffer has filled.
    Overflow = -4,

    /// Returned when a requested operation or flag setting
    /// is not supported by the underlying implementation.
    NotSupported = -5,

    /// Returned when a the device encountered a stream time
    /// which was expired (late) or too early to process.
    TimeError = -6,

    /// Returned when write caused an underflow condition.
    /// For example, a continuous stream was interrupted.
    Underflow = -7,

    /// Error without a specific code, see error string
    Other = 0,
}

impl ErrorCode {
    fn from_c(code: c_int) -> ErrorCode {
        match code {
            soapysdr_sys::SOAPY_SDR_TIMEOUT => ErrorCode::Timeout,
            soapysdr_sys::SOAPY_SDR_STREAM_ERROR => ErrorCode::StreamError,
            soapysdr_sys::SOAPY_SDR_CORRUPTION => ErrorCode::Corruption,
            soapysdr_sys::SOAPY_SDR_OVERFLOW => ErrorCode::Overflow,
            soapysdr_sys::SOAPY_SDR_NOT_SUPPORTED => ErrorCode::NotSupported,
            soapysdr_sys::SOAPY_SDR_TIME_ERROR => ErrorCode::TimeError,
            soapysdr_sys::SOAPY_SDR_UNDERFLOW => ErrorCode::Underflow,
            _ => ErrorCode::Other,
        }
    }
}

/// An error type combining an error code and a string message
#[derive(Clone, Debug, Hash)]
pub struct Error {
    pub code: ErrorCode,
    pub message: String,
}

impl ::std::fmt::Display for Error {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        write!(f, "{:?}: {}", self.code, self.message)
    }
}

impl ::std::error::Error for Error {
    fn description(&self) -> &str {
        &self.message[..]
    }
}

/// Transmit or Receive
#[repr(u32)]
#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)]
pub enum Direction {
    /// Transmit direction
    Tx = SOAPY_SDR_TX,

    /// Receive direction
    Rx = SOAPY_SDR_RX,
}

impl From<Direction> for c_int {
    fn from(f: Direction) -> c_int {
        f as c_int
    }
}

struct DeviceInner {
    ptr: *mut SoapySDRDevice,
}

/// Device method implementations are required to be thread safe
unsafe impl Send for DeviceInner {}
unsafe impl Sync for DeviceInner {}

impl Drop for DeviceInner {
    fn drop(&mut self) {
        unsafe {
            SoapySDRDevice_unmake(self.ptr);
        }
    }
}

/// An opened SDR hardware device.
#[derive(Clone)]
pub struct Device {
    inner: Arc<DeviceInner>,
}

impl Device {
    fn from_ptr(ptr: *mut SoapySDRDevice) -> Device {
        Device {
            inner: Arc::new(DeviceInner { ptr }),
        }
    }
}

fn last_error_str() -> String {
    unsafe {
        // Capture error string from thread local storage
        CStr::from_ptr(SoapySDRDevice_lastError())
            .to_string_lossy()
            .into()
    }
}

fn check_error<T>(r: T) -> Result<T, Error> {
    unsafe {
        if SoapySDRDevice_lastStatus() == 0 {
            Ok(r)
        } else {
            Err(Error {
                code: ErrorCode::Other,
                message: last_error_str(),
            })
        }
    }
}

fn check_ret_error(r: c_int) -> Result<(), Error> {
    if r == 0 {
        Ok(())
    } else {
        Err(Error {
            code: ErrorCode::from_c(r),
            message: last_error_str(),
        })
    }
}

fn len_result(ret: c_int) -> Result<c_int, Error> {
    if ret >= 0 {
        Ok(ret)
    } else {
        Err(Error {
            code: ErrorCode::from_c(ret),
            message: last_error_str(),
        })
    }
}

unsafe fn string_result(r: *mut c_char) -> Result<String, Error> {
    unsafe {
        let ptr: *mut c_char = check_error(r)?;
        let ret = CStr::from_ptr(ptr).to_string_lossy().into();
        SoapySDR_free(ptr as *mut c_void);
        Ok(ret)
    }
}

unsafe fn string_list_result<F: FnOnce(*mut usize) -> *mut *mut c_char>(
    f: F,
) -> Result<Vec<String>, Error> {
    unsafe {
        let mut len: usize = 0;
        let mut ptr = check_error(f(&mut len as *mut _))?;
        let ret = slice::from_raw_parts(ptr, len)
            .iter()
            .map(|&p| CStr::from_ptr(p).to_string_lossy().into())
            .collect();
        SoapySDRStrings_clear(&mut ptr as *mut _, len);
        Ok(ret)
    }
}

unsafe fn arg_info_result<F: FnOnce(*mut usize) -> *mut SoapySDRArgInfo>(
    f: F,
) -> Result<Vec<ArgInfo>, Error> {
    unsafe {
        let mut len: usize = 0;
        let ptr = check_error(f(&mut len as *mut _))?;
        let r = slice::from_raw_parts(ptr, len)
            .iter()
            .map(|x| arg_info_from_c(x))
            .collect();
        SoapySDRArgInfoList_clear(ptr, len);
        Ok(r)
    }
}

unsafe fn list_result<T: Copy, F: FnOnce(*mut usize) -> *mut T>(f: F) -> Result<Vec<T>, Error> {
    unsafe {
        let mut len: usize = 0;
        let ptr = check_error(f(&mut len as *mut _))?;
        let ret = slice::from_raw_parts(ptr, len).to_owned();
        SoapySDR_free(ptr as *mut c_void);
        Ok(ret)
    }
}

fn optional_string_arg<S: AsRef<str>>(optstr: Option<S>) -> CString {
    match optstr {
        Some(s) => CString::new(s.as_ref()).expect("Optional arg string contains null"),
        None => CString::new("").unwrap(),
    }
}

/// Enumerate a list of available devices on the system.
///
/// `args`: a set of arguments to filter the devices returned.
///
/// # Example (list all devices)
/// ```
/// for dev in soapysdr::enumerate("").unwrap() {
///     println!("{}", dev);
/// }
/// ```
///
/// This function returns a list of argument lists that can be passed to `Device::new()` to
/// open the device.
pub fn enumerate<A: Into<Args>>(args: A) -> Result<Vec<Args>, Error> {
    unsafe {
        let mut len: usize = 0;
        let devs = check_error(SoapySDRDevice_enumerate(
            args.into().as_raw_const(),
            &mut len as *mut _,
        ))?;
        let args = slice::from_raw_parts(devs, len)
            .iter()
            .map(|&arg| Args::from_raw(arg))
            .collect();
        SoapySDR_free(devs as *mut c_void);
        Ok(args)
    }
}

impl Device {
    /// Find and open a device matching a set of filters.
    ///
    /// # Example
    /// ```
    /// let mut d = soapysdr::Device::new("type=null").unwrap();
    /// ```
    pub fn new<A: Into<Args>>(args: A) -> Result<Device, Error> {
        unsafe {
            let d = check_error(SoapySDRDevice_make(args.into().as_raw_const()))?;
            Ok(Device::from_ptr(d))
        }
    }

    #[doc(hidden)]
    pub fn null_device() -> Device {
        Device::new("type=null").unwrap()
    }

    /// A key that uniquely identifies the device driver.
    ///
    /// This key identifies the underlying implementation.
    /// Several variants of a product may share a driver.
    pub fn driver_key(&self) -> Result<String, Error> {
        unsafe { string_result(SoapySDRDevice_getDriverKey(self.inner.ptr)) }
    }

    /// A key that uniquely identifies the hardware.
    ///
    /// This key should be meaningful to the user to optimize for the underlying hardware.
    pub fn hardware_key(&self) -> Result<String, Error> {
        unsafe { string_result(SoapySDRDevice_getHardwareKey(self.inner.ptr)) }
    }

    /// Query a dictionary of available device information.
    ///
    /// This dictionary can any number of values like
    /// vendor name, product name, revisions, serials...
    ///
    /// This information can be displayed to the user
    /// to help identify the instantiated device.
    pub fn hardware_info(&self) -> Result<Args, Error> {
        unsafe {
            check_error(SoapySDRDevice_getHardwareInfo(self.inner.ptr)).map(|x| Args::from_raw(x))
        }
    }

    /// Get the mapping configuration string.
    pub fn frontend_mapping(&self, direction: Direction) -> Result<String, Error> {
        unsafe {
            string_result(SoapySDRDevice_getFrontendMapping(
                self.inner.ptr,
                direction.into(),
            ))
        }
    }

    /// List the device's sensors.
    pub fn list_sensors(&self) -> Result<Vec<String>, Error> {
        unsafe { string_list_result(|len_ptr| SoapySDRDevice_listSensors(self.inner.ptr, len_ptr)) }
    }

    /// Read sensor value.
    pub fn read_sensor(&self, key: &str) -> Result<String, Error> {
        let key_c = CString::new(key).expect("key contains null byte");
        unsafe { string_result(SoapySDRDevice_readSensor(self.inner.ptr, key_c.as_ptr())) }
    }

    /// Get channel sensor info.
    pub fn get_channel_sensor_info(
        &self,
        dir: Direction,
        channel: usize,
        key: &str,
    ) -> Result<ArgInfo, Error> {
        let key_c = CString::new(key).expect("key contains null byte");
        Ok(unsafe {
            arg_info_from_c(&SoapySDRDevice_getChannelSensorInfo(
                self.inner.ptr,
                dir.into(),
                channel,
                key_c.as_ptr(),
            ))
        })
    }

    /// List the channel's sensors.
    pub fn list_channel_sensors(
        &self,
        dir: Direction,
        channel: usize,
    ) -> Result<Vec<String>, Error> {
        unsafe {
            string_list_result(|len_ptr| {
                SoapySDRDevice_listChannelSensors(self.inner.ptr, dir.into(), channel, len_ptr)
            })
        }
    }

    /// Read channel sensor value.
    pub fn read_channel_sensor(
        &self,
        dir: Direction,
        channel: usize,
        key: &str,
    ) -> Result<String, Error> {
        let key_c = CString::new(key).expect("key contains null byte");
        unsafe {
            string_result(SoapySDRDevice_readChannelSensor(
                self.inner.ptr,
                dir.into(),
                channel,
                key_c.as_ptr(),
            ))
        }
    }

    /// Get sensor info.
    pub fn get_sensor_info(&self, key: &str) -> Result<ArgInfo, Error> {
        let key_c = CString::new(key).expect("key contains null byte");
        Ok(unsafe {
            arg_info_from_c(&SoapySDRDevice_getSensorInfo(
                self.inner.ptr,
                key_c.as_ptr(),
            ))
        })
    }

    /// Set the frontend mapping of available DSP units to RF frontends.
    ///
    /// This controls channel mapping and channel availability.
    pub fn set_frontend_mapping<S: Into<Vec<u8>>>(
        &self,
        direction: Direction,
        mapping: S,
    ) -> Result<(), Error> {
        unsafe {
            let mapping_c = CString::new(mapping).expect("Mapping contains null byte");
            SoapySDRDevice_setFrontendMapping(self.inner.ptr, direction.into(), mapping_c.as_ptr());
            check_error(())
        }
    }

    /// Get a number of channels given the streaming direction
    pub fn num_channels(&self, direction: Direction) -> Result<usize, Error> {
        unsafe {
            check_error(SoapySDRDevice_getNumChannels(
                self.inner.ptr,
                direction.into(),
            ))
        }
    }

    /// Get channel info given the streaming direction
    pub fn channel_info(&self, direction: Direction, channel: usize) -> Result<Args, Error> {
        unsafe {
            check_error(SoapySDRDevice_getChannelInfo(
                self.inner.ptr,
                direction.into(),
                channel,
            ))
            .map(|x| Args::from_raw(x))
        }
    }

    /// Find out if the specified channel is full or half duplex.
    ///
    /// Returns `true` for full duplex, `false` for half duplex.
    pub fn full_duplex(&self, direction: Direction, channel: usize) -> Result<bool, Error> {
        unsafe {
            check_error(SoapySDRDevice_getFullDuplex(
                self.inner.ptr,
                direction.into(),
                channel,
            ))
        }
    }

    /// Query a list of the available stream formats.
    pub fn stream_formats(
        &self,
        direction: Direction,
        channel: usize,
    ) -> Result<Vec<Format>, Error> {
        unsafe {
            let mut len: usize = 0;
            let mut ptr = check_error(SoapySDRDevice_getStreamFormats(
                self.inner.ptr,
                direction.into(),
                channel,
                &mut len as *mut _,
            ))?;
            let ret = slice::from_raw_parts(ptr, len)
                .iter()
                .flat_map(|&p| CStr::from_ptr(p).to_str().ok())
                .flat_map(|s| s.parse().ok())
                .collect();
            SoapySDRStrings_clear(&mut ptr as *mut _, len);
            Ok(ret)
        }
    }

    /// Get the hardware's native stream format and full-scale value for this channel.
    ///
    /// This is the format used by the underlying transport layer,
    /// and the direct buffer access API calls (when available).
    pub fn native_stream_format(
        &self,
        direction: Direction,
        channel: usize,
    ) -> Result<(Format, f64), Error> {
        unsafe {
            let mut fullscale: f64 = 0.0;
            let ptr = check_error(SoapySDRDevice_getNativeStreamFormat(
                self.inner.ptr,
                direction.into(),
                channel,
                &mut fullscale as *mut _,
            ))?;

            let format = CStr::from_ptr(ptr)
                .to_str()
                .ok()
                .and_then(|s| s.parse().ok())
                .ok_or_else(|| Error {
                    code: ErrorCode::Other,
                    message: "Invalid stream format returned by SoapySDR".into(),
                })?;

            Ok((format, fullscale))
        }
    }

    /// Query the argument info description for stream args.
    pub fn stream_args_info(
        &self,
        direction: Direction,
        channel: usize,
    ) -> Result<Vec<ArgInfo>, Error> {
        unsafe {
            arg_info_result(|len_ptr| {
                SoapySDRDevice_getStreamArgsInfo(self.inner.ptr, direction.into(), channel, len_ptr)
            })
        }
    }

    ///  Initialize an RX stream given a list of channels
    pub fn rx_stream<E: StreamSample>(&self, channels: &[usize]) -> Result<RxStream<E>, Error> {
        self.rx_stream_args(channels, ())
    }

    ///  Initialize an RX stream given a list of channels and stream arguments.
    pub fn rx_stream_args<E: StreamSample, A: Into<Args>>(
        &self,
        channels: &[usize],
        args: A,
    ) -> Result<RxStream<E>, Error> {
        unsafe {
            let stream = check_error(SoapySDRDevice_setupStream(
                self.inner.ptr,
                Direction::Rx.into(),
                E::STREAM_FORMAT.as_ptr(),
                channels.as_ptr(),
                channels.len(),
                args.into().as_raw_const(),
            ))?;
            Ok(RxStream {
                device: self.clone(),
                handle: stream,
                nchannels: channels.len(),
                flags: 0,
                time_ns: 0,
                active: false,
                buf_ptrs: vec![std::ptr::null_mut(); channels.len()],
                phantom: PhantomData,
            })
        }
    }

    /// Initialize a TX stream given a list of channels and stream arguments.
    pub fn tx_stream<E: StreamSample>(&self, channels: &[usize]) -> Result<TxStream<E>, Error> {
        self.tx_stream_args(channels, ())
    }

    /// Initialize a TX stream given a list of channels and stream arguments.
    pub fn tx_stream_args<E: StreamSample, A: Into<Args>>(
        &self,
        channels: &[usize],
        args: A,
    ) -> Result<TxStream<E>, Error> {
        unsafe {
            let stream = check_error(SoapySDRDevice_setupStream(
                self.inner.ptr,
                Direction::Tx.into(),
                E::STREAM_FORMAT.as_ptr(),
                channels.as_ptr(),
                channels.len(),
                args.into().as_raw_const(),
            ))?;
            Ok(TxStream {
                device: self.clone(),
                handle: stream,
                nchannels: channels.len(),
                active: false,
                buf_ptrs: vec![std::ptr::null_mut(); channels.len()],
                phantom: PhantomData,
            })
        }
    }

    /// Get a list of available antennas to select on a given chain.
    pub fn antennas(&self, direction: Direction, channel: usize) -> Result<Vec<String>, Error> {
        unsafe {
            string_list_result(|len_ptr| {
                SoapySDRDevice_listAntennas(self.inner.ptr, direction.into(), channel, len_ptr)
            })
        }
    }

    /// Set the selected antenna on a chain.
    pub fn set_antenna<S: Into<Vec<u8>>>(
        &self,
        direction: Direction,
        channel: usize,
        name: S,
    ) -> Result<(), Error> {
        unsafe {
            let name_c = CString::new(name).expect("Antenna name contains null byte");
            SoapySDRDevice_setAntenna(self.inner.ptr, direction.into(), channel, name_c.as_ptr());
            check_error(())
        }
    }

    /// Get the selected antenna on a chain.
    pub fn antenna(&self, direction: Direction, channel: usize) -> Result<String, Error> {
        unsafe {
            string_result(SoapySDRDevice_getAntenna(
                self.inner.ptr,
                direction.into(),
                channel,
            ))
        }
    }

    /// Does the device support automatic DC offset corrections?
    ///
    /// Returns true if automatic corrections are supported
    pub fn has_dc_offset_mode(&self, direction: Direction, channel: usize) -> Result<bool, Error> {
        unsafe {
            check_error(SoapySDRDevice_hasDCOffsetMode(
                self.inner.ptr,
                direction.into(),
                channel,
            ))
        }
    }

    /// Enable or disable automatic DC offset corrections mode.
    pub fn set_dc_offset_mode(
        &self,
        direction: Direction,
        channel: usize,
        automatic: bool,
    ) -> Result<(), Error> {
        unsafe {
            SoapySDRDevice_setDCOffsetMode(self.inner.ptr, direction.into(), channel, automatic);
            check_error(())
        }
    }

    /// Returns true if automatic DC offset mode is enabled
    pub fn dc_offset_mode(&self, direction: Direction, channel: usize) -> Result<bool, Error> {
        unsafe {
            check_error(SoapySDRDevice_getDCOffsetMode(
                self.inner.ptr,
                direction.into(),
                channel,
            ))
        }
    }

    /// Does the device support frontend DC offset corrections?
    ///
    /// Returns true if manual corrections are supported
    pub fn has_dc_offset(&self, direction: Direction, channel: usize) -> Result<bool, Error> {
        unsafe {
            check_error(SoapySDRDevice_hasDCOffset(
                self.inner.ptr,
                direction.into(),
                channel,
            ))
        }
    }

    /// Set the frontend DC offset correction.
    ///
    /// The offsets are configured for each of the I and Q components (1.0 max)
    pub fn set_dc_offset(
        &self,
        direction: Direction,
        channel: usize,
        offset_i: f64,
        offset_q: f64,
    ) -> Result<(), Error> {
        unsafe {
            SoapySDRDevice_setDCOffset(
                self.inner.ptr,
                direction.into(),
                channel,
                offset_i,
                offset_q,
            );
            check_error(())
        }
    }

    /// Get the frontend DC offset correction for (I, Q), 1.0 max
    pub fn dc_offset(&self, direction: Direction, channel: usize) -> Result<(f64, f64), Error> {
        unsafe {
            let mut i: f64 = 0.0;
            let mut q: f64 = 0.0;
            SoapySDRDevice_getDCOffset(
                self.inner.ptr,
                direction.into(),
                channel,
                &mut i as *mut _,
                &mut q as *mut _,
            );
            check_error((i, q))
        }
    }

    /// Does the device support frontend IQ balance correction?
    ///
    /// Returns true if IQ balance corrections are supported.
    pub fn has_iq_balance(&self, direction: Direction, channel: usize) -> Result<bool, Error> {
        unsafe {
            check_error(SoapySDRDevice_hasIQBalance(
                self.inner.ptr,
                direction.into(),
                channel,
            ))
        }
    }

    /// Set the frontend IQ balance correction
    ///
    /// The correction is configured for each of the I and Q components (1.0 max)
    pub fn set_iq_balance(
        &self,
        direction: Direction,
        channel: usize,
        balance_i: f64,
        balance_q: f64,
    ) -> Result<(), Error> {
        unsafe {
            SoapySDRDevice_setIQBalance(
                self.inner.ptr,
                direction.into(),
                channel,
                balance_i,
                balance_q,
            );
            check_error(())
        }
    }

    /// Get the frontend IQ balance correction for (I, Q), 1.0 max
    pub fn iq_balance(&self, direction: Direction, channel: usize) -> Result<(f64, f64), Error> {
        unsafe {
            let mut i: f64 = 0.0;
            let mut q: f64 = 0.0;
            SoapySDRDevice_getIQBalance(
                self.inner.ptr,
                direction.into(),
                channel,
                &mut i as *mut _,
                &mut q as *mut _,
            );
            check_error((i, q))
        }
    }

    /// List available amplification elements.
    ///
    /// Elements should be in order RF to baseband.
    pub fn list_gains(&self, direction: Direction, channel: usize) -> Result<Vec<String>, Error> {
        unsafe {
            string_list_result(|len_ptr| {
                SoapySDRDevice_listGains(self.inner.ptr, direction.into(), channel, len_ptr)
            })
        }
    }

    /// Does the device support automatic gain control?
    pub fn has_gain_mode(&self, direction: Direction, channel: usize) -> Result<bool, Error> {
        unsafe {
            check_error(SoapySDRDevice_hasGainMode(
                self.inner.ptr,
                direction.into(),
                channel,
            ))
        }
    }

    /// Enable or disable automatic gain control.
    pub fn set_gain_mode(
        &self,
        direction: Direction,
        channel: usize,
        automatic: bool,
    ) -> Result<(), Error> {
        unsafe {
            SoapySDRDevice_setGainMode(self.inner.ptr, direction.into(), channel, automatic);
            check_error(())
        }
    }

    /// Returns true if automatic gain control is enabled
    pub fn gain_mode(&self, direction: Direction, channel: usize) -> Result<bool, Error> {
        unsafe {
            check_error(SoapySDRDevice_getGainMode(
                self.inner.ptr,
                direction.into(),
                channel,
            ))
        }
    }

    /// Set the overall amplification in a chain.
    ///
    /// The gain will be distributed automatically across available elements.
    ///
    /// `gain`: the new amplification value in dB
    pub fn set_gain(&self, direction: Direction, channel: usize, gain: f64) -> Result<(), Error> {
        unsafe {
            SoapySDRDevice_setGain(self.inner.ptr, direction.into(), channel, gain);
            check_error(())
        }
    }

    /// Get the overall value of the gain elements in a chain in dB.
    pub fn gain(&self, direction: Direction, channel: usize) -> Result<f64, Error> {
        unsafe {
            check_error(SoapySDRDevice_getGain(
                self.inner.ptr,
                direction.into(),
                channel,
            ))
        }
    }

    /// Get the overall range of possible gain values.
    pub fn gain_range(&self, direction: Direction, channel: usize) -> Result<Range, Error> {
        unsafe {
            check_error(SoapySDRDevice_getGainRange(
                self.inner.ptr,
                direction.into(),
                channel,
            ))
        }
    }

    /// Set the value of a amplification element in a chain.
    ///
    /// # Arguments
    /// * `name`: the name of an amplification element from `Device::list_gains`
    /// * `gain`: the new amplification value in dB
    pub fn set_gain_element<S: Into<Vec<u8>>>(
        &self,
        direction: Direction,
        channel: usize,
        name: S,
        gain: f64,
    ) -> Result<(), Error> {
        unsafe {
            let name_c = CString::new(name).expect("Gain name contains null byte");
            SoapySDRDevice_setGainElement(
                self.inner.ptr,
                direction.into(),
                channel,
                name_c.as_ptr(),
                gain,
            );
            check_error(())
        }
    }

    /// Get the value of an individual amplification element in a chain in dB.
    pub fn gain_element<S: Into<Vec<u8>>>(
        &self,
        direction: Direction,
        channel: usize,
        name: S,
    ) -> Result<f64, Error> {
        unsafe {
            let name_c = CString::new(name).expect("Gain name contains null byte");
            check_error(SoapySDRDevice_getGainElement(
                self.inner.ptr,
                direction.into(),
                channel,
                name_c.as_ptr(),
            ))
        }
    }

    /// Get the range of possible gain values for a specific element.
    pub fn gain_element_range<S: Into<Vec<u8>>>(
        &self,
        direction: Direction,
        channel: usize,
        name: S,
    ) -> Result<Range, Error> {
        unsafe {
            let name_c = CString::new(name).expect("Gain name contains null byte");
            check_error(SoapySDRDevice_getGainElementRange(
                self.inner.ptr,
                direction.into(),
                channel,
                name_c.as_ptr(),
            ))
        }
    }

    /// Get the ranges of overall frequency values.
    pub fn frequency_range(
        &self,
        direction: Direction,
        channel: usize,
    ) -> Result<Vec<Range>, Error> {
        unsafe {
            list_result(|len_ptr| {
                SoapySDRDevice_getFrequencyRange(self.inner.ptr, direction.into(), channel, len_ptr)
            })
        }
    }

    /// Get the overall center frequency of the chain.
    ///
    ///   - For RX, this specifies the down-conversion frequency.
    ///   - For TX, this specifies the up-conversion frequency.
    ///
    /// Returns the center frequency in Hz.
    pub fn frequency(&self, direction: Direction, channel: usize) -> Result<f64, Error> {
        unsafe {
            check_error(SoapySDRDevice_getFrequency(
                self.inner.ptr,
                direction.into(),
                channel,
            ))
        }
    }

    /// Set the center frequency of the chain.
    ///
    ///   - For RX, this specifies the down-conversion frequency.
    ///   - For TX, this specifies the up-conversion frequency.
    ///
    /// The default implementation of `set_frequency` will tune the "RF"
    /// component as close as possible to the requested center frequency in Hz.
    /// Tuning inaccuracies will be compensated for with the "BB" component.
    ///
    /// The `args` can be used to augment the tuning algorithm.
    ///
    ///   - Use `"OFFSET"` to specify an "RF" tuning offset,
    ///     usually with the intention of moving the LO out of the passband.
    ///     The offset will be compensated for using the "BB" component.
    ///   - Use the name of a component for the key and a frequency in Hz
    ///     as the value (any format) to enforce a specific frequency.
    ///     The other components will be tuned with compensation
    ///     to achieve the specified overall frequency.
    ///   - Use the name of a component for the key and the value `"IGNORE"`
    ///     so that the tuning algorithm will avoid altering the component.
    ///   - Vendor specific implementations can also use the same args to augment
    ///     tuning in other ways such as specifying fractional vs integer N tuning.
    ///
    pub fn set_frequency<A: Into<Args>>(
        &self,
        direction: Direction,
        channel: usize,
        frequency: f64,
        args: A,
    ) -> Result<(), Error> {
        unsafe {
            SoapySDRDevice_setFrequency(
                self.inner.ptr,
                direction.into(),
                channel,
                frequency,
                args.into().as_raw_const(),
            );
            check_error(())
        }
    }

    /// List available tunable elements in the chain.
    ///
    /// Elements should be in order RF to baseband.
    pub fn list_frequencies(
        &self,
        direction: Direction,
        channel: usize,
    ) -> Result<Vec<String>, Error> {
        unsafe {
            string_list_result(|len_ptr| {
                SoapySDRDevice_listFrequencies(self.inner.ptr, direction.into(), channel, len_ptr)
            })
        }
    }

    /// Get the range of tunable values for the specified element.
    pub fn component_frequency_range<S: Into<Vec<u8>>>(
        &self,
        direction: Direction,
        channel: usize,
        name: S,
    ) -> Result<Vec<Range>, Error> {
        unsafe {
            let name_c = CString::new(name).expect("Component name contains null byte");
            list_result(|len_ptr| {
                SoapySDRDevice_getFrequencyRangeComponent(
                    self.inner.ptr,
                    direction.into(),
                    channel,
                    name_c.as_ptr(),
                    len_ptr,
                )
            })
        }
    }

    /// Get the frequency of a tunable element in the chain.
    pub fn component_frequency<S: Into<Vec<u8>>>(
        &self,
        direction: Direction,
        channel: usize,
        name: S,
    ) -> Result<f64, Error> {
        unsafe {
            let name_c = CString::new(name).expect("Component name contains null byte");
            check_error(SoapySDRDevice_getFrequencyComponent(
                self.inner.ptr,
                direction.into(),
                channel,
                name_c.as_ptr(),
            ))
        }
    }

    /// Tune the center frequency of the specified element.
    ///
    ///   - For RX, this specifies the down-conversion frequency.
    ///   - For TX, this specifies the up-conversion frequency.
    ///
    /// Recommended names used to represent tunable components:
    ///
    ///   - "CORR" - freq error correction in PPM
    ///   - "RF" - frequency of the RF frontend
    ///   - "BB" - frequency of the baseband DSP
    ///
    pub fn set_component_frequency<S: Into<Vec<u8>>, A: Into<Args>>(
        &self,
        direction: Direction,
        channel: usize,
        name: S,
        frequency: f64,
        args: A,
    ) -> Result<(), Error> {
        unsafe {
            let name_c = CString::new(name).expect("Component name contains null byte");
            SoapySDRDevice_setFrequencyComponent(
                self.inner.ptr,
                direction.into(),
                channel,
                name_c.as_ptr(),
                frequency,
                args.into().as_raw_const(),
            );
            check_error(())
        }
    }

    /// Query the argument info description for tune args.
    pub fn frequency_args_info(
        &self,
        direction: Direction,
        channel: usize,
    ) -> Result<Vec<ArgInfo>, Error> {
        unsafe {
            arg_info_result(|len_ptr| {
                SoapySDRDevice_getFrequencyArgsInfo(
                    self.inner.ptr,
                    direction.into(),
                    channel,
                    len_ptr,
                )
            })
        }
    }

    /// Get the baseband sample rate of the chain in samples per second.
    pub fn sample_rate(&self, direction: Direction, channel: usize) -> Result<f64, Error> {
        unsafe {
            check_error(SoapySDRDevice_getSampleRate(
                self.inner.ptr,
                direction.into(),
                channel,
            ))
        }
    }

    /// Set the baseband sample rate of the chain in samples per second.
    pub fn set_sample_rate(
        &self,
        direction: Direction,
        channel: usize,
        rate: f64,
    ) -> Result<(), Error> {
        unsafe {
            SoapySDRDevice_setSampleRate(self.inner.ptr, direction.into(), channel, rate);
            check_error(())
        }
    }

    /// Get the range of possible baseband sample rates.
    pub fn get_sample_rate_range(
        &self,
        direction: Direction,
        channel: usize,
    ) -> Result<Vec<Range>, Error> {
        unsafe {
            list_result(|len_ptr| {
                SoapySDRDevice_getSampleRateRange(
                    self.inner.ptr,
                    direction.into(),
                    channel,
                    len_ptr,
                )
            })
        }
    }

    /// Get the baseband filter width of the chain in Hz
    pub fn bandwidth(&self, direction: Direction, channel: usize) -> Result<f64, Error> {
        unsafe {
            check_error(SoapySDRDevice_getBandwidth(
                self.inner.ptr,
                direction.into(),
                channel,
            ))
        }
    }

    /// Set the baseband filter width of the chain in Hz
    pub fn set_bandwidth(
        &self,
        direction: Direction,
        channel: usize,
        bandwidth: f64,
    ) -> Result<(), Error> {
        unsafe {
            SoapySDRDevice_setBandwidth(self.inner.ptr, direction.into(), channel, bandwidth);
            check_error(())
        }
    }

    /// Get the ranges of possible baseband filter widths.
    pub fn bandwidth_range(
        &self,
        direction: Direction,
        channel: usize,
    ) -> Result<Vec<Range>, Error> {
        unsafe {
            list_result(|len_ptr| {
                SoapySDRDevice_getBandwidthRange(self.inner.ptr, direction.into(), channel, len_ptr)
            })
        }
    }

    /// List time sources
    pub fn list_time_sources(&self) -> Result<Vec<String>, Error> {
        unsafe {
            string_list_result(|len_ptr| SoapySDRDevice_listTimeSources(self.inner.ptr, len_ptr))
        }
    }

    /// Get the current time source
    pub fn get_time_source(&self) -> Result<String, Error> {
        unsafe { string_result(SoapySDRDevice_getTimeSource(self.inner.ptr)) }
    }

    /// Set the current time source
    pub fn set_time_source<S: Into<Vec<u8>>>(&self, time_source: S) -> Result<(), Error> {
        let time_source = CString::new(time_source).expect("Time source contained null");
        unsafe {
            SoapySDRDevice_setTimeSource(self.inner.ptr, time_source.as_ptr());
            check_error(())
        }
    }

    /// Check whether there is a given hardware time source.
    /// Hardware time sources are not the same as time sources (at least for UHD Devices)
    /// UHD supported hw time sources: "PPS" or "" (i.e. None)
    pub fn has_hardware_time(&self, hw_time_source: Option<&str>) -> Result<bool, Error> {
        let hw_time_source = optional_string_arg(hw_time_source);
        unsafe {
            let has_hw_time =
                SoapySDRDevice_hasHardwareTime(self.inner.ptr, hw_time_source.as_ptr());
            check_error(has_hw_time)
        }
    }

    /// Get the current timestamp in ns
    pub fn get_hardware_time(&self, hw_time_source: Option<&str>) -> Result<i64, Error> {
        let hw_time_source = optional_string_arg(hw_time_source);
        unsafe {
            let tstamp = SoapySDRDevice_getHardwareTime(self.inner.ptr, hw_time_source.as_ptr());
            check_error(tstamp)
        }
    }

    /// Set the current hardware timestmap for the given source
    /// UHD supported hardware times: "CMD","PPS","UNKNOWN_PPS"
    pub fn set_hardware_time(
        &self,
        hw_time_source: Option<&str>,
        new_time_ns: i64,
    ) -> Result<(), Error> {
        let hw_time_source = optional_string_arg(hw_time_source);
        unsafe {
            SoapySDRDevice_setHardwareTime(self.inner.ptr, new_time_ns, hw_time_source.as_ptr());
            check_error(())
        }
    }

    /// List clock sources
    pub fn list_clock_sources(&self) -> Result<Vec<String>, Error> {
        unsafe {
            string_list_result(|len_ptr| SoapySDRDevice_listClockSources(self.inner.ptr, len_ptr))
        }
    }

    /// Get the current clock source
    pub fn get_clock_source(&self) -> Result<String, Error> {
        unsafe { string_result(SoapySDRDevice_getClockSource(self.inner.ptr)) }
    }

    /// Set the current clock source
    pub fn set_clock_source<S: Into<Vec<u8>>>(&self, clock_source: S) -> Result<(), Error> {
        let clock_source = CString::new(clock_source).expect("clock source contained null");
        unsafe {
            SoapySDRDevice_setClockSource(self.inner.ptr, clock_source.as_ptr());
            check_error(())
        }
    }

    /// Get the current master clock rate
    pub fn get_master_clock_rate(&self) -> Result<f64, Error> {
        unsafe { check_error(SoapySDRDevice_getMasterClockRate(self.inner.ptr)) }
    }

    // TODO: sensors

    /// Write a register on device given interface name
    pub fn write_register<S: Into<Vec<u8>>>(
        &self,
        name: S,
        address: u32,
        value: u32,
    ) -> Result<(), Error> {
        let name = CString::new(name).expect("name must not contain null byte");
        unsafe {
            SoapySDRDevice_writeRegister(self.inner.ptr, name.as_ptr(), address, value);
            check_error(())
        }
    }

    /// Read a register on device given interface name
    pub fn read_register<S: Into<Vec<u8>>>(&self, name: S, address: u32) -> Result<u32, Error> {
        let name = CString::new(name).expect("name must not contain null byte");
        unsafe {
            let value = SoapySDRDevice_readRegister(self.inner.ptr, name.as_ptr(), address);
            check_error(value)
        }
    }

    /// Write a memory block on the device given interface name
    pub fn write_registers<S: Into<Vec<u8>>>(
        &self,
        name: S,
        address: u32,
        value: &[u32],
    ) -> Result<(), Error> {
        let name = CString::new(name).expect("name must not contain null byte");
        unsafe {
            SoapySDRDevice_writeRegisters(
                self.inner.ptr,
                name.as_ptr(),
                address,
                value.as_ptr(),
                value.len(),
            );
            check_error(())
        }
    }

    /// Get a list of available register interfaces by name
    pub fn list_register_interfaces(&self) -> Result<Vec<String>, Error> {
        unsafe {
            string_list_result(|len_ptr| {
                SoapySDRDevice_listRegisterInterfaces(self.inner.ptr, len_ptr)
            })
        }
    }

    /// Write a setting
    pub fn write_setting<S: Into<Vec<u8>>>(&self, key: S, value: S) -> Result<(), Error> {
        let key = CString::new(key).expect("key must not contain null byte");
        let value = CString::new(value).expect("value must not contain null byte");
        unsafe {
            check_ret_error(SoapySDRDevice_writeSetting(
                self.inner.ptr,
                key.as_ptr(),
                value.as_ptr(),
            ))?;
            Ok(())
        }
    }

    /// Read a setting
    pub fn read_setting<S: Into<Vec<u8>>>(&self, key: S) -> Result<String, Error> {
        let key = CString::new(key).expect("key must not contain null byte");
        unsafe { string_result(SoapySDRDevice_readSetting(self.inner.ptr, key.as_ptr())) }
    }

    // TODO: gpio

    // TODO: I2C

    // TODO: SPI

    // TODO: UART
}

/// A stream open for receiving.
///
/// To obtain a RxStream, call [Device::rx_stream]. The type parameter `E` represents the type
/// of this stream's samples.
///
/// Streams may involve multiple channels.
pub struct RxStream<E: StreamSample> {
    device: Device,
    handle: *mut SoapySDRStream,
    nchannels: usize,
    flags: i32,
    time_ns: i64,
    active: bool,
    buf_ptrs: Vec<*mut E>,
    phantom: PhantomData<fn(&mut [E])>,
}

/// Streams may only be used on one thread at a time but may be sent between threads
unsafe impl<E: StreamSample> Send for RxStream<E> {}

impl<E: StreamSample> Drop for RxStream<E> {
    fn drop(&mut self) {
        unsafe {
            if self.active {
                self.deactivate(None).ok();
            }
            SoapySDRDevice_closeStream(self.device.inner.ptr, self.handle);
        }
    }
}

impl<E: StreamSample> RxStream<E> {
    /// Get the stream's maximum transmission unit (MTU) in number of elements.
    ///
    /// The MTU specifies the maximum payload transfer in a stream operation.
    /// This value can be used as a stream buffer allocation size that can
    /// best optimize throughput given the underlying stream implementation.
    pub fn mtu(&self) -> Result<usize, Error> {
        unsafe {
            check_error(SoapySDRDevice_getStreamMTU(
                self.device.inner.ptr,
                self.handle,
            ))
        }
    }

    /// Activate a stream.
    ///
    /// Call `activate` to enable a stream before using `read()`
    ///
    /// # Arguments:
    ///   * `time_ns` -- optional activation time in nanoseconds
    pub fn activate(&mut self, time_ns: Option<i64>) -> Result<(), Error> {
        if self.active {
            return Err(Error {
                code: ErrorCode::Other,
                message: "Stream is already active".into(),
            });
        }
        unsafe {
            let flags = if time_ns.is_some() {
                SOAPY_SDR_HAS_TIME as i32
            } else {
                0
            };
            check_ret_error(SoapySDRDevice_activateStream(
                self.device.inner.ptr,
                self.handle,
                flags,
                time_ns.unwrap_or(0),
                0,
            ))?;
            self.active = true;
            Ok(())
        }
    }

    /// Fetch the active state of the stream.
    pub fn active(&self) -> bool {
        self.active
    }

    // TODO: activate_burst()

    /// Deactivate a stream.
    /// The implementation will control switches or halt data flow.
    ///
    /// # Arguments:
    ///   * `time_ns` -- optional deactivation time in nanoseconds
    pub fn deactivate(&mut self, time_ns: Option<i64>) -> Result<(), Error> {
        if !self.active {
            return Err(Error {
                code: ErrorCode::Other,
                message: "Stream is not active".into(),
            });
        }
        unsafe {
            let flags = if time_ns.is_some() {
                SOAPY_SDR_HAS_TIME as i32
            } else {
                0
            };
            check_ret_error(SoapySDRDevice_deactivateStream(
                self.device.inner.ptr,
                self.handle,
                flags,
                time_ns.unwrap_or(0),
            ))?;
            self.active = false;
            Ok(())
        }
    }

    /// Read samples from the stream into the provided buffers.
    ///
    /// `buffers` contains one destination slice for each channel of this stream.
    ///
    /// Returns the number of samples read, which may be smaller than the size of the passed arrays.
    ///
    /// # Panics
    ///  * If `buffers` is not the same length as the `channels` array passed to `Device::rx_stream`.
    pub fn read(&mut self, buffers: &mut [&mut [E]], timeout_us: i64) -> Result<usize, Error> {
        unsafe {
            assert!(buffers.len() == self.nchannels);

            let num_samples = buffers.iter().map(|b| b.len()).min().unwrap_or(0);

            for (dst, src) in self.buf_ptrs.iter_mut().zip(buffers.iter_mut()) {
                *dst = src.as_mut_ptr();
            }

            self.flags = 0;
            let len = len_result(SoapySDRDevice_readStream(
                self.device.inner.ptr,
                self.handle,
                self.buf_ptrs.as_ptr() as *const *mut _,
                num_samples,
                &mut self.flags as *mut _,
                &mut self.time_ns as *mut _,
                timeout_us as _,
            ))?;

            Ok(len as usize)
        }
    }

    /// Return timestamp of the last successful `read()` operation.
    pub fn time_ns(&self) -> i64 {
        self.time_ns
    }
}

/// A stream open for transmitting.
///
/// To obtain a TxStream, call [Device::tx_stream]. The type parameter `E` represents the type
/// of this stream's samples.
///
/// Streams may involve multiple channels.
pub struct TxStream<E: StreamSample> {
    device: Device,
    handle: *mut SoapySDRStream,
    nchannels: usize,
    active: bool,
    buf_ptrs: Vec<*const E>,
    phantom: PhantomData<fn(&[E])>,
}

/// Streams may only be used on one thread at a time but may be sent between threads
unsafe impl<E: StreamSample> Send for TxStream<E> {}

impl<E: StreamSample> Drop for TxStream<E> {
    fn drop(&mut self) {
        unsafe {
            if self.active {
                self.deactivate(None).ok();
            }
            SoapySDRDevice_closeStream(self.device.inner.ptr, self.handle);
        }
    }
}

impl<E: StreamSample> TxStream<E> {
    /// Get the stream's maximum transmission unit (MTU) in number of elements.
    ///
    /// The MTU specifies the maximum payload transfer in a stream operation.
    /// This value can be used as a stream buffer allocation size that can
    /// best optimize throughput given the underlying stream implementation.
    pub fn mtu(&self) -> Result<usize, Error> {
        unsafe {
            check_error(SoapySDRDevice_getStreamMTU(
                self.device.inner.ptr,
                self.handle,
            ))
        }
    }

    /// Activate a stream.
    ///
    /// Call `activate` to enable a stream before using `write()`
    ///
    /// # Arguments:
    ///   * `time_ns` -- optional activation time in nanoseconds
    pub fn activate(&mut self, time_ns: Option<i64>) -> Result<(), Error> {
        if self.active {
            return Err(Error {
                code: ErrorCode::Other,
                message: "Stream is already active".into(),
            });
        }
        unsafe {
            let flags = if time_ns.is_some() {
                SOAPY_SDR_HAS_TIME as i32
            } else {
                0
            };
            check_ret_error(SoapySDRDevice_activateStream(
                self.device.inner.ptr,
                self.handle,
                flags,
                time_ns.unwrap_or(0),
                0,
            ))?;
            self.active = true;
            Ok(())
        }
    }

    /// Fetch the active state of the stream.
    pub fn active(&self) -> bool {
        self.active
    }

    /// Deactivate a stream.
    /// The implementation will control switches or halt data flow.
    ///
    /// # Arguments:
    ///   * `time_ns` -- optional deactivation time in nanoseconds
    pub fn deactivate(&mut self, time_ns: Option<i64>) -> Result<(), Error> {
        if !self.active {
            return Err(Error {
                code: ErrorCode::Other,
                message: "Stream is not active".into(),
            });
        }
        unsafe {
            let flags = if time_ns.is_some() {
                SOAPY_SDR_HAS_TIME as i32
            } else {
                0
            };
            check_ret_error(SoapySDRDevice_deactivateStream(
                self.device.inner.ptr,
                self.handle,
                flags,
                time_ns.unwrap_or(0),
            ))?;
            self.active = false;
            Ok(())
        }
    }

    /// Attempt to write samples to the device from the provided buffer.
    ///
    /// The stream must first be [activated](TxStream::activate).
    ///
    /// `buffers` contains one source slice for each channel of the stream.
    ///
    /// `at_ns` is an optional nanosecond precision device timestamp at which
    /// the device is to begin the transmission (c.f. [get_hardware_time](Device::get_hardware_time)).
    ///
    /// `end_burst` indicates when this packet ends a burst transmission.
    ///
    /// Returns the number of samples written, which may be smaller than the size of the passed arrays.
    ///
    /// # Panics
    ///  * If `buffers` is not the same length as the `channels` array passed to `Device::tx_stream`.
    ///  * If all the buffers in `buffers` are not the same length.
    pub fn write(
        &mut self,
        buffers: &[&[E]],
        at_ns: Option<i64>,
        end_burst: bool,
        timeout_us: i64,
    ) -> Result<usize, Error> {
        unsafe {
            assert!(
                buffers.len() == self.nchannels,
                "Number of buffers must equal number of channels on stream"
            );

            let num_elems = buffers.first().map_or(0, |x| x.len());
            for (dst, src) in self.buf_ptrs.iter_mut().zip(buffers) {
                assert_eq!(src.len(), num_elems, "All buffers must be the same length");
                *dst = src.as_ptr();
            }

            let mut flags = 0;

            if at_ns.is_some() {
                flags |= SOAPY_SDR_HAS_TIME as i32;
            }

            if end_burst {
                flags |= SOAPY_SDR_END_BURST as i32;
            }

            let len = len_result(SoapySDRDevice_writeStream(
                self.device.inner.ptr,
                self.handle,
                self.buf_ptrs.as_ptr() as *const *const _,
                num_elems,
                &mut flags as *mut _,
                at_ns.unwrap_or(0),
                timeout_us as _,
            ))?;

            Ok(len as usize)
        }
    }

    /// Write all samples to the device.
    ///
    /// This method repeatedly calls [write](TxStream::write) until the entire provided buffer has
    /// been written.
    ///
    /// The stream must first be [activated](TxStream::activate).
    ///
    /// `buffers` contains one source slice for each channel of the stream.
    ///
    /// `at_ns` is an optional nanosecond precision device timestamp at which
    /// the device is to begin the transmission (c.f. [get_hardware_time](Device::get_hardware_time)).
    ///
    /// `end_burst` indicates when this packet ends a burst transmission.
    ///
    /// # Panics
    ///  * If `buffers` is not the same length as the `channels` array passed to `Device::rx_stream`.
    ///  * If all the buffers in `buffers` are not the same length.
    pub fn write_all(
        &mut self,
        buffers: &[&[E]],
        at_ns: Option<i64>,
        end_burst: bool,
        timeout_us: i64,
    ) -> Result<(), Error> {
        let mut buffers = buffers.to_owned();
        let mut at_ns = at_ns;

        while buffers.first().map_or(0, |x| x.len()) > 0 {
            // The timestamp is only sent on the first write.
            let written = self.write(&buffers, at_ns.take(), end_burst, timeout_us)?;

            // Advance the buffer pointers
            for buf in &mut buffers {
                *buf = &buf[written..];
            }
        }

        Ok(())
    }

    /// Read the status of the stream.
    ///
    /// This is required to detect underflows and such as they are not reported by
    /// [write](TxStream::write).
    ///
    /// `chan_mask``, `flags``, and `time_ns`` are output parameters and _may_ be
    /// set depending on the type of status result.
    ///
    /// Returns the status `Result`, usually this will be an [Error], as would be
    /// returned from a stream read/write.
    ///
    /// [ErrorCode::Timeout] should generally be ignored.
    ///
    /// Note that `timeout_us` is only `i32` on Windows and panics if the value is
    /// too large for `i32` on that platform.
    pub fn read_status(
        &mut self,
        chan_mask: &mut usize,
        flags: &mut i32,
        time_ns: &mut i64,
        timeout_us: i64,
    ) -> Result<usize, Error> {
        // Conversion needed for Windows, which takes an i32 here for some reason.
        #[allow(clippy::useless_conversion)]
        let timeout_us = timeout_us.try_into().unwrap();
        unsafe {
            let status = len_result(SoapySDRDevice_readStreamStatus(
                self.device.inner.ptr,
                self.handle,
                chan_mask,
                flags,
                time_ns,
                timeout_us,
            ))?;

            Ok(status as usize)
        }
    }

    // TODO: DMA
}