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
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
|
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License, Version 1.0 only
# (the "License"). You may not use this file except in compliance
# with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
#
# Copyright 2004 Sun Microsystems, Inc. All rights reserved.
# Use is subject to license terms.
#
# Copyright 2019 RackTop Systems.
#
# Makefile for cmd/audio/audioconvert
PROG= audioconvert
include ../../Makefile.cmd
INCLUDES += -I../include -I.
CPPFLAGS += $(INCLUDES)
PROGSRCS= convert.cc file.cc main.cc parse.cc
OBJS= $(PROGSRCS:%.cc=%.o)
LDLIBS += -laudio -lm -lc
LDFLAGS += -L../utilities
CCERRWARN += -Wno-switch
CCERRWARN += -Wno-parentheses
CCERRWARN += -Wno-ignored-qualifiers
CCERRWARN += -Wno-return-type
.PARALLEL: $(OBJS)
.KEEP_STATE:
all: $(PROG)
install: all .WAIT $(ROOTPROG)
_msg:
$(PROG): $(OBJS)
$(LINK.cc) $(OBJS) -o $@ $(LDLIBS)
$(POST_PROCESS)
clean:
$(RM) $(OBJS)
clobber: clean
$(RM) $(PROG) $(CLOBBERFILES)
lint:
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License, Version 1.0 only
* (the "License"). You may not use this file except in compliance
* with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2004 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <sys/param.h>
#include <Audio.h>
#include <AudioFile.h>
#include <AudioPipe.h>
#include <AudioRawPipe.h>
#include <AudioLib.h>
#include <AudioTypePcm.h>
#include <AudioTypeG72X.h>
#include <AudioTypeChannel.h>
#include <AudioTypeMux.h>
#include <AudioTypeSampleRate.h>
#include <convert.h>
// Maximum sizes of buffer to convert, in seconds and bytes
#define CVTMAXTIME ((double)5.0)
#define CVTMAXBUF (64 * 1024)
// maintain a list of conversions
struct conv_list {
struct conv_list *next; // next conversion in chain
unsigned bufcnt; // number of buffers to process
AudioTypeConvert* conv; // conversion class
AudioHdr hdr; // what to convert to
char *desc; // describe conversion (for errs)
};
// check if this is a valid conversion. return -1 if not, 0 if OK.
int
verify_conversion(
AudioHdr ihdr,
AudioHdr ohdr)
{
char *enc1;
char *enc2;
if (((ihdr.encoding != ULAW) &&
(ihdr.encoding != ALAW) &&
(ihdr.encoding != LINEAR) &&
(ihdr.encoding != FLOAT) &&
(ihdr.encoding != G721) &&
(ihdr.encoding != G723)) ||
((ohdr.encoding != ULAW) &&
(ohdr.encoding != ALAW) &&
(ohdr.encoding != LINEAR) &&
(ohdr.encoding != FLOAT) &&
(ohdr.encoding != G721) &&
(ohdr.encoding != G723))) {
enc1 = ihdr.EncodingString();
enc2 = ohdr.EncodingString();
Err(MGET("can't convert from %s to %s\n"), enc1, enc2);
delete enc1;
delete enc2;
return (-1);
}
return (0);
}
// check if this conversion is a no-op
int
noop_conversion(
AudioHdr ihdr,
AudioHdr ohdr,
format_type i_fmt,
format_type o_fmt,
off_t i_offset,
off_t /* o_offset */)
{
if ((ihdr == ohdr) &&
(i_fmt == o_fmt) &&
(i_offset == 0)) {
return (1);
}
return (0);
}
// Conversion list maintenance routines
// Return a pointer to the last conversion entry in the list
struct conv_list
*get_last_conv(
struct conv_list *list)
{
struct conv_list *lp;
for (lp = list; lp != NULL; lp = lp->next) {
if (lp->next == NULL)
break;
}
return (lp);
}
// Release the conversion list
void
free_conv_list(
struct conv_list *&list)
{
unsigned int i;
unsigned int bufs;
struct conv_list *tlp;
AudioTypeConvert* conv;
while (list != NULL) {
bufs = list->bufcnt;
conv = list->conv;
for (i = 0; i < bufs; i++) {
// Delete the conversion string
if (list[i].desc != NULL)
free(list[i].desc);
// Delete the conversion class if unique
if ((list[i].conv != NULL) &&
((i == 0) || (list[i].conv != conv)))
delete(list[i].conv);
}
tlp = list->next;
free((char *)list);
list = tlp;
}
}
// Append a new entry on the end of the conversion list
void
append_conv_list(
struct conv_list *&list, // list to modify
AudioHdr tohdr, // target format
unsigned int bufs, // number of buffers involved
AudioTypeConvert* conv, // NULL, if multiple buffers
char *desc) // string describing the transform
{
unsigned int i;
struct conv_list *lp;
struct conv_list *nlp;
Boolean B;
nlp = new struct conv_list[bufs];
if (nlp == NULL) {
Err(MGET("out of memory\n"));
exit(1);
}
B = tohdr.Validate();
// Initialize a conversion entry for each expected buffer
for (i = 0; i < bufs; i++) {
nlp[i].next = NULL;
nlp[i].hdr = tohdr;
B = nlp[i].hdr.Validate();
nlp[i].bufcnt = bufs;
nlp[i].conv = conv;
if (desc && *desc) {
nlp[i].desc = strdup(desc);
} else {
nlp[i].desc = NULL;
}
}
// Link in the new entry
if (list == NULL) {
list = nlp;
} else {
lp = get_last_conv(list);
lp->next = nlp;
}
}
// Routines to establish specific conversions.
// These routines append the proper conversion to the list, and update
// the audio header structure to reflect the resulting data format.
// Multiplex/Demultiplex interleaved data
// If the data is multi-channel, demultiplex into multiple buffer streams.
// If there are multiple buffers, multiplex back into one interleaved stream.
AudioError
add_mux_convert(
struct conv_list *&list,
AudioHdr& ihdr,
unsigned int& bufs)
{
AudioTypeConvert* conv;
unsigned int n;
char *msg;
conv = new AudioTypeMux;
// Verify conversion
if (!conv->CanConvert(ihdr)) {
error: delete conv;
return (AUDIO_ERR_FORMATLOCK);
}
if (bufs == 1) {
// Demultiplex multi-channel data
n = ihdr.channels; // save the target number of buffers
ihdr.channels = 1; // each output buffer will be mono
msg = MGET("Split multi-channel data");
} else {
// Multiplex multiple buffers
ihdr.channels = bufs; // set the target interleave
n = 1;
bufs = 1; // just one conversion necessary
msg = MGET("Interleave multi-channel data");
}
if (!conv->CanConvert(ihdr))
goto error;
append_conv_list(list, ihdr, bufs, conv, msg);
bufs = n;
return (AUDIO_SUCCESS);
}
// Convert to PCM (linear, ulaw, alaw)
AudioError
add_pcm_convert(
struct conv_list *&list,
AudioHdr& ihdr,
AudioEncoding tofmt,
unsigned int unitsz,
unsigned int& bufs)
{
AudioTypeConvert* conv;
char msg[BUFSIZ];
char *infmt;
char *outfmt;
AudioError err;
conv = new AudioTypePcm;
// Verify conversion
if (!conv->CanConvert(ihdr)) {
error: delete conv;
return (AUDIO_ERR_FORMATLOCK);
}
// Set up conversion, get encoding strings
infmt = ihdr.EncodingString();
ihdr.encoding = tofmt;
ihdr.bytes_per_unit = unitsz;
ihdr.samples_per_unit = 1;
if (!conv->CanConvert(ihdr))
goto error;
outfmt = ihdr.EncodingString();
sprintf(msg, MGET("Convert %s to %s"), infmt, outfmt);
delete infmt;
delete outfmt;
append_conv_list(list, ihdr, bufs, conv, msg);
return (AUDIO_SUCCESS);
}
// Convert multi-channel data to mono, or vice versa
AudioError
add_channel_convert(
struct conv_list *&list,
AudioHdr& ihdr,
unsigned int tochans,
unsigned int& bufs)
{
AudioTypeConvert* conv;
char msg[BUFSIZ];
char *inchans;
char *outchans;
AudioError err;
// Make sure we're converting to/from mono with an interleaved buffer
if (((ihdr.channels != 1) && (tochans != 1)) || (bufs != 1))
return (AUDIO_ERR_FORMATLOCK);
conv = new AudioTypeChannel;
// Verify conversion; if no good, try converting to 16-bit pcm first
if (!conv->CanConvert(ihdr) || (ihdr.channels != 1)) {
if (err = add_pcm_convert(list, ihdr, LINEAR, 2, bufs)) {
delete conv;
return (err);
}
if (!conv->CanConvert(ihdr)) {
error: delete conv;
return (AUDIO_ERR_FORMATLOCK);
}
}
// Set up conversion, get channel strings
inchans = ihdr.ChannelString();
ihdr.channels = tochans;
if (!conv->CanConvert(ihdr))
goto error;
outchans = ihdr.ChannelString();
sprintf(msg, MGET("Convert %s to %s"), inchans, outchans);
delete inchans;
delete outchans;
append_conv_list(list, ihdr, bufs, conv, msg);
return (AUDIO_SUCCESS);
}
// Compress data
AudioError
add_compress(
struct conv_list *&list,
AudioHdr& ihdr,
AudioEncoding tofmt,
unsigned int unitsz,
unsigned int& bufs)
{
AudioTypeConvert* conv;
char msg[BUFSIZ];
char *infmt;
char *outfmt;
struct conv_list *lp;
int i;
AudioError err;
// Make sure we're converting something we understand
if ((tofmt != G721) && (tofmt != G723))
return (AUDIO_ERR_FORMATLOCK);
conv = new AudioTypeG72X;
// Verify conversion; if no good, try converting to 16-bit pcm first
if (!conv->CanConvert(ihdr)) {
if (err = add_pcm_convert(list, ihdr, LINEAR, 2, bufs)) {
delete conv;
return (err);
}
if (!conv->CanConvert(ihdr)) {
error: delete conv;
return (AUDIO_ERR_FORMATLOCK);
}
}
// Set up conversion, get encoding strings
infmt = ihdr.EncodingString();
ihdr.encoding = tofmt;
switch (tofmt) {
case G721:
ihdr.bytes_per_unit = unitsz;
ihdr.samples_per_unit = 2;
break;
case G723:
ihdr.bytes_per_unit = unitsz;
ihdr.samples_per_unit = 8;
break;
}
if (!conv->CanConvert(ihdr))
goto error;
outfmt = ihdr.EncodingString();
sprintf(msg, MGET("Convert %s to %s"), infmt, outfmt);
delete infmt;
delete outfmt;
append_conv_list(list, ihdr, bufs, NULL, msg);
// Need a separate converter instantiation for each channel
lp = get_last_conv(list);
for (i = 0; i < bufs; i++) {
if (i == 0)
lp[i].conv = conv;
else
lp[i].conv = new AudioTypeG72X;
}
return (AUDIO_SUCCESS);
}
// Decompress data
AudioError
add_decompress(
struct conv_list *&list,
AudioHdr& ihdr,
AudioEncoding tofmt,
unsigned int unitsz,
unsigned int& bufs)
{
AudioTypeConvert* conv;
char msg[BUFSIZ];
char *infmt;
char *outfmt;
struct conv_list *lp;
int i;
AudioError err;
// Make sure we're converting something we understand
if ((ihdr.encoding != G721) && (ihdr.encoding != G723))
return (AUDIO_ERR_FORMATLOCK);
conv = new AudioTypeG72X;
// Verify conversion
if (!conv->CanConvert(ihdr)) {
error: delete conv;
return (AUDIO_ERR_FORMATLOCK);
}
// Set up conversion, get encoding strings
infmt = ihdr.EncodingString();
ihdr.encoding = tofmt;
ihdr.bytes_per_unit = unitsz;
ihdr.samples_per_unit = 1;
if (!conv->CanConvert(ihdr)) {
// Try converting to 16-bit linear
ihdr.encoding = LINEAR;
ihdr.bytes_per_unit = 2;
if (!conv->CanConvert(ihdr))
goto error;
}
outfmt = ihdr.EncodingString();
sprintf(msg, MGET("Convert %s to %s"), infmt, outfmt);
delete infmt;
delete outfmt;
append_conv_list(list, ihdr, bufs, NULL, msg);
// Need a separate converter instantiation for each channel
lp = get_last_conv(list);
for (i = 0; i < bufs; i++) {
if (i == 0)
lp[i].conv = conv;
else
lp[i].conv = new AudioTypeG72X;
}
return (AUDIO_SUCCESS);
}
// Sample rate conversion
AudioError
add_rate_convert(
struct conv_list *&list,
AudioHdr& ihdr,
unsigned int torate,
unsigned int& bufs)
{
AudioTypeConvert* conv;
unsigned int fromrate;
char msg[BUFSIZ];
char *inrate;
char *outrate;
struct conv_list *lp;
int i;
AudioError err;
fromrate = ihdr.sample_rate;
conv = new AudioTypeSampleRate(fromrate, torate);
// Verify conversion; if no good, try converting to 16-bit pcm first
if (!conv->CanConvert(ihdr)) {
if (err = add_pcm_convert(list, ihdr, LINEAR, 2, bufs)) {
delete conv;
return (err);
}
if (!conv->CanConvert(ihdr)) {
error: delete conv;
return (AUDIO_ERR_FORMATLOCK);
}
}
// Set up conversion, get encoding strings
inrate = ihdr.RateString();
ihdr.sample_rate = torate;
if (!conv->CanConvert(ihdr))
goto error;
outrate = ihdr.RateString();
sprintf(msg, MGET("Convert %s to %s"), inrate, outrate);
delete inrate;
delete outrate;
append_conv_list(list, ihdr, bufs, NULL, msg);
// Need a separate converter instantiation for each channel
lp = get_last_conv(list);
for (i = 0; i < bufs; i++) {
if (i == 0)
lp[i].conv = conv;
else
lp[i].conv = new AudioTypeSampleRate(fromrate, torate);
}
return (AUDIO_SUCCESS);
}
// Returns TRUE if the specified header has a pcm type encoding
Boolean
pcmtype(
AudioHdr& hdr)
{
if (hdr.samples_per_unit != 1)
return (FALSE);
switch (hdr.encoding) {
case LINEAR:
case FLOAT:
case ULAW:
case ALAW:
return (TRUE);
}
return (FALSE);
}
#define IS_PCM(ihp) (pcmtype(ihp))
#define IS_MONO(ihp) (ihp.channels == 1)
#define RATE_CONV(ihp, ohp) (ihp.sample_rate != ohp.sample_rate)
#define ENC_CONV(ihp, ohp) ((ihp.encoding != ohp.encoding) || \
(ihp.samples_per_unit != \
ohp.samples_per_unit) || \
(ihp.bytes_per_unit != ohp.bytes_per_unit))
#define CHAN_CONV(ihp, ohp) (ihp.channels != ohp.channels)
// Build the conversion list to get from input to output format
AudioError
build_conversion_list(
struct conv_list *&list,
AudioStream* ifp,
AudioStream* ofp)
{
AudioHdr ihdr;
AudioHdr ohdr;
unsigned int bufs;
AudioError err;
ihdr = ifp->GetHeader();
ohdr = ofp->GetHeader();
bufs = 1;
// Each pass, add another conversion, until there's no more to do
while (((ihdr != ohdr) || (bufs != 1)) && !err) {
// First off, if the target is mono, convert the source to mono
// before doing harder stuff, like sample rate conversion.
if (IS_MONO(ohdr)) {
if (!IS_MONO(ihdr)) {
if (IS_PCM(ihdr)) {
// If multi-channel pcm,
// mix the channels down to one
err = add_channel_convert(list,
ihdr, 1, bufs);
} else {
// If not pcm, demultiplex in order
// to decompress
err = add_mux_convert(list, ihdr, bufs);
}
continue;
} else if (bufs != 1) {
// Multi-channel data was demultiplexed
if (IS_PCM(ihdr)) {
// If multi-channel pcm, recombine them
// for mixing down to one
err = add_mux_convert(list, ihdr, bufs);
} else {
// If not pcm, decompress it
err = add_decompress(list, ihdr,
ohdr.encoding, ohdr.bytes_per_unit,
bufs);
}
continue;
}
// At this point, input and output are both mono
} else if (ihdr.channels != 1) {
// Here if input and output are both multi-channel.
// If sample rate conversion or compression,
// split into multiple streams
if (RATE_CONV(ihdr, ohdr) ||
(ENC_CONV(ihdr, ohdr) &&
(!IS_PCM(ihdr) || !IS_PCM(ohdr)))) {
err = add_mux_convert(list, ihdr, bufs);
continue;
}
}
// Input is either mono, split into multiple buffers, or
// this is a conversion that can be handled multi-channel.
if (RATE_CONV(ihdr, ohdr)) {
// Decompress before sample-rate conversion
if (!IS_PCM(ihdr)) {
err = add_decompress(list, ihdr,
ohdr.encoding, ohdr.bytes_per_unit,
bufs);
} else {
err = add_rate_convert(list, ihdr,
ohdr.sample_rate, bufs);
}
continue;
}
if (ENC_CONV(ihdr, ohdr)) {
// Encoding is changing:
if (!IS_PCM(ihdr)) {
// if we start compressed, decompress
err = add_decompress(list, ihdr,
ohdr.encoding, ohdr.bytes_per_unit,
bufs);
} else if (IS_PCM(ohdr)) {
// we should be able to convert to PCM now
err = add_pcm_convert(list, ihdr,
ohdr.encoding, ohdr.bytes_per_unit,
bufs);
} else {
// we should be able to compress now
err = add_compress(list, ihdr,
ohdr.encoding, ohdr.bytes_per_unit,
bufs);
}
continue;
}
// The sample rate and encoding match.
// All that's left to do is get the channels right
if (bufs > 1) {
// Combine channels back into an interleaved stream
err = add_mux_convert(list, ihdr, bufs);
continue;
}
if (!IS_MONO(ohdr)) {
// If multi-channel output, try to accomodate
err = add_channel_convert(list,
ihdr, ohdr.channels, bufs);
continue;
}
// Everything should be done at this point.
// XXX - this should never be reached
return (AUDIO_ERR_FORMATLOCK);
}
return (err);
}
// Set up the conversion list and execute it
int
do_convert(
AudioStream* ifp,
AudioStream* ofp)
{
struct conv_list *list = NULL;
struct conv_list *lp;
AudioBuffer* obuf;
AudioBuffer** multibuf;
AudioError err;
AudioHdr ihdr;
AudioHdr ohdr;
Double pos = 0.0;
size_t len;
unsigned int i;
Double cvtlen;
char *msg1;
char *msg2;
ihdr = ifp->GetHeader();
ohdr = ofp->GetHeader();
// create conversion list
if ((err = build_conversion_list(list, ifp, ofp)) != AUDIO_SUCCESS) {
free_conv_list(list);
msg1 = ohdr.FormatString();
Err(MGET("Cannot convert %s to %s\n"), ifp->GetName(), msg1);
delete msg1;
return (-1);
}
// Print warnings for exceptional conditions
if ((ohdr.sample_rate < 8000) || (ohdr.sample_rate > 48000)) {
msg1 = ohdr.RateString();
Err(MGET("Warning: converting %s to %s\n"),
ifp->GetName(), msg1);
delete msg1;
}
if (ohdr.channels > 2) {
msg1 = ohdr.ChannelString();
Err(MGET("Warning: converting %s to %s\n"),
ifp->GetName(), msg1);
delete msg1;
}
if (Debug) {
msg1 = ihdr.FormatString();
msg2 = ohdr.FormatString();
Err(MGET("Converting %s:\n\t\tfrom: %s\n\t\tto: %s\n"),
ifp->GetName(), msg1, msg2);
delete msg1;
delete msg2;
// Print each entry in the conversion list
for (lp = list; lp; lp = lp->next) {
(void) fprintf(stderr, MGET("\t%s %s\n"), lp->desc,
(lp->bufcnt == 1) ? "" : MGET("(multi-channel)"));
}
}
// Calculate buffer size, obeying maximums
cvtlen = ihdr.Bytes_to_Time(CVTMAXBUF);
if (cvtlen > CVTMAXTIME)
cvtlen = CVTMAXTIME;
if (cvtlen > ohdr.Bytes_to_Time(CVTMAXBUF * 4))
cvtlen = ohdr.Bytes_to_Time(CVTMAXBUF * 4);
// create output buf
if (!(obuf = new AudioBuffer(cvtlen, MGET("Audio Convert Buffer")))) {
Err(MGET("Can't create conversion buffer\n"));
exit(1);
}
while (1) {
// Reset length
len = (size_t)ihdr.Time_to_Bytes(cvtlen);
if ((err = obuf->SetHeader(ihdr)) != AUDIO_SUCCESS) {
Err(MGET("Can't set buffer header: %s\n"), err.msg());
return (-1);
}
// If growing buffer, free the old one rather than copy data
if (obuf->GetSize() < cvtlen)
obuf->SetSize(0.);
obuf->SetSize(cvtlen);
// Read a chunk of input and set the real length of buffer
// XXX - Use Copy() method?? Check for errors?
if (err = ifp->ReadData(obuf->GetAddress(), len, pos))
break;
obuf->SetLength(ihdr.Bytes_to_Time(len));
// Process each entry in the conversion list
for (lp = list; lp; lp = lp->next) {
if (lp->conv) {
// If multiple buffers, make multiple calls
if (lp->bufcnt == 1) {
err = lp->conv->Convert(obuf, lp->hdr);
} else {
multibuf = (AudioBuffer**)obuf;
for (i = 0; i < lp->bufcnt; i++) {
err = lp[i].conv->Convert(
multibuf[i], lp[i].hdr);
if (err)
break;
}
}
if (err) {
Err(MGET(
"Conversion failed: %s (%s)\n"),
lp->desc ? lp->desc : MGET("???"),
err.msg());
return (-1);
}
}
}
if ((err = write_output(obuf, ofp)) != AUDIO_SUCCESS) {
Err(MGET("Error writing to output file %s (%s)\n"),
ofp->GetName(), err.msg());
return (-1);
}
}
// Now flush any left overs from conversions w/state
obuf->SetLength(0.0);
for (lp = list; lp; lp = lp->next) {
if (lp->conv) {
// First check if there's any residual to convert.
// If not, just set the header to this type.
// If multiple buffers, make multiple calls
if (lp->bufcnt == 1) {
err = lp->conv->Convert(obuf, lp->hdr);
if (!err)
err = lp->conv->Flush(obuf);
} else {
multibuf = (AudioBuffer**)obuf;
for (i = 0; i < lp->bufcnt; i++) {
err = lp[i].conv->Convert(
multibuf[i], lp[i].hdr);
if (!err) {
err = lp[i].conv->Flush(
multibuf[i]);
}
if (err)
break;
}
}
if (err) {
Err(MGET(
"Warning: Flush of final bytes failed: "
"%s (%s)\n"),
lp->desc ? lp->desc : MGET("???"),
err.msg());
/* return (-1); ignore errors for now */
break;
}
}
}
if (obuf->GetLength() > 0.0) {
if ((err = write_output(obuf, ofp)) != AUDIO_SUCCESS) {
Err(MGET("Warning: Final write to %s failed (%s)\n"),
ofp->GetName(), err.msg());
/* return (-1); ignore errors for now */
}
}
delete obuf;
free_conv_list(list);
return (0);
}
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License, Version 1.0 only
* (the "License"). You may not use this file except in compliance
* with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 1993-2001 by Sun Microsystems, Inc.
* All rights reserved.
*/
#ifndef _AUDIOCONVERT_CONVERT_H
#define _AUDIOCONVERT_CONVERT_H
#include <audio_i18n.h>
#include <Audio.h>
#include <AudioUnixfile.h>
#include <AudioBuffer.h>
#include <AudioTypeConvert.h>
#include <parse.h>
#ifdef __cplusplus
extern "C" {
#endif
// for localizing strings
#define MGET(str) (char *)gettext(str)
extern int Statistics; // report timing statistics
extern int Debug; // Debug flag
extern AudioBuffer* create_buffer(Audio*);
extern void get_realfile(char *&, struct stat *);
extern AudioUnixfile* open_input_file(const char *, const AudioHdr,
int, int, off_t, format_type&);
extern AudioUnixfile* create_output_file(const char *, const AudioHdr,
format_type, const char *infoString);
extern int verify_conversion(AudioHdr, AudioHdr);
extern int do_convert(AudioStream*, AudioStream*);
extern AudioError write_output(AudioBuffer*, AudioStream*);
extern int noop_conversion(AudioHdr, AudioHdr,
format_type, format_type, off_t, off_t);
extern void Err(char *, ...);
#ifdef __cplusplus
}
#endif
#endif /* !_AUDIOCONVERT_CONVERT_H */
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License, Version 1.0 only
* (the "License"). You may not use this file except in compliance
* with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 1993-2003 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <sys/param.h>
#include <Audio.h>
#include <AudioFile.h>
#include <AudioPipe.h>
#include <AudioRawPipe.h>
#include <AudioLib.h>
#include <AudioHdr.h>
#include <libaudio.h>
#include <audio/au.h>
extern char *Stdin;
extern char *Stdout;
#include <convert.h>
// append contents of buffer to output audio stream.
AudioError
write_output(AudioBuffer* buf, AudioStream* ofp)
{
unsigned char *cp;
size_t len;
Double pos;
AudioError err;
pos = ofp->GetLength();
len = (size_t)buf->GetHeader().Time_to_Bytes(buf->GetLength());
cp = (unsigned char *)buf->GetAddress();
err = ofp->WriteData(cp, len, pos);
return (err);
}
// open input file and return ptr to AudioUnixFile object
// path is the path to the file (or set to Stdin if standard input).
// ihdr is the input header (only used for openning raw files)
// israw flags if it's a raw file. if fflag is set, ignore an
// any existing header on raw files. offset indicates where to
// start reading the file (raw files only ??).
AudioUnixfile *open_input_file(const char *path, const AudioHdr ihdr,
int israw, int fflag, off_t offset,
format_type& fmt)
{
AudioUnixfile* ifp;
int fd;
int file_type; // ignore this ...
int infosize; // ignore this ...
au_filehdr_t fhdr;
Audio_hdr ohdr; // ignore this ...
unsigned int hsize;
// need to let caller know what format this is. so far, only raw
// and sun are supported....
fmt = (israw ? F_RAW : F_SUN);
// no file
if (!path) {
// no file? shouldn't happen. bomb out.
Err(MGET("no input file specified\n"));
exit(1);
}
// deal with stdin
if (path == Stdin) {
if (isatty(fileno(stdin))) {
Err(MGET(
"Stdin is a tty, please specify an input file\n"));
exit(1);
}
if (israw) {
// XXX - need to check if stdin has a file
// header and ignore it if fflag not set.
ifp = new AudioRawPipe(fileno(stdin),
(FileAccess)ReadOnly, ihdr, path,
offset);
} else {
ifp = new AudioPipe(fileno(stdin), (FileAccess)ReadOnly,
path);
}
if (!ifp) {
Err(MGET("can't open pipe to %s, skipping...\n"),
Stdin);
}
return (ifp);
}
// fall through for real files ...
if (israw) {
if ((fd = open(path, O_RDONLY)) < 0) {
Err(MGET("can't open %s, skipping...\n"), path);
perror(MGET("open"));
return (NULL);
}
if (!fflag) {
// check if file already has a hdr.
if (hsize = read(fd, (char *)&fhdr, sizeof (fhdr))
< 0) {
perror("read");
exit(1);
}
if (lseek(fd, 0, 0) < 0) { // reset
perror("lseek");
exit(1);
}
if (hsize != sizeof (fhdr)) {
// no hdr - file too small,
// assume data is ok (tho it
// probably won't be) ...
ifp = new AudioRawPipe(fd, (FileAccess)ReadOnly,
ihdr, path, offset);
} else {
// Check the validity of the
// header and get the size of
// the info field
if (audio_decode_filehdr(fd,
(unsigned char *)&fhdr, &file_type, &ohdr,
&infosize) == AUDIO_SUCCESS) {
close(fd); // create AudioFile()
// issue a warning
Err(
MGET("%s has a file header, ignoring -i ...\n"),
path);
fmt = F_SUN; // was raw ...
ifp = new AudioFile(path,
(FileAccess)ReadOnly);
} else {
// no hdr, create AudioRawPipe.
ifp = new AudioRawPipe(fd,
(FileAccess)ReadOnly, ihdr,
path, offset);
}
}
} else { // force flag - don't even look for header
ifp = new AudioRawPipe(fd, (FileAccess)ReadOnly, ihdr,
path, offset);
}
} else {
ifp = new AudioFile(path, (FileAccess)ReadOnly);
}
if (!ifp) {
Err(MGET("can't open %s, skipping...\n"), path);
}
return (ifp);
}
// given a path, find the file it really points to (if it's a
// sym-link). return it's stat buf and real path.
void
get_realfile(char *&path, struct stat *st)
{
static char tmpf[MAXPATHLEN]; // for reading sym-link
int err; // for stat err
// first see if it's a sym-link and find real file
err = 0;
while (err == 0) {
if (err = lstat(path, st) < 0) {
perror("lstat");
exit(1);
}
if (!err && S_ISLNK(st->st_mode)) {
err = readlink(path, tmpf,
(sizeof (tmpf) - 1));
if (err > 0) {
tmpf[err] = '\0';
path = tmpf;
err = 0;
}
} else {
break;
}
}
}
// create output audio file. if no path is supplied, use stdout.
// returns a ptr to an AudioUnixFile object.
AudioUnixfile*
create_output_file(
const char *path,
const AudioHdr ohdr,
format_type ofmt,
const char *infoString)
{
AudioUnixfile* ofp = 0;
AudioError err; // for error msgs
int fd;
if (!path) {
if (isatty(fileno(stdout))) {
Err(
MGET("Stdout is a tty, please specify an output file\n"));
exit(1);
}
path = Stdout;
if (ofmt == F_RAW) {
if (!(ofp = new AudioRawPipe(fileno(stdout),
(FileAccess)WriteOnly, ohdr,
path))) {
Err(
MGET("can't create audio raw stdout pipe\n"));
exit(1);
}
} else if (ofmt == F_SUN) {
if (!(ofp = new AudioPipe(fileno(stdout),
(FileAccess)WriteOnly, path))) {
Err(
MGET("can't create audio pipe for stdout\n"));
exit(1);
}
} else {
// XXX - should never happen ...
Err(MGET("can't create output file, unknown format\n"));
exit(1);
}
} else {
if (ofmt == F_RAW) {
// first open file, then attach pipe to it
if ((fd = open(path, O_WRONLY|O_CREAT|O_TRUNC,
0666)) < 0) {
perror(MGET("open"));
Err(MGET("can't create output file %s\n"),
path);
exit(1);
}
if (!(ofp = new AudioRawPipe(fd, (FileAccess)WriteOnly,
ohdr, path))) {
Err(MGET("can't create raw audio pipe %s\n"),
path);
exit(1);
}
} else if (ofmt == F_SUN) {
if (!(ofp = new AudioFile(path,
(FileAccess)ReadWrite))) {
Err(MGET("can't create output file %s\n"),
path);
exit(1);
}
} else {
// XXX - should never happen ...
Err(MGET("can't create output file, unknown format\n"));
exit(1);
}
}
// set the info string.
ofp->SetInfostring(infoString, -1);
// set the header and create the output audio object
if ((err = ofp->SetHeader(ohdr)) != AUDIO_SUCCESS) {
Err(MGET("can't set hdr on output file: %s\n"), err.msg());
exit(1);
}
if ((err = ofp->Create()) != AUDIO_SUCCESS) {
Err(MGET("can't create output file: %s\n"), err.msg());
exit(1);
}
return (ofp);
}
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License, Version 1.0 only
* (the "License"). You may not use this file except in compliance
* with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 1993-2001 by Sun Microsystems, Inc.
* All rights reserved.
*/
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <sys/param.h>
#include <convert.h>
#if !defined(TEXT_DOMAIN) /* Should be defined by cc -D */
#define TEXT_DOMAIN "SYS_TEST" /* Use this only if it weren't */
#endif
const char *opt_string = "pf:o:i:FTD?";
char *Stdin;
char *Stdout;
char *Suffix = (char *)".AUDCVTMP";
char *progname; // program name
char *fake_argv[] = {(char *)"-", NULL}; // stdin with no args
extern char *optarg;
extern int optind;
int Statistics = 0;
int Debug = 0;
void init_header(AudioHdr&);
void usage();
int
main(int argc, char *argv[])
{
AudioUnixfile* ifp = NULL; // input & output audio objects
AudioUnixfile* ofp = NULL;
AudioHdr ihdr; // input/output headers
AudioHdr ohdr;
char *infile = NULL; // input/output file names
char *outfile = NULL;
char *realfile = NULL;
char *out_fmt = NULL; // output fmt string
AudioError err; // for error msgs
int c; // for getopt
int pflag = 0; // in place flag
int fflag = 0; // ignore header (force conversion)
int stdin_seen = 0; // already read stdin
int israw = 0; // once we've seen -i, it's raw data
format_type ofmt = F_SUN; // output format type
format_type ifmt = F_SUN; // expected input format type
format_type fmt = F_SUN; // actual input format type
off_t o_offset = 0; // output offset (ignored)
off_t i_offset = 0; // input offset
int i;
struct stat st;
setlocale(LC_ALL, "");
(void) textdomain(TEXT_DOMAIN);
// basename of program
if (progname = strrchr(argv[0], '/')) {
progname++;
} else {
progname = argv[0];
}
Stdin = MGET("(stdin)");
Stdout = MGET("(stdout)");
// init the input & output headers
init_header(ihdr);
init_header(ohdr);
// some conversions depend on invocation name. we'll create
// default input/output formats based on argv[0] that
// can be overridden by -o or -i options.
if (strcmp(progname, "ulaw2pcm") == 0) {
(void) parse_format((char *)"ulaw", ihdr, ifmt, i_offset);
(void) parse_format((char *)"pcm", ohdr, ofmt, o_offset);
} else if (strcmp(progname, "pcm2ulaw") == 0) {
(void) parse_format((char *)"pcm", ihdr, ifmt, i_offset);
(void) parse_format((char *)"ulaw", ohdr, ofmt, o_offset);
} else if (strcmp(progname, "adpcm_enc") == 0) {
(void) parse_format((char *)"ulaw", ihdr, ifmt, i_offset);
(void) parse_format((char *)"g721", ohdr, ofmt, o_offset);
} else if (strcmp(progname, "adpcm_dec") == 0) {
(void) parse_format((char *)"g721", ihdr, ifmt, i_offset);
(void) parse_format((char *)"ulaw", ohdr, ofmt, o_offset);
} else if (strcmp(progname, "raw2audio") == 0) {
(void) parse_format((char *)"ulaw", ihdr, ifmt, i_offset);
(void) parse_format((char *)"ulaw", ohdr, ofmt, o_offset);
israw++;
pflag++;
} else if (argc <= 1) {
// audioconvert with no arguments
usage();
}
// now parse the rest of the arg's
while ((c = getopt(argc, argv, opt_string)) != -1) {
switch (c) {
#ifdef DEBUG
case 'D':
// enable debug messages
Debug++;
break;
#endif
case 'p':
// convert files in place
if (outfile != NULL) {
Err(MGET("can't use -p with -o\n"));
exit(1);
}
pflag++;
break;
case 'F':
// force treatment of audio files as raw files
// (ignore filehdr).
fflag++;
break;
case 'f':
// save format string to parse later, but verify now
out_fmt = optarg;
if (parse_format(out_fmt, ohdr, ofmt, o_offset) == -1)
exit(1);
if (o_offset != 0) {
Err(MGET("can't specify an offset with -f\n"));
exit(1);
}
break;
case 'o':
if (pflag) {
Err(MGET("can't use -o with -p\n"));
exit(1);
}
outfile = optarg;
break;
case 'i':
// if bogus input header, exit ...
if (parse_format(optarg, ihdr, ifmt, i_offset) == -1) {
exit(1);
}
israw++;
break;
default:
case '?':
usage();
}
}
// XXX - should check argument consistency here....
// If no args left, we're taking input from stdin.
// In this case, make argv point to a fake argv with "-" as a file
// name, and set optind and argc apropriately so we'll go through
// the loop below once.
if (optind >= argc) {
argv = fake_argv;
argc = 1;
optind = 0;
/*
* XXX - we turn off pflag if stdin is the only input file.
* this is kind of a hack. if invoked as raw2audio, pflag
* it turned on. if no files are given, we want to turn
* it off, otherwise we'll complain about using -p with
* stdin, which won't make sense if invoked as raw2audio.
* instead, just silently ignore. the message is still given
* and stdin is ignored if it's specified as one of several
* input files.
*/
pflag = 0;
}
// From this point on we're looking at file names or -i args
// for input format specs.
for (; optind < argc; optind++) {
// new input format spec.
if (strcmp(argv[optind], "-i") == 0) {
init_header(ihdr);
i_offset = 0;
ifmt = F_SUN;
// if bogus input header, exit ...
if (parse_format(argv[++optind], ihdr, ifmt, i_offset)
== -1) {
exit(1);
}
israw++;
} else if (strcmp(argv[optind], "-") == 0) {
// ignore stdin argument if in place
if (pflag) {
Err(MGET("can't use %s with -p flag\n"),
Stdin);
continue;
}
if (stdin_seen) {
Err(MGET("already used stdin for input\n"));
continue;
} else {
stdin_seen++;
}
infile = Stdin;
} else {
infile = argv[optind];
}
// if no audio object returned, just continue to the next
// file. if a fatal error occurs, open_input_file()
// will exit the program.
ifp =
open_input_file(infile, ihdr, israw, fflag, i_offset, fmt);
if (!ifp) {
continue;
}
if ((err = ifp->Open()) != AUDIO_SUCCESS) {
Err(MGET("open error on input file %s - %s\n"),
infile, err.msg());
exit(1);
}
ifp->Reference();
// create the output file if not created yet, or if
// converting in place. ofp will be NULL only the first
// time through. use the header of the first input file
// to base the output format on - then create the output
// header w/the output format spec.
if ((ofp == NULL) && !pflag) {
ohdr = ifp->GetHeader();
ohdr = ifp->GetHeader();
ofmt = ifmt;
// just use input hdr if no output hdr spec
if (out_fmt) {
if (parse_format(out_fmt, ohdr, ofmt, o_offset)
== -1) {
exit(1);
}
}
// need to check before output is opened ...
if (verify_conversion(ifp->GetHeader(), ohdr) == -1) {
// XXX - bomb out or skip?
exit(3);
}
// Create the file and set the info string.
char *infoString;
int infoStringLen;
infoString = ifp->GetInfostring(infoStringLen);
ofp = create_output_file(outfile, ohdr, ofmt,
infoString);
} else if (pflag) {
// create new output header based on each input file
ohdr = ifp->GetHeader();
ofmt = ifmt;
// just use input hdr if no output hdr spec
if (out_fmt) {
if (parse_format(out_fmt, ohdr, ofmt, o_offset)
== -1) {
exit(1);
}
}
// get the *real* path of the infile (follow sym-links),
// and the stat info.
realfile = infile;
get_realfile(realfile, &st);
// if the file is read-only, give up
if (access(realfile, W_OK)) {
// XXX - do we really want to exit?
perror(infile);
Err(MGET("cannot rewrite in place\n"));
exit(1);
}
// this is now the output file.
i = strlen(realfile) + strlen(Suffix) + 1;
outfile = (char *)malloc((unsigned)i);
if (outfile == NULL) {
Err(MGET("out of memory\n"));
exit(1);
}
(void) sprintf(outfile, "%s%s", realfile, Suffix);
// outfile will get re-assigned to a tmp file
if (verify_conversion(ifp->GetHeader(), ohdr) == -1) {
// XXX - bomb out or skip?
exit(3);
}
// If no conversion, just skip the file
if (noop_conversion(ifp->GetHeader(), ohdr,
fmt, ofmt, i_offset, o_offset)) {
if (Debug)
Err(MGET(
"%s: no-op conversion...skipping\n"),
infile);
continue;
}
// Get the input info string.
char *infoString;
int infoStringLen;
infoString = ifp->GetInfostring(infoStringLen);
ofp = create_output_file(outfile, ohdr, ofmt,
infoString);
}
// verify that it's a valid conversion by looking at the
// file headers. (this will be called twice for the first
// file if *not* converting in place. that's ok....
if (!pflag && (verify_conversion(ifp->GetHeader(), ohdr)
== -1)) {
// XXX - bomb out or skip file if invalid conversion?
exit(3);
}
// do the conversion, if error, bomb out
if (do_convert(ifp, ofp) == -1) {
exit(4);
}
ifp->Close();
ifp->Dereference();
// if in place, finish up by renaming the outfile to
// back to the infile.
if (pflag) {
delete(ofp); // will close and deref, etc.
if (rename(outfile, realfile) < 0) {
perror(outfile);
Err(MGET("error renaming %s to %s"),
outfile, realfile);
exit(1);
}
/* Set the permissions to match the original */
if (chmod(realfile, (int)st.st_mode) < 0) {
Err(MGET("WARNING: could not reset mode of"));
perror(realfile);
}
}
}
if (!pflag) {
delete(ofp); // close output file
}
return (0);
}
// initialize audio hdr to default val's
void
init_header(
AudioHdr& hdr)
{
hdr.encoding = NONE;
hdr.sample_rate = 0;
hdr.samples_per_unit = 0;
hdr.bytes_per_unit = 0;
hdr.channels = 0;
}
extern "C" { void _doprnt(char *, ...); }
// report a fatal error and exit
void
Err(char *format, ...)
{
va_list ap;
va_start(ap, format);
fprintf(stderr, "%s: ", progname);
_doprnt(format, ap, stderr);
fflush(stderr);
va_end(ap);
}
void
usage()
{
fprintf(stderr, MGET(
"Convert between audio file formats and data encodings -- usage:\n"
"\t%s [-pF] [-f outfmt] [-o outfile] [[-i infmt] [file ...]] ...\n"
"where:\n"
"\t-p\tConvert files in place\n"
"\t-F\tForce interpretation of -i (ignore existing file hdr)\n"
"\t-f\tOutput format description\n"
"\t-o\tOutput file (default: stdout)\n"
"\t-i\tInput format description\n"
"\tfile\tList of files to convert (default: stdin)\n\n"
"Format Description:\n"
"\tkeyword=value[,keyword=value...]\n"
"where:\n"
"\tKeywords:\tValues:\n"
"\trate\t\tSample Rate in samples/second\n"
"\tchannels\tNumber of interleaved channels\n"
"\tencoding\tAudio encoding. One of:\n"
"\t\t\t ulaw, alaw, g721, g723,\n"
"\t\t\t linear8, linear16, linear32\n"
"\t\t\t pcm (same as linear16)\n"
"\t\t\t voice (ulaw,mono,rate=8k)\n"
"\t\t\t cd (linear16,stereo,rate=44.1k)\n"
"\t\t\t dat (linear16,stereo,rate=48k)\n"
"\tformat\t\tFile format. One of:\n"
"\t\t\t sun, raw (no format)\n"
"\toffset\t\tByte offset (raw input only)\n"),
progname);
exit(1);
}
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License, Version 1.0 only
* (the "License"). You may not use this file except in compliance
* with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 1993-2001 by Sun Microsystems, Inc.
* All rights reserved.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <Audio.h>
#include <AudioHdr.h>
#include <parse.h>
#include <convert.h>
static struct keyword_table Keywords[] = {
(char *)"encoding", K_ENCODING,
(char *)"rate", K_RATE,
(char *)"channels", K_CHANNELS,
(char *)"offset", K_OFFSET,
(char *)"format", K_FORMAT,
NULL, K_NULL,
};
// Lookup the string in a keyword table. return the token associated with it.
keyword_type
do_lookup(
char *s,
struct keyword_table *kp)
{
struct keyword_table *tkp = NULL;
for (; kp && kp->name; kp++) {
if (strncmp(s, kp->name, strlen(s)) == 0) {
// check if exact match
if (strlen(s) == strlen(kp->name)) {
return (kp->type);
} else {
// already have another partial match, so
// it's ambiguous
if (tkp) {
return (K_AMBIG);
} else {
tkp = kp;
}
}
}
}
// at end of list. if there was a partial match, return it, if
// not, there's no match....
if (tkp) {
return (tkp->type);
} else {
return (K_NULL);
}
}
// Parse a file format specification
int
fileformat_parse(
char *val,
format_type& format)
{
// XXX - other formats later ...
if (strcasecmp(val, "sun") == 0) {
format = F_SUN;
} else if (strcasecmp(val, "raw") == 0) {
format = F_RAW;
} else if (strcasecmp(val, "aiff") == 0) {
Err(MGET("AIFF not yet supported\n"));
return (-1);
} else {
return (-1);
}
return (0);
}
// Parse an audio format keyword
int
audioformat_parse(
char *val,
AudioHdr& hdr)
{
// check if it's "cd" or "dat" or "voice".
// these set the precision and encoding, etc.
if (strcasecmp(val, "dat") == 0) {
hdr.sample_rate = 48000;
hdr.channels = 2;
hdr.encoding = LINEAR;
hdr.samples_per_unit = 1;
hdr.bytes_per_unit = 2;
} else if (strcasecmp(val, "cd") == 0) {
hdr.sample_rate = 44100;
hdr.channels = 2;
hdr.encoding = LINEAR;
hdr.samples_per_unit = 1;
hdr.bytes_per_unit = 2;
} else if (strcasecmp(val, "voice") == 0) {
hdr.sample_rate = 8000;
hdr.channels = 1;
hdr.encoding = ULAW;
hdr.samples_per_unit = 1;
hdr.bytes_per_unit = 1;
} else {
return (-1);
}
return (0);
}
// Parse a format spec and return an audio header that describes it.
// Format is in the form of: [keyword=]value[,[keyword=]value ...].
int
parse_format(
char *s,
AudioHdr& hdr,
format_type& format,
off_t& offset)
{
char *cp;
char *buf;
char *key;
char *val;
char *cp2;
offset = 0;
format = F_SUN;
// if no string provided, just return ...
if (!(s && *s))
return (0);
// First off, try to parse it as a full format string
// (it would have to have been quoted).
// If this works, we're done.
if (hdr.FormatParse(s) == AUDIO_SUCCESS) {
return (0);
}
buf = strdup(s); // save a copy of the string
// XXX - bug alert: if someone has info="xxx,yyy", strtok will
// break unless we snarf properly snarf the info. punt for now,
// fix later (since no info supported yet)....
for (cp = strtok(buf, ","); cp; cp = strtok(NULL, ",")) {
// Check if there's a '='
// If so, left side is keyword, right side is value.
// If not, entire string is value.
if (cp2 = strchr(cp, '=')) {
*cp2++ = '\0';
key = cp;
val = cp2;
// Look for the keyword
switch (do_lookup(key, Keywords)) {
case K_ENCODING:
if (hdr.EncodingParse(val)) {
Err(MGET(
"invalid encoding option: %s\n"),
val);
goto parse_error;
}
break;
case K_RATE:
if (hdr.RateParse(val)) {
Err(MGET("invalid sample rate: %s\n"),
val);
goto parse_error;
}
break;
case K_CHANNELS:
if (hdr.ChannelParse(val)) {
Err(MGET(
"invalid channels option: %s\n"),
val);
goto parse_error;
}
break;
case K_FORMAT:
if (fileformat_parse(val, format) < 0) {
Err(MGET("unknown format: %s\n"), val);
goto parse_error;
}
break;
case K_OFFSET:
offset = (off_t)atoi(val);
break;
case K_AMBIG:
Err(MGET("ambiguous keyword: %s\n"), key);
goto parse_error;
case K_NULL:
Err(MGET("null keyword: =%s\n"), val);
goto parse_error;
default:
Err(MGET("invalid keyword: %s\n"), key);
goto parse_error;
}
} else {
// No keyword, so try to intuit the value
// First try encoding, audio, and file format.
// If they fail, try sample rate and channels.
val = cp;
if (hdr.EncodingParse(val) &&
(audioformat_parse(val, hdr) < 0) &&
(fileformat_parse(val, format) < 0)) {
// If this looks like sample rate, make sure
// it is not ambiguous with channels
if (!hdr.RateParse(val)) {
if (hdr.sample_rate < 1000) {
int x;
char y[10];
if (sscanf(val, " %lf %9s",
&x, y) != 1) {
Err(
MGET("ambiguous numeric option: %s\n"),
val);
goto parse_error;
}
}
} else if (hdr.ChannelParse(val)) {
Err(MGET("invalid option value: %s\n"),
val);
goto parse_error;
}
}
}
}
free(buf);
return (0);
parse_error:
free(buf);
return (-1);
}
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License, Version 1.0 only
* (the "License"). You may not use this file except in compliance
* with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 1992-2001 by Sun Microsystems, Inc.
* All rights reserved.
*/
#ifndef _AUDIOCONVERT_PARSE_H
#define _AUDIOCONVERT_PARSE_H
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
K_NULL = 0, K_ENCODING = 1, K_FORMAT, K_RATE, K_CHANNELS,
K_OFFSET, K_INFO, K_AMBIG = -1
} keyword_type;
typedef enum {
F_RAW = 0, F_SUN = 1, F_AIFF, F_UNKNOWN = -1
} format_type;
struct keyword_table {
char *name;
keyword_type type;
};
extern int parse_format(char *, AudioHdr&, format_type&, off_t&);
#ifdef __cplusplus
}
#endif
#endif /* !_AUDIOCONVERT_PARSE_H */
|