sox-devel@lists.sourceforge.net unofficial mirror
 help / color / mirror / code / Atom feed
blob f868dab4b2942cd57013005db04cb57c72b6b68b 64006 bytes (raw)
name: src/wav.c 	 # note: path name is non-authoritative(*)

   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
 
/* libSoX microsoft's WAVE sound format handler
 *
 * Copyright 1998-2006 Chris Bagwell and SoX Contributors
 * Copyright 1997 Graeme W. Gill, 93/5/17
 * Copyright 1992 Rick Richardson
 * Copyright 1991 Lance Norskog And Sundry Contributors
 *
 * Info for format tags can be found at:
 *   http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html
 *
 */

#include "sox_i.h"

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

#include "ima_rw.h"
#include "adpcm.h"
#ifdef EXTERNAL_GSM

#ifdef HAVE_GSM_GSM_H
#include <gsm/gsm.h>
#else
#include <gsm.h>
#endif

#else
#include "../libgsm/gsm.h"
#endif

/* Magic length writen when its not possible to write valid lengths.
 * This can be either because of non-seekable output or because
 * the length can not be represented by the 32-bits used in WAV files.
 * When magic length is detected on inputs, disable any length
 * logic.
 */
#define MS_UNSPEC 0x7ffff000

#define WAVE_FORMAT_UNKNOWN             (0x0000U)
#define WAVE_FORMAT_PCM                 (0x0001U)
#define WAVE_FORMAT_ADPCM               (0x0002U)
#define WAVE_FORMAT_IEEE_FLOAT          (0x0003U)
#define WAVE_FORMAT_ALAW                (0x0006U)
#define WAVE_FORMAT_MULAW               (0x0007U)
#define WAVE_FORMAT_OKI_ADPCM           (0x0010U)
#define WAVE_FORMAT_IMA_ADPCM           (0x0011U)
#define WAVE_FORMAT_DIGISTD             (0x0015U)
#define WAVE_FORMAT_DIGIFIX             (0x0016U)
#define WAVE_FORMAT_DOLBY_AC2           (0x0030U)
#define WAVE_FORMAT_GSM610              (0x0031U)
#define WAVE_FORMAT_ROCKWELL_ADPCM      (0x003bU)
#define WAVE_FORMAT_ROCKWELL_DIGITALK   (0x003cU)
#define WAVE_FORMAT_G721_ADPCM          (0x0040U)
#define WAVE_FORMAT_G728_CELP           (0x0041U)
#define WAVE_FORMAT_MPEG                (0x0050U)
#define WAVE_FORMAT_MPEGLAYER3          (0x0055U)
#define WAVE_FORMAT_G726_ADPCM          (0x0064U)
#define WAVE_FORMAT_G722_ADPCM          (0x0065U)
#define WAVE_FORMAT_EXTENSIBLE          (0xfffeU)

/* To allow padding to samplesPerBlock. Works, but currently never true. */
static const size_t pad_nsamps = sox_false;

/* Private data for .wav file */
typedef struct {
    /* samples/channel reading: starts at total count and decremented  */
    /* writing: starts at 0 and counts samples written */
    uint64_t  numSamples;    
    size_t    dataLength;     /* needed for ADPCM writing */
    unsigned short formatTag;       /* What type of encoding file is using */
    unsigned short samplesPerBlock;
    unsigned short blockAlign;
    size_t dataStart;           /* need to for seeking */
    char           * comment;
    int ignoreSize;                 /* ignoreSize allows us to process 32-bit WAV files that are
                                     * greater then 2 Gb and can't be represented by the
                                     * 32-bit size field. */
  /* FIXME: Have some front-end code which sets this flag. */

    /* following used by *ADPCM wav files */
    unsigned short nCoefs;          /* ADPCM: number of coef sets */
    short         *lsx_ms_adpcm_i_coefs;          /* ADPCM: coef sets           */
    unsigned char *packet;          /* Temporary buffer for packets */
    short         *samples;         /* interleaved samples buffer */
    short         *samplePtr;       /* Pointer to current sample  */
    short         *sampleTop;       /* End of samples-buffer      */
    unsigned short blockSamplesRemaining;/* Samples remaining per channel */
    int            state[16];       /* step-size info for *ADPCM writes */

    /* following used by GSM 6.10 wav */
    gsm            gsmhandle;
    gsm_signal     *gsmsample;
    int            gsmindex;
    size_t      gsmbytecount;    /* counts bytes written to data block */
    sox_bool       isRF64;          /* True if file being read is a RF64 */
    uint64_t       ds64_dataSize;   /* Size of data chunk from ds64 header */
} priv_t;

static char *wav_format_str(unsigned wFormatTag);

static int wavwritehdr(sox_format_t *, int);


/****************************************************************************/
/* IMA ADPCM Support Functions Section                                      */
/****************************************************************************/

/*
 *
 * ImaAdpcmReadBlock - Grab and decode complete block of samples
 *
 */
static unsigned short  ImaAdpcmReadBlock(sox_format_t * ft)
{
    priv_t *       wav = (priv_t *) ft->priv;
    size_t bytesRead;
    int samplesThisBlock;

    /* Pull in the packet and check the header */
    bytesRead = lsx_readbuf(ft, wav->packet, (size_t)wav->blockAlign);
    samplesThisBlock = wav->samplesPerBlock;
    if (bytesRead < wav->blockAlign)
    {
        /* If it looks like a valid header is around then try and */
        /* work with partial blocks.  Specs say it should be null */
        /* padded but I guess this is better than trailing quiet. */
        samplesThisBlock = lsx_ima_samples_in((size_t)0, (size_t)ft->signal.channels, bytesRead, (size_t) 0);
        if (samplesThisBlock == 0)
        {
            lsx_warn("Premature EOF on .wav input file");
            return 0;
        }
    }

    wav->samplePtr = wav->samples;

    /* For a full block, the following should be true: */
    /* wav->samplesPerBlock = blockAlign - 8byte header + 1 sample in header */
    lsx_ima_block_expand_i(ft->signal.channels, wav->packet, wav->samples, samplesThisBlock);
    return samplesThisBlock;

}

/****************************************************************************/
/* MS ADPCM Support Functions Section                                       */
/****************************************************************************/

/*
 *
 * AdpcmReadBlock - Grab and decode complete block of samples
 *
 */
static unsigned short  AdpcmReadBlock(sox_format_t * ft)
{
    priv_t *       wav = (priv_t *) ft->priv;
    size_t bytesRead;
    int samplesThisBlock;
    const char *errmsg;

    /* Pull in the packet and check the header */
    bytesRead = lsx_readbuf(ft, wav->packet, (size_t) wav->blockAlign);
    samplesThisBlock = wav->samplesPerBlock;
    if (bytesRead < wav->blockAlign)
    {
        /* If it looks like a valid header is around then try and */
        /* work with partial blocks.  Specs say it should be null */
        /* padded but I guess this is better than trailing quiet. */
        samplesThisBlock = lsx_ms_adpcm_samples_in((size_t)0, (size_t)ft->signal.channels, bytesRead, (size_t)0);
        if (samplesThisBlock == 0 || samplesThisBlock > wav->samplesPerBlock)
        {
            lsx_warn("Premature EOF on .wav input file");
            return 0;
        }
    }

    errmsg = lsx_ms_adpcm_block_expand_i(ft->signal.channels, wav->nCoefs, wav->lsx_ms_adpcm_i_coefs, wav->packet, wav->samples, samplesThisBlock);

    if (errmsg)
        lsx_warn("%s", errmsg);

    return samplesThisBlock;
}

/****************************************************************************/
/* Common ADPCM Write Function                                              */
/****************************************************************************/

static int xxxAdpcmWriteBlock(sox_format_t * ft)
{
    priv_t * wav = (priv_t *) ft->priv;
    size_t chans, ct;
    short *p;

    chans = ft->signal.channels;
    p = wav->samplePtr;
    ct = p - wav->samples;
    if (ct>=chans) {
        /* zero-fill samples if needed to complete block */
        for (p = wav->samplePtr; p < wav->sampleTop; p++) *p=0;
        /* compress the samples to wav->packet */
        if (wav->formatTag == WAVE_FORMAT_ADPCM) {
            lsx_ms_adpcm_block_mash_i((unsigned) chans, wav->samples, wav->samplesPerBlock, wav->state, wav->packet, wav->blockAlign);
        }else{ /* WAVE_FORMAT_IMA_ADPCM */
            lsx_ima_block_mash_i((unsigned) chans, wav->samples, wav->samplesPerBlock, wav->state, wav->packet, 9);
        }
        /* write the compressed packet */
        if (lsx_writebuf(ft, wav->packet, (size_t) wav->blockAlign) != wav->blockAlign)
        {
            lsx_fail_errno(ft,SOX_EOF,"write error");
            return (SOX_EOF);
        }
        /* update lengths and samplePtr */
        wav->dataLength += wav->blockAlign;
        if (pad_nsamps)
          wav->numSamples += wav->samplesPerBlock;
        else
          wav->numSamples += ct/chans;
        wav->samplePtr = wav->samples;
    }
    return (SOX_SUCCESS);
}

/****************************************************************************/
/* WAV GSM6.10 support functions                                            */
/****************************************************************************/
/* create the gsm object, malloc buffer for 160*2 samples */
static int wavgsminit(sox_format_t * ft)
{
    int valueP=1;
    priv_t *       wav = (priv_t *) ft->priv;
    wav->gsmbytecount=0;
    wav->gsmhandle=gsm_create();
    if (!wav->gsmhandle)
    {
        lsx_fail_errno(ft,SOX_EOF,"cannot create GSM object");
        return (SOX_EOF);
    }

    if(gsm_option(wav->gsmhandle,GSM_OPT_WAV49,&valueP) == -1){
        lsx_fail_errno(ft,SOX_EOF,"error setting gsm_option for WAV49 format. Recompile gsm library with -DWAV49 option and relink sox");
        return (SOX_EOF);
    }

    wav->gsmsample=lsx_malloc(sizeof(gsm_signal)*160*2);
    wav->gsmindex=0;
    return (SOX_SUCCESS);
}

/*destroy the gsm object and free the buffer */
static void wavgsmdestroy(sox_format_t * ft)
{
    priv_t *       wav = (priv_t *) ft->priv;
    gsm_destroy(wav->gsmhandle);
    free(wav->gsmsample);
}

static size_t wavgsmread(sox_format_t * ft, sox_sample_t *buf, size_t len)
{
    priv_t *       wav = (priv_t *) ft->priv;
    size_t done=0;
    int bytes;
    gsm_byte    frame[65];

    ft->sox_errno = SOX_SUCCESS;

  /* copy out any samples left from the last call */
    while(wav->gsmindex && (wav->gsmindex<160*2) && (done < len))
        buf[done++]=SOX_SIGNED_16BIT_TO_SAMPLE(wav->gsmsample[wav->gsmindex++],);

  /* read and decode loop, possibly leaving some samples in wav->gsmsample */
    while (done < len) {
        wav->gsmindex=0;
        bytes = lsx_readbuf(ft, frame, (size_t)65);
        if (bytes <=0)
            return done;
        if (bytes<65) {
            lsx_warn("invalid wav gsm frame size: %d bytes",bytes);
            return done;
        }
        /* decode the long 33 byte half */
        if(gsm_decode(wav->gsmhandle,frame, wav->gsmsample)<0)
        {
            lsx_fail_errno(ft,SOX_EOF,"error during gsm decode");
            return 0;
        }
        /* decode the short 32 byte half */
        if(gsm_decode(wav->gsmhandle,frame+33, wav->gsmsample+160)<0)
        {
            lsx_fail_errno(ft,SOX_EOF,"error during gsm decode");
            return 0;
        }

        while ((wav->gsmindex <160*2) && (done < len)){
            buf[done++]=SOX_SIGNED_16BIT_TO_SAMPLE(wav->gsmsample[(wav->gsmindex)++],);
        }
    }

    return done;
}

static int wavgsmflush(sox_format_t * ft)
{
    gsm_byte    frame[65];
    priv_t *       wav = (priv_t *) ft->priv;

    /* zero fill as needed */
    while(wav->gsmindex<160*2)
        wav->gsmsample[wav->gsmindex++]=0;

    /*encode the even half short (32 byte) frame */
    gsm_encode(wav->gsmhandle, wav->gsmsample, frame);
    /*encode the odd half long (33 byte) frame */
    gsm_encode(wav->gsmhandle, wav->gsmsample+160, frame+32);
    if (lsx_writebuf(ft, frame, (size_t) 65) != 65)
    {
        lsx_fail_errno(ft,SOX_EOF,"write error");
        return (SOX_EOF);
    }
    wav->gsmbytecount += 65;

    wav->gsmindex = 0;
    return (SOX_SUCCESS);
}

static size_t wavgsmwrite(sox_format_t * ft, const sox_sample_t *buf, size_t len)
{
    priv_t * wav = (priv_t *) ft->priv;
    size_t done = 0;
    int rc;

    ft->sox_errno = SOX_SUCCESS;

    while (done < len) {
        SOX_SAMPLE_LOCALS;
        while ((wav->gsmindex < 160*2) && (done < len))
            wav->gsmsample[(wav->gsmindex)++] =
                SOX_SAMPLE_TO_SIGNED_16BIT(buf[done++], ft->clips);

        if (wav->gsmindex < 160*2)
            break;

        rc = wavgsmflush(ft);
        if (rc)
            return 0;
    }
    return done;

}

static void wavgsmstopwrite(sox_format_t * ft)
{
    priv_t *       wav = (priv_t *) ft->priv;

    ft->sox_errno = SOX_SUCCESS;

    if (wav->gsmindex)
        wavgsmflush(ft);

    /* Add a pad byte if amount of written bytes is not even. */
    if (wav->gsmbytecount && wav->gsmbytecount % 2){
        if(lsx_writeb(ft, 0))
            lsx_fail_errno(ft,SOX_EOF,"write error");
        else
            wav->gsmbytecount += 1;
    }

    wavgsmdestroy(ft);
}

/****************************************************************************/
/* General Sox WAV file code                                                */
/****************************************************************************/

static int sndfile_workaround(uint64_t *len, sox_format_t *ft) {
    char magic[5];
    off_t here;

    here = lsx_tell(ft);

    lsx_debug("Attempting work around for bad ds64 length bug");

    /* Seek to last four bytes of chunk, assuming size is correct. */
    if (lsx_seeki(ft, (off_t)(*len)-4, SEEK_CUR) != SOX_SUCCESS)
    {
        lsx_fail_errno(ft, SOX_EHDR, "WAV chunk appears to have invalid size %ld.", *len);
        return SOX_EOF;
    }

    /* Get the last four bytes to see if it is an "fmt " chunk */
    if (lsx_reads(ft, magic, (size_t)4) == SOX_EOF)
    {
        lsx_fail_errno(ft,SOX_EHDR, "WAV chunk appears to have invalid size %ld.", *len);
        return SOX_EOF;
    }

    /* Seek back to where we were, which won't work if you're piping */
    if (lsx_seeki(ft, here, SEEK_SET)!=SOX_SUCCESS)
    {
        lsx_fail_errno(ft,SOX_EHDR, "Cannot seek backwards to work around possible broken header.");
        return SOX_EOF;
    }
    if (memcmp(magic, "fmt ", (size_t)4)==0)
    {
        /* If the last four bytes were "fmt ", len is almost certainly four bytes too big. */
        lsx_debug("File had libsndfile bug, working around tell=%ld", lsx_tell(ft));
        *len -= 4;
    }
    return SOX_SUCCESS;
}

static int findChunk(sox_format_t * ft, const char *Label, uint64_t *len)
{
    char magic[5];
    priv_t *wav = (priv_t *) ft->priv;
    uint32_t len_tmp;

    lsx_debug("Searching for %2x %2x %2x %2x", Label[0], Label[1], Label[2], Label[3]);
    for (;;)
    {
        if (lsx_reads(ft, magic, (size_t)4) == SOX_EOF)
        {
            lsx_fail_errno(ft, SOX_EHDR, "WAVE file has missing %s chunk",
                          Label);
            return SOX_EOF;
        }
        lsx_debug("WAV Chunk %s", magic);
        if (lsx_readdw(ft, &len_tmp) == SOX_EOF)
        {
            lsx_fail_errno(ft, SOX_EHDR, "WAVE file %s chunk is too short",
                          magic);
            return SOX_EOF;
        }

        if (len_tmp == 0xffffffff && wav->isRF64==sox_true)
        {
            /* Chunk length should come from ds64 header */
            if (memcmp(magic, "data", (size_t)4)==0)
            {
                *len = wav->ds64_dataSize;
            }
            else
            {
                lsx_fail_errno(ft, SOX_EHDR, "Cannot yet read block sizes of arbitary RF64 chunks, cannot find chunk '%s'", Label);
                return SOX_EOF;
            }
        }
        else {
            *len = len_tmp;
        }

        /* Work around for a bug in libsndfile
         * https://github.com/erikd/libsndfile/commit/7fa1c57c37844a9d44642ea35e6638238b8af19e#src/rf64.c
           The ds64 chunk should be 0x1c bytes, not 0x20.
         */
        if ((*len) == 0x20 && memcmp(Label, "ds64", (size_t)4)==0)
        {
            int fail;
            if ((fail = sndfile_workaround(len, ft)) != SOX_SUCCESS) {
                return fail;
            }
        }

        if (memcmp(Label, magic, (size_t)4) == 0)
            break; /* Found the given chunk */

        /* Chunks are required to be word aligned. */
        if ((*len) % 2) (*len)++;

        /* skip to next chunk */
        if (!*len || lsx_seeki(ft, (off_t)(*len), SEEK_CUR) != SOX_SUCCESS)
        {
            lsx_fail_errno(ft,SOX_EHDR,
                          "WAV chunk appears to have invalid size %ld.", *len);
            return SOX_EOF;
        }
    }
    return SOX_SUCCESS;
}


static int wavfail(sox_format_t * ft, const char *format)
{
    lsx_fail_errno(ft, SOX_EHDR, "WAV file encoding `%s' is not supported", format);
    return SOX_EOF;
}

/*
 * Do anything required before you start reading samples.
 * Read file header.
 *      Find out sampling rate,
 *      size and encoding of samples,
 *      mono/stereo/quad.
 */
static int startread(sox_format_t * ft)
{
    priv_t *       wav = (priv_t *) ft->priv;
    char        magic[5];
    uint64_t    len;

    /* wave file characteristics */
    uint64_t      qwRiffLength;
    uint32_t      dwRiffLength_tmp;
    unsigned short wChannels;       /* number of channels */
    uint32_t      dwSamplesPerSecond; /* samples per second per channel */
    uint32_t      dwAvgBytesPerSec;/* estimate of bytes per second needed */
    uint16_t wBitsPerSample;  /* bits per sample */
    uint32_t wFmtSize;
    uint16_t wExtSize = 0;    /* extended field for non-PCM */

    uint64_t      qwDataLength;    /* length of sound data in bytes */
    size_t    bytesPerBlock = 0;
    int    bytespersample;          /* bytes per sample (per channel */
    char text[256];
    uint32_t      dwLoopPos;

    ft->sox_errno = SOX_SUCCESS;
    wav->ignoreSize = ft->signal.length == SOX_IGNORE_LENGTH;

    if (lsx_reads(ft, magic, (size_t)4) == SOX_EOF || (strncmp("RIFF", magic, (size_t)4) != 0 &&
                                             strncmp("RIFX", magic, (size_t)4) != 0 && strncmp("RF64", magic, (size_t)4)!=0 ))
    {
        lsx_fail_errno(ft,SOX_EHDR,"WAVE: RIFF header not found");
        return SOX_EOF;
    }

    /* RIFX is a Big-endian RIFF */
    if (strncmp("RIFX", magic, (size_t)4) == 0)
    {
        lsx_debug("Found RIFX header");
        ft->encoding.reverse_bytes = MACHINE_IS_LITTLEENDIAN;
    }
    else ft->encoding.reverse_bytes = MACHINE_IS_BIGENDIAN;

    if (strncmp("RF64", magic, (size_t)4) == 0)
    {
        wav->isRF64 = sox_true;
    }
    else
    {
        wav->isRF64 = sox_false;
    }

    lsx_readdw(ft, &dwRiffLength_tmp);
    qwRiffLength = dwRiffLength_tmp;

    if (lsx_reads(ft, magic, (size_t)4) == SOX_EOF || strncmp("WAVE", magic, (size_t)4))
    {
        lsx_fail_errno(ft,SOX_EHDR,"WAVE header not found");
        return SOX_EOF;
    }

    if (wav->isRF64 && findChunk(ft, "ds64", &len) != SOX_EOF) {
        lsx_debug("Found ds64 header");

        if (dwRiffLength_tmp==0xffffffff)
        {
            lsx_readqw(ft, &qwRiffLength);
        }
        else
        {
            lsx_skipbytes(ft, (size_t)8);
        }
        lsx_readqw(ft, &wav->ds64_dataSize);
        lsx_skipbytes(ft, (size_t)len-16);
    }

    /* Now look for the format chunk */
    if (findChunk(ft, "fmt ", &len) == SOX_EOF)
    {
        lsx_fail_errno(ft,SOX_EHDR,"WAVE chunk fmt not found");
        return SOX_EOF;
    }
    wFmtSize = len;

    if (wFmtSize < 16)
    {
        lsx_fail_errno(ft,SOX_EHDR,"WAVE file fmt chunk is too short");
        return SOX_EOF;
    }

    lsx_readw(ft, &(wav->formatTag));
    lsx_readw(ft, &wChannels);
    lsx_readdw(ft, &dwSamplesPerSecond);
    lsx_readdw(ft, &dwAvgBytesPerSec);   /* Average bytes/second */
    lsx_readw(ft, &(wav->blockAlign));   /* Block align */
    lsx_readw(ft, &wBitsPerSample);      /* bits per sample per channel */
    len -= 16;

    if (wav->formatTag == WAVE_FORMAT_EXTENSIBLE)
    {
      uint16_t extensionSize;
      uint16_t numberOfValidBits;
      uint32_t speakerPositionMask;
      uint16_t subFormatTag;
      uint8_t dummyByte;
      int i;

      if (wFmtSize < 18)
      {
        lsx_fail_errno(ft,SOX_EHDR,"WAVE file fmt chunk is too short");
        return SOX_EOF;
      }
      lsx_readw(ft, &extensionSize);
      len -= 2;
      if (extensionSize < 22)
      {
        lsx_fail_errno(ft,SOX_EHDR,"WAVE file fmt chunk is too short");
        return SOX_EOF;
      }
      lsx_readw(ft, &numberOfValidBits);
      lsx_readdw(ft, &speakerPositionMask);
      lsx_readw(ft, &subFormatTag);
      for (i = 0; i < 14; ++i) lsx_readb(ft, &dummyByte);
      len -= 22;
      if (numberOfValidBits != wBitsPerSample)
      {
        lsx_fail_errno(ft,SOX_EHDR,"WAVE file fmt with padded samples is not supported yet");
        return SOX_EOF;
      }
      wav->formatTag = subFormatTag;
      lsx_report("EXTENSIBLE");
    }

    switch (wav->formatTag)
    {
    case WAVE_FORMAT_UNKNOWN:
        lsx_fail_errno(ft,SOX_EHDR,"WAVE file is in unsupported Microsoft Official Unknown format.");
        return SOX_EOF;

    case WAVE_FORMAT_PCM:
        /* Default (-1) depends on sample size.  Set that later on. */
        if (ft->encoding.encoding != SOX_ENCODING_UNKNOWN && ft->encoding.encoding != SOX_ENCODING_UNSIGNED &&
            ft->encoding.encoding != SOX_ENCODING_SIGN2)
            lsx_report("User options overriding encoding read in .wav header");
        break;

    case WAVE_FORMAT_IMA_ADPCM:
        if (ft->encoding.encoding == SOX_ENCODING_UNKNOWN || ft->encoding.encoding == SOX_ENCODING_IMA_ADPCM)
            ft->encoding.encoding = SOX_ENCODING_IMA_ADPCM;
        else
            lsx_report("User options overriding encoding read in .wav header");
        break;

    case WAVE_FORMAT_ADPCM:
        if (ft->encoding.encoding == SOX_ENCODING_UNKNOWN || ft->encoding.encoding == SOX_ENCODING_MS_ADPCM)
            ft->encoding.encoding = SOX_ENCODING_MS_ADPCM;
        else
            lsx_report("User options overriding encoding read in .wav header");
        break;

    case WAVE_FORMAT_IEEE_FLOAT:
        if (ft->encoding.encoding == SOX_ENCODING_UNKNOWN || ft->encoding.encoding == SOX_ENCODING_FLOAT)
            ft->encoding.encoding = SOX_ENCODING_FLOAT;
        else
            lsx_report("User options overriding encoding read in .wav header");
        break;

    case WAVE_FORMAT_ALAW:
        if (ft->encoding.encoding == SOX_ENCODING_UNKNOWN || ft->encoding.encoding == SOX_ENCODING_ALAW)
            ft->encoding.encoding = SOX_ENCODING_ALAW;
        else
            lsx_report("User options overriding encoding read in .wav header");
        break;

    case WAVE_FORMAT_MULAW:
        if (ft->encoding.encoding == SOX_ENCODING_UNKNOWN || ft->encoding.encoding == SOX_ENCODING_ULAW)
            ft->encoding.encoding = SOX_ENCODING_ULAW;
        else
            lsx_report("User options overriding encoding read in .wav header");
        break;

    case WAVE_FORMAT_OKI_ADPCM:
        return wavfail(ft, "OKI ADPCM");
    case WAVE_FORMAT_DIGISTD:
        return wavfail(ft, "Digistd");
    case WAVE_FORMAT_DIGIFIX:
        return wavfail(ft, "Digifix");
    case WAVE_FORMAT_DOLBY_AC2:
        return wavfail(ft, "Dolby AC2");
    case WAVE_FORMAT_GSM610:
        if (ft->encoding.encoding == SOX_ENCODING_UNKNOWN || ft->encoding.encoding == SOX_ENCODING_GSM )
            ft->encoding.encoding = SOX_ENCODING_GSM;
        else
            lsx_report("User options overriding encoding read in .wav header");
        break;
    case WAVE_FORMAT_ROCKWELL_ADPCM:
        return wavfail(ft, "Rockwell ADPCM");
    case WAVE_FORMAT_ROCKWELL_DIGITALK:
        return wavfail(ft, "Rockwell DIGITALK");
    case WAVE_FORMAT_G721_ADPCM:
        return wavfail(ft, "G.721 ADPCM");
    case WAVE_FORMAT_G728_CELP:
        return wavfail(ft, "G.728 CELP");
    case WAVE_FORMAT_MPEG:
        return wavfail(ft, "MPEG");
    case WAVE_FORMAT_MPEGLAYER3:
        return wavfail(ft, "MP3");
    case WAVE_FORMAT_G726_ADPCM:
        return wavfail(ft, "G.726 ADPCM");
    case WAVE_FORMAT_G722_ADPCM:
        return wavfail(ft, "G.722 ADPCM");
    default:
        lsx_fail_errno(ft, SOX_EHDR, "Unknown WAV file encoding (type %x)", wav->formatTag);
        return SOX_EOF;
    }

    /* User options take precedence */
    if (ft->signal.channels == 0 || ft->signal.channels == wChannels)
        ft->signal.channels = wChannels;
    else
        lsx_report("User options overriding channels read in .wav header");

    if (ft->signal.rate == 0 || ft->signal.rate == dwSamplesPerSecond)
        ft->signal.rate = dwSamplesPerSecond;
    else
        lsx_report("User options overriding rate read in .wav header");


    wav->lsx_ms_adpcm_i_coefs = NULL;
    wav->packet = NULL;
    wav->samples = NULL;

    /* non-PCM formats except alaw and mulaw formats have extended fmt chunk.
     * Check for those cases.
     */
    if (wav->formatTag != WAVE_FORMAT_PCM &&
        wav->formatTag != WAVE_FORMAT_ALAW &&
        wav->formatTag != WAVE_FORMAT_MULAW) {
        if (len >= 2) {
            lsx_readw(ft, &wExtSize);
            len -= 2;
        } else {
            lsx_warn("wave header missing extended part of fmt chunk");
        }
    }

    if (wExtSize > len)
    {
        lsx_fail_errno(ft,SOX_EOF,"wave header error: wExtSize inconsistent with wFmtLen");
        return SOX_EOF;
    }

    switch (wav->formatTag)
    {
    case WAVE_FORMAT_ADPCM:
        if (wExtSize < 4)
        {
            lsx_fail_errno(ft,SOX_EOF,"format[%s]: expects wExtSize >= %d",
                        wav_format_str(wav->formatTag), 4);
            return SOX_EOF;
        }

        if (wBitsPerSample != 4)
        {
            lsx_fail_errno(ft,SOX_EOF,"Can only handle 4-bit MS ADPCM in wav files");
            return SOX_EOF;
        }

        lsx_readw(ft, &(wav->samplesPerBlock));
        bytesPerBlock = lsx_ms_adpcm_bytes_per_block((size_t) ft->signal.channels, (size_t) wav->samplesPerBlock);
        if (bytesPerBlock != wav->blockAlign)
        {
            lsx_fail_errno(ft,SOX_EOF,"format[%s]: samplesPerBlock(%d) incompatible with blockAlign(%d)",
                wav_format_str(wav->formatTag), wav->samplesPerBlock, wav->blockAlign);
            return SOX_EOF;
        }

        lsx_readw(ft, &(wav->nCoefs));
        if (wav->nCoefs < 7 || wav->nCoefs > 0x100) {
            lsx_fail_errno(ft,SOX_EOF,"ADPCM file nCoefs (%.4hx) makes no sense", wav->nCoefs);
            return SOX_EOF;
        }
        wav->packet = lsx_malloc((size_t)wav->blockAlign);

        len -= 4;

        if (wExtSize < 4 + 4*wav->nCoefs)
        {
            lsx_fail_errno(ft,SOX_EOF,"wave header error: wExtSize(%d) too small for nCoefs(%d)", wExtSize, wav->nCoefs);
            return SOX_EOF;
        }

        wav->samples = lsx_malloc(wChannels*wav->samplesPerBlock*sizeof(short));

        /* nCoefs, lsx_ms_adpcm_i_coefs used by adpcm.c */
        wav->lsx_ms_adpcm_i_coefs = lsx_malloc(wav->nCoefs * 2 * sizeof(short));
        {
            int i, errct=0;
            for (i=0; len>=2 && i < 2*wav->nCoefs; i++) {
                lsx_readsw(ft, &(wav->lsx_ms_adpcm_i_coefs[i]));
                len -= 2;
                if (i<14) errct += (wav->lsx_ms_adpcm_i_coefs[i] != lsx_ms_adpcm_i_coef[i/2][i%2]);
                /* lsx_debug("lsx_ms_adpcm_i_coefs[%2d] %4d",i,wav->lsx_ms_adpcm_i_coefs[i]); */
            }
            if (errct) lsx_warn("base lsx_ms_adpcm_i_coefs differ in %d/14 positions",errct);
        }

        bytespersample = 2;  /* AFTER de-compression */
        break;

    case WAVE_FORMAT_IMA_ADPCM:
        if (wExtSize < 2)
        {
            lsx_fail_errno(ft,SOX_EOF,"format[%s]: expects wExtSize >= %d",
                    wav_format_str(wav->formatTag), 2);
            return SOX_EOF;
        }

        if (wBitsPerSample != 4)
        {
            lsx_fail_errno(ft,SOX_EOF,"Can only handle 4-bit IMA ADPCM in wav files");
            return SOX_EOF;
        }

        lsx_readw(ft, &(wav->samplesPerBlock));
        bytesPerBlock = lsx_ima_bytes_per_block((size_t) ft->signal.channels, (size_t) wav->samplesPerBlock);
        if (bytesPerBlock != wav->blockAlign || wav->samplesPerBlock%8 != 1)
        {
            lsx_fail_errno(ft,SOX_EOF,"format[%s]: samplesPerBlock(%d) incompatible with blockAlign(%d)",
                wav_format_str(wav->formatTag), wav->samplesPerBlock, wav->blockAlign);
            return SOX_EOF;
        }

        wav->packet = lsx_malloc((size_t)wav->blockAlign);
        len -= 2;

        wav->samples = lsx_malloc(wChannels*wav->samplesPerBlock*sizeof(short));

        bytespersample = 2;  /* AFTER de-compression */
        break;

    /* GSM formats have extended fmt chunk.  Check for those cases. */
    case WAVE_FORMAT_GSM610:
        if (wExtSize < 2)
        {
            lsx_fail_errno(ft,SOX_EOF,"format[%s]: expects wExtSize >= %d",
                    wav_format_str(wav->formatTag), 2);
            return SOX_EOF;
        }
        lsx_readw(ft, &wav->samplesPerBlock);
        bytesPerBlock = 65;
        if (wav->blockAlign != 65)
        {
            lsx_fail_errno(ft,SOX_EOF,"format[%s]: expects blockAlign(%d) = %d",
                    wav_format_str(wav->formatTag), wav->blockAlign, 65);
            return SOX_EOF;
        }
        if (wav->samplesPerBlock != 320)
        {
            lsx_fail_errno(ft,SOX_EOF,"format[%s]: expects samplesPerBlock(%d) = %d",
                    wav_format_str(wav->formatTag), wav->samplesPerBlock, 320);
            return SOX_EOF;
        }
        bytespersample = 2;  /* AFTER de-compression */
        len -= 2;
        break;

    default:
      bytespersample = (wBitsPerSample + 7)/8;

    }

    /* User options take precedence */
    if (!ft->encoding.bits_per_sample || ft->encoding.bits_per_sample == wBitsPerSample)
      ft->encoding.bits_per_sample = wBitsPerSample;
    else
      lsx_warn("User options overriding size read in .wav header");

    /* Now we have enough information to set default encodings. */
    switch (bytespersample)
    {
    case 1:
      if (ft->encoding.encoding == SOX_ENCODING_UNKNOWN)
        ft->encoding.encoding = SOX_ENCODING_UNSIGNED;
      break;

    case 2: case 3: case 4:
      if (ft->encoding.encoding == SOX_ENCODING_UNKNOWN)
        ft->encoding.encoding = SOX_ENCODING_SIGN2;
      break;

    case 8:
      if (ft->encoding.encoding == SOX_ENCODING_UNKNOWN)
        ft->encoding.encoding = SOX_ENCODING_FLOAT;
      break;

    default:
      lsx_fail_errno(ft,SOX_EFMT,"Sorry, don't understand .wav size");
      return SOX_EOF;
    }

    /* Skip anything left over from fmt chunk */
    lsx_seeki(ft, (off_t)len, SEEK_CUR);

    /* for non-PCM formats, there's a 'fact' chunk before
     * the upcoming 'data' chunk */

    /* Now look for the wave data chunk */
    if (findChunk(ft, "data", &len) == SOX_EOF)
    {
        lsx_fail_errno(ft, SOX_EOF, "Could not find data chunk.");
        return SOX_EOF;
    }

    /* ds64 size will have been applied in findChunk */
    qwDataLength = len;
    /* XXX - does MS_UNSPEC apply to RF64 files? */
    if (qwDataLength == MS_UNSPEC) {
      wav->ignoreSize = 1;
      lsx_debug("WAV Chunk data's length is value often used in pipes or 4G files.  Ignoring length.");
    }


    /* Data starts here */
    wav->dataStart = lsx_tell(ft);

    switch (wav->formatTag)
    {

    case WAVE_FORMAT_ADPCM:
        wav->numSamples =
            lsx_ms_adpcm_samples_in((size_t)qwDataLength, (size_t)ft->signal.channels,
                           (size_t)wav->blockAlign, (size_t)wav->samplesPerBlock);
        lsx_debug_more("datalen %ld, numSamples %lu",qwDataLength, (unsigned long)wav->numSamples);
        wav->blockSamplesRemaining = 0;        /* Samples left in buffer */
        ft->signal.length = wav->numSamples*ft->signal.channels;
        break;

    case WAVE_FORMAT_IMA_ADPCM:
        /* Compute easiest part of number of samples.  For every block, there
           are samplesPerBlock samples to read. */
        wav->numSamples =
            lsx_ima_samples_in((size_t)qwDataLength, (size_t)ft->signal.channels,
                         (size_t)wav->blockAlign, (size_t)wav->samplesPerBlock);
        lsx_debug_more("datalen %ld, numSamples %lu",qwDataLength, (unsigned long)wav->numSamples);
        wav->blockSamplesRemaining = 0;        /* Samples left in buffer */
        lsx_ima_init_table();
        ft->signal.length = wav->numSamples*ft->signal.channels;
        break;

    case WAVE_FORMAT_GSM610:
        wav->numSamples = ((qwDataLength / wav->blockAlign) * wav->samplesPerBlock);
        wavgsminit(ft);
        ft->signal.length = wav->numSamples*ft->signal.channels;
        break;

    default:
        wav->numSamples = div_bits(qwDataLength, ft->encoding.bits_per_sample) / ft->signal.channels;
        ft->signal.length = wav->numSamples * ft->signal.channels;
    }
     
    /* When ignoring size, reset length so that output files do
     * not mistakenly depend on it.
     */
    if (wav->ignoreSize)
      ft->signal.length = SOX_UNSPEC;

    lsx_debug("Reading Wave file: %s format, %d channel%s, %d samp/sec",
           wav_format_str(wav->formatTag), ft->signal.channels,
           wChannels == 1 ? "" : "s", dwSamplesPerSecond);
    lsx_debug("        %d byte/sec, %d block align, %d bits/samp, %lu data bytes",
           dwAvgBytesPerSec, wav->blockAlign, wBitsPerSample, qwDataLength);

    /* Can also report extended fmt information */
    switch (wav->formatTag)
    {
        case WAVE_FORMAT_ADPCM:
            lsx_debug("        %d Extsize, %d Samps/block, %lu bytes/block %d Num Coefs, %lu Samps/chan",
                      wExtSize,wav->samplesPerBlock,
                      (unsigned long)bytesPerBlock,wav->nCoefs,
                      (unsigned long)wav->numSamples);
            break;

        case WAVE_FORMAT_IMA_ADPCM:
            lsx_debug("        %d Extsize, %d Samps/block, %lu bytes/block %lu Samps/chan",
                      wExtSize, wav->samplesPerBlock, 
                      (unsigned long)bytesPerBlock,
                      (unsigned long)wav->numSamples);
            break;

        case WAVE_FORMAT_GSM610:
            lsx_debug("GSM .wav: %d Extsize, %d Samps/block, %lu Samples/chan",
                      wExtSize, wav->samplesPerBlock, 
                      (unsigned long)wav->numSamples);
            break;

        default:
            lsx_debug("        %lu Samps/chans", 
                      (unsigned long)wav->numSamples);
    }

    /* Horrible way to find Cool Edit marker points. Taken from Quake source*/
    ft->oob.loops[0].start = SOX_IGNORE_LENGTH;
    if(ft->seekable){
        /*Got this from the quake source.  I think it 32bit aligns the chunks
         * doubt any machine writing Cool Edit Chunks writes them at an odd
         * offset */
        len = (len + 1) & ~1u;
        if (lsx_seeki(ft, (off_t)len, SEEK_CUR) == SOX_SUCCESS &&
            findChunk(ft, "LIST", &len) != SOX_EOF)
        {
            wav->comment = lsx_malloc((size_t)256);
            /* Initialize comment to a NULL string */
            wav->comment[0] = 0;
            while(!lsx_eof(ft))
            {
                if (lsx_reads(ft,magic,(size_t)4) == SOX_EOF)
                    break;

                /* First look for type fields for LIST Chunk and
                 * skip those if found.  Since a LIST is a list
                 * of Chunks, treat the remaining data as Chunks
                 * again.
                 */
                if (strncmp(magic, "INFO", (size_t)4) == 0)
                {
                    /*Skip*/
                    lsx_debug("Type INFO");
                }
                else if (strncmp(magic, "adtl", (size_t)4) == 0)
                {
                    /* Skip */
                    lsx_debug("Type adtl");
                }
                else
                {
                    uint32_t len_tmp;
                    if (lsx_readdw(ft,&len_tmp) == SOX_EOF)
                        break;
                    len = len_tmp;
                    if (strncmp(magic,"ICRD",(size_t)4) == 0)
                    {
                        lsx_debug("Chunk ICRD");
                        if (len > 254)
                        {
                            lsx_warn("Possible buffer overflow hack attack (ICRD)!");
                            break;
                        }
                        lsx_reads(ft,text, (size_t)len);
                        if (strlen(wav->comment) + strlen(text) < 254)
                        {
                            if (wav->comment[0] != 0)
                                strcat(wav->comment,"\n");

                            strcat(wav->comment,text);
                        }
                        if (strlen(text) < len)
                           lsx_seeki(ft, (off_t)(len - strlen(text)), SEEK_CUR);
                    }
                    else if (strncmp(magic,"ISFT",(size_t)4) == 0)
                    {
                        lsx_debug("Chunk ISFT");
                        if (len > 254)
                        {
                            lsx_warn("Possible buffer overflow hack attack (ISFT)!");
                            break;
                        }
                        lsx_reads(ft,text, (size_t)len);
                        if (strlen(wav->comment) + strlen(text) < 254)
                        {
                            if (wav->comment[0] != 0)
                                strcat(wav->comment,"\n");

                            strcat(wav->comment,text);
                        }
                        if (strlen(text) < len)
                           lsx_seeki(ft, (off_t)(len - strlen(text)), SEEK_CUR);
                    }
                    else if (strncmp(magic,"cue ",(size_t)4) == 0)
                    {
                        lsx_debug("Chunk cue ");
                        lsx_seeki(ft,(off_t)(len-4),SEEK_CUR);
                        lsx_readdw(ft,&dwLoopPos);
                        ft->oob.loops[0].start = dwLoopPos;
                    }
                    else if (strncmp(magic,"ltxt",(size_t)4) == 0)
                    {
                        lsx_debug("Chunk ltxt");
                        lsx_readdw(ft,&dwLoopPos);
                        ft->oob.loops[0].length = dwLoopPos - ft->oob.loops[0].start;
                        if (len > 4)
                           lsx_seeki(ft, (off_t)(len - 4), SEEK_CUR);
                    }
                    else
                    {
                        lsx_debug("Attempting to seek beyond unsupported chunk `%c%c%c%c' of length %ld bytes", magic[0], magic[1], magic[2], magic[3], len);
                        len = (len + 1) & ~1u;
                        lsx_seeki(ft, (off_t)len, SEEK_CUR);
                    }
                }
            }
        }
        lsx_clearerr(ft);
        lsx_seeki(ft,(off_t)wav->dataStart,SEEK_SET);
    }
    return lsx_rawstartread(ft);
}


/*
 * Read up to len samples from file.
 * Convert to signed longs.
 * Place in buf[].
 * Return number of samples read.
 */

static size_t read_samples(sox_format_t * ft, sox_sample_t *buf, size_t len)
{
        priv_t *   wav = (priv_t *) ft->priv;
        size_t done;

        ft->sox_errno = SOX_SUCCESS;

        /* If file is in ADPCM encoding then read in multiple blocks else */
        /* read as much as possible and return quickly. */
        switch (ft->encoding.encoding)
        {
        case SOX_ENCODING_IMA_ADPCM:
        case SOX_ENCODING_MS_ADPCM:

            if (!wav->ignoreSize && len > (wav->numSamples*ft->signal.channels))
                len = (wav->numSamples*ft->signal.channels);

            done = 0;
            while (done < len) { /* Still want data? */
                /* See if need to read more from disk */
                if (wav->blockSamplesRemaining == 0) {
                    if (wav->formatTag == WAVE_FORMAT_IMA_ADPCM)
                        wav->blockSamplesRemaining = ImaAdpcmReadBlock(ft);
                    else
                        wav->blockSamplesRemaining = AdpcmReadBlock(ft);
                    if (wav->blockSamplesRemaining == 0)
                    {
                        /* Don't try to read any more samples */
                        wav->numSamples = 0;
                        return done;
                    }
                    wav->samplePtr = wav->samples;
                }

                /* Copy interleaved data into buf, converting to sox_sample_t */
                {
                    short *p, *top;
                    size_t ct;
                    ct = len-done;
                    if (ct > (wav->blockSamplesRemaining*ft->signal.channels))
                        ct = (wav->blockSamplesRemaining*ft->signal.channels);

                    done += ct;
                    wav->blockSamplesRemaining -= (ct/ft->signal.channels);
                    p = wav->samplePtr;
                    top = p+ct;
                    /* Output is already signed */
                    while (p<top)
                        *buf++ = SOX_SIGNED_16BIT_TO_SAMPLE((*p++),);

                    wav->samplePtr = p;
                }
            }
            /* "done" for ADPCM equals total data processed and not
             * total samples procesed.  The only way to take care of that
             * is to return here and not fall thru.
             */
            wav->numSamples -= (done / ft->signal.channels);
            return done;
            break;

        case SOX_ENCODING_GSM:
            if (!wav->ignoreSize && len > wav->numSamples*ft->signal.channels)
                len = (wav->numSamples*ft->signal.channels);

            done = wavgsmread(ft, buf, len);
            if (done == 0 && wav->numSamples != 0 && !wav->ignoreSize)
                lsx_warn("Premature EOF on .wav input file");
        break;

        default: /* assume PCM or float encoding */
            if (!wav->ignoreSize && len > wav->numSamples*ft->signal.channels)
                len = (wav->numSamples*ft->signal.channels);

            done = lsx_rawread(ft, buf, len);
            /* If software thinks there are more samples but I/O */
            /* says otherwise, let the user know about this.     */
            if (done == 0 && wav->numSamples != 0 && !wav->ignoreSize)
                lsx_warn("Premature EOF on .wav input file");
        }

        /* Only return buffers that contain a totally playable
         * amount of audio.
         */
        done -= done % ft->signal.channels;
        if (done/ft->signal.channels > wav->numSamples)
            wav->numSamples = 0;
        else
            wav->numSamples -= (done/ft->signal.channels);
        return done;
}

/*
 * Do anything required when you stop reading samples.
 * Don't close input file!
 */
static int stopread(sox_format_t * ft)
{
    priv_t *       wav = (priv_t *) ft->priv;

    ft->sox_errno = SOX_SUCCESS;

    free(wav->packet);
    free(wav->samples);
    free(wav->lsx_ms_adpcm_i_coefs);
    free(wav->comment);
    wav->comment = NULL;

    switch (ft->encoding.encoding)
    {
    case SOX_ENCODING_GSM:
        wavgsmdestroy(ft);
        break;
    case SOX_ENCODING_IMA_ADPCM:
    case SOX_ENCODING_MS_ADPCM:
        break;
    default:
        break;
    }
    return SOX_SUCCESS;
}

static int startwrite(sox_format_t * ft)
{
    priv_t * wav = (priv_t *) ft->priv;
    int rc;

    ft->sox_errno = SOX_SUCCESS;

    if (ft->encoding.encoding != SOX_ENCODING_MS_ADPCM &&
        ft->encoding.encoding != SOX_ENCODING_IMA_ADPCM &&
        ft->encoding.encoding != SOX_ENCODING_GSM)
    {
        rc = lsx_rawstartwrite(ft);
        if (rc)
            return rc;
    }

    wav->numSamples = 0;
    wav->dataLength = 0;
    if (!ft->signal.length && !ft->seekable)
        lsx_warn("Length in output .wav header will be wrong since can't seek to fix it");

    rc = wavwritehdr(ft, 0);  /* also calculates various wav->* info */
    if (rc != 0)
        return rc;

    wav->packet = NULL;
    wav->samples = NULL;
    wav->lsx_ms_adpcm_i_coefs = NULL;
    switch (wav->formatTag)
    {
        size_t ch, sbsize;

        case WAVE_FORMAT_IMA_ADPCM:
            lsx_ima_init_table();
        /* intentional case fallthru! */
        case WAVE_FORMAT_ADPCM:
            /* #channels already range-checked for overflow in wavwritehdr() */
            for (ch=0; ch<ft->signal.channels; ch++)
                wav->state[ch] = 0;
            sbsize = ft->signal.channels * wav->samplesPerBlock;
            wav->packet = lsx_malloc((size_t)wav->blockAlign);
            wav->samples = lsx_malloc(sbsize*sizeof(short));
            wav->sampleTop = wav->samples + sbsize;
            wav->samplePtr = wav->samples;
            break;

        case WAVE_FORMAT_GSM610:
            return wavgsminit(ft);

        default:
            break;
    }
    return SOX_SUCCESS;
}

/* wavwritehdr:  write .wav headers as follows:

bytes      variable      description
0  - 3     'RIFF'/'RIFX' Little/Big-endian
4  - 7     wRiffLength   length of file minus the 8 byte riff header
8  - 11    'WAVE'
12 - 15    'fmt '
16 - 19    wFmtSize       length of format chunk minus 8 byte header
20 - 21    wFormatTag     identifies PCM, ULAW etc
22 - 23    wChannels
24 - 27    dwSamplesPerSecond  samples per second per channel
28 - 31    dwAvgBytesPerSec    non-trivial for compressed formats
32 - 33    wBlockAlign         basic block size
34 - 35    wBitsPerSample      non-trivial for compressed formats

PCM formats then go straight to the data chunk:
36 - 39    'data'
40 - 43     dwDataLength   length of data chunk minus 8 byte header
44 - (dwDataLength + 43)   the data
(+ a padding byte if dwDataLength is odd)

non-PCM formats must write an extended format chunk and a fact chunk:

ULAW, ALAW formats:
36 - 37    wExtSize = 0  the length of the format extension
38 - 41    'fact'
42 - 45    dwFactSize = 4  length of the fact chunk minus 8 byte header
46 - 49    dwSamplesWritten   actual number of samples written out
50 - 53    'data'
54 - 57     dwDataLength  length of data chunk minus 8 byte header
58 - (dwDataLength + 57)  the data
(+ a padding byte if dwDataLength is odd)


GSM6.10  format:
36 - 37    wExtSize = 2 the length in bytes of the format-dependent extension
38 - 39    320           number of samples per  block
40 - 43    'fact'
44 - 47    dwFactSize = 4  length of the fact chunk minus 8 byte header
48 - 51    dwSamplesWritten   actual number of samples written out
52 - 55    'data'
56 - 59     dwDataLength  length of data chunk minus 8 byte header
60 - (dwDataLength + 59)  the data (including a padding byte, if necessary,
                            so dwDataLength is always even)


note that header contains (up to) 3 separate ways of describing the
length of the file, all derived here from the number of (input)
samples wav->numSamples in a way that is non-trivial for the blocked
and padded compressed formats:

wRiffLength -      (riff header) the length of the file, minus 8
dwSamplesWritten - (fact header) the number of samples written (after padding
                   to a complete block eg for GSM)
dwDataLength     - (data chunk header) the number of (valid) data bytes written

*/

static int wavwritehdr(sox_format_t * ft, int second_header)
{
    priv_t *       wav = (priv_t *) ft->priv;

    /* variables written to wav file header */
    /* RIFF header */
    uint32_t wRiffLength ;  /* length of file after 8 byte riff header */
    /* fmt chunk */
    uint16_t wFmtSize = 16;       /* size field of the fmt chunk */
    uint16_t wFormatTag = 0;      /* data format */
    uint16_t wChannels;           /* number of channels */
    uint32_t dwSamplesPerSecond;  /* samples per second per channel*/
    uint32_t dwAvgBytesPerSec=0;  /* estimate of bytes per second needed */
    uint16_t wBlockAlign=0;       /* byte alignment of a basic sample block */
    uint16_t wBitsPerSample=0;    /* bits per sample */
    /* fmt chunk extension (not PCM) */
    uint16_t wExtSize=0;          /* extra bytes in the format extension */
    uint16_t wSamplesPerBlock;    /* samples per channel per block */
    /* wSamplesPerBlock and other things may go into format extension */

    /* fact chunk (not PCM) */
    uint32_t dwFactSize=4;        /* length of the fact chunk */
    uint32_t dwSamplesWritten=0;  /* windows doesnt seem to use this*/

    /* data chunk */
    uint32_t  dwDataLength; /* length of sound data in bytes */
    /* end of variables written to header */

    /* internal variables, intermediate values etc */
    int bytespersample; /* (uncompressed) bytes per sample (per channel) */
    long blocksWritten = 0;
    sox_bool isExtensible = sox_false;    /* WAVE_FORMAT_EXTENSIBLE? */

    dwSamplesPerSecond = ft->signal.rate;
    wChannels = ft->signal.channels;
    wBitsPerSample = ft->encoding.bits_per_sample;
    wSamplesPerBlock = 1;       /* common default for PCM data */

    switch (ft->encoding.encoding)
    {
        case SOX_ENCODING_UNSIGNED:
        case SOX_ENCODING_SIGN2:
            wFormatTag = WAVE_FORMAT_PCM;
            bytespersample = (wBitsPerSample + 7)/8;
            wBlockAlign = wChannels * bytespersample;
            break;
        case SOX_ENCODING_FLOAT:
            wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
            bytespersample = (wBitsPerSample + 7)/8;
            wBlockAlign = wChannels * bytespersample;
            break;
        case SOX_ENCODING_ALAW:
            wFormatTag = WAVE_FORMAT_ALAW;
            wBlockAlign = wChannels;
            break;
        case SOX_ENCODING_ULAW:
            wFormatTag = WAVE_FORMAT_MULAW;
            wBlockAlign = wChannels;
            break;
        case SOX_ENCODING_IMA_ADPCM:
            if (wChannels>16)
            {
                lsx_fail_errno(ft,SOX_EOF,"Channels(%d) must be <= 16",wChannels);
                return SOX_EOF;
            }
            wFormatTag = WAVE_FORMAT_IMA_ADPCM;
            wBlockAlign = wChannels * 256; /* reasonable default */
            wBitsPerSample = 4;
            wExtSize = 2;
            wSamplesPerBlock = lsx_ima_samples_in((size_t) 0, (size_t) wChannels, (size_t) wBlockAlign, (size_t) 0);
            break;
        case SOX_ENCODING_MS_ADPCM:
            if (wChannels>16)
            {
                lsx_fail_errno(ft,SOX_EOF,"Channels(%d) must be <= 16",wChannels);
                return SOX_EOF;
            }
            wFormatTag = WAVE_FORMAT_ADPCM;
            wBlockAlign = ft->signal.rate / 11008;
            wBlockAlign = max(wBlockAlign, 1) * wChannels * 256;
            wBitsPerSample = 4;
            wExtSize = 4+4*7;      /* Ext fmt data length */
            wSamplesPerBlock = lsx_ms_adpcm_samples_in((size_t) 0, (size_t) wChannels, (size_t) wBlockAlign, (size_t) 0);
            break;
        case SOX_ENCODING_GSM:
            if (wChannels!=1)
            {
                lsx_report("Overriding GSM audio from %d channel to 1",wChannels);
                if (!second_header)
                  ft->signal.length /= max(1, ft->signal.channels);
                wChannels = ft->signal.channels = 1;
            }
            wFormatTag = WAVE_FORMAT_GSM610;
            /* dwAvgBytesPerSec = 1625*(dwSamplesPerSecond/8000.)+0.5; */
            wBlockAlign=65;
            wBitsPerSample=0;  /* not representable as int   */
            wExtSize=2;        /* length of format extension */
            wSamplesPerBlock = 320;
            break;
        default:
                break;
    }
    wav->formatTag = wFormatTag;
    wav->blockAlign = wBlockAlign;
    wav->samplesPerBlock = wSamplesPerBlock;

    /* When creating header, use length hint given by input file.  If no
     * hint then write default value.  Also, use default value even
     * on header update if more then 32-bit length needs to be written.
     */
    if ((!second_header && !ft->signal.length) || 
        wav->numSamples > 0xffffffff) { 
        /* adjust for blockAlign */
        blocksWritten = MS_UNSPEC/wBlockAlign;
        dwDataLength = blocksWritten * wBlockAlign;
        dwSamplesWritten = blocksWritten * wSamplesPerBlock;
    } else {    /* fixup with real length */
        dwSamplesWritten = 
            second_header? wav->numSamples : ft->signal.length / wChannels;
        blocksWritten = (dwSamplesWritten+wSamplesPerBlock-1)/wSamplesPerBlock;
        dwDataLength = blocksWritten * wBlockAlign;
    }

    if (wFormatTag == WAVE_FORMAT_GSM610)
        dwDataLength = (dwDataLength+1) & ~1u; /* round up to even */

    if (wFormatTag == WAVE_FORMAT_PCM && (wBitsPerSample > 16 || wChannels > 2)
        && strcmp(ft->filetype, "wavpcm")) {
      isExtensible = sox_true;
      wFmtSize += 2 + 22;
    }
    else if (wFormatTag != WAVE_FORMAT_PCM)
        wFmtSize += 2+wExtSize; /* plus ExtData */

    wRiffLength = 4 + (8+wFmtSize) + (8+dwDataLength+dwDataLength%2);
    if (isExtensible || wFormatTag != WAVE_FORMAT_PCM) /* PCM omits the "fact" chunk */
        wRiffLength += (8+dwFactSize);

    /* dwAvgBytesPerSec <-- this is BEFORE compression, isn't it? guess not. */
    dwAvgBytesPerSec = (double)wBlockAlign*ft->signal.rate / (double)wSamplesPerBlock + 0.5;

    /* figured out header info, so write it */

    /* If user specified opposite swap than we think, assume they are
     * asking to write a RIFX file.
     */
    if (ft->encoding.reverse_bytes == MACHINE_IS_LITTLEENDIAN)
    {
        if (!second_header)
            lsx_report("Requested to swap bytes so writing RIFX header");
        lsx_writes(ft, "RIFX");
    }
    else
        lsx_writes(ft, "RIFF");
    lsx_writedw(ft, wRiffLength);
    lsx_writes(ft, "WAVE");
    lsx_writes(ft, "fmt ");
    lsx_writedw(ft, wFmtSize);
    lsx_writew(ft, isExtensible ? WAVE_FORMAT_EXTENSIBLE : wFormatTag);
    lsx_writew(ft, wChannels);
    lsx_writedw(ft, dwSamplesPerSecond);
    lsx_writedw(ft, dwAvgBytesPerSec);
    lsx_writew(ft, wBlockAlign);
    lsx_writew(ft, wBitsPerSample); /* end info common to all fmts */

    if (isExtensible) {
      uint32_t dwChannelMask=0;  /* unassigned speaker mapping by default */
      static unsigned char const guids[][14] = {
        "\x00\x00\x00\x00\x10\x00\x80\x00\x00\xAA\x00\x38\x9B\x71",  /* wav */
        "\x00\x00\x21\x07\xd3\x11\x86\x44\xc8\xc1\xca\x00\x00\x00"}; /* amb */

      /* if not amb, assume most likely channel masks from number of channels; not
       * ideal solution, but will make files playable in many/most situations
       */
      if (strcmp(ft->filetype, "amb")) {
        if      (wChannels == 1) dwChannelMask = 0x4;     /* 1 channel (mono) = FC */
        else if (wChannels == 2) dwChannelMask = 0x3;     /* 2 channels (stereo) = FL, FR */
        else if (wChannels == 4) dwChannelMask = 0x33;    /* 4 channels (quad) = FL, FR, BL, BR */
        else if (wChannels == 6) dwChannelMask = 0x3F;    /* 6 channels (5.1) = FL, FR, FC, LF, BL, BR */
        else if (wChannels == 8) dwChannelMask = 0x63F;   /* 8 channels (7.1) = FL, FR, FC, LF, BL, BR, SL, SR */
      }
 
      lsx_writew(ft, 22);
      lsx_writew(ft, wBitsPerSample); /* No padding in container */
      lsx_writedw(ft, dwChannelMask); /* Speaker mapping is something reasonable */
      lsx_writew(ft, wFormatTag);
      lsx_writebuf(ft, guids[!strcmp(ft->filetype, "amb")], (size_t)14);
    }
    else
    /* if not PCM, we need to write out wExtSize even if wExtSize=0 */
    if (wFormatTag != WAVE_FORMAT_PCM)
        lsx_writew(ft,wExtSize);

    switch (wFormatTag)
    {
        int i;
        case WAVE_FORMAT_IMA_ADPCM:
        lsx_writew(ft, wSamplesPerBlock);
        break;
        case WAVE_FORMAT_ADPCM:
        lsx_writew(ft, wSamplesPerBlock);
        lsx_writew(ft, 7); /* nCoefs */
        for (i=0; i<7; i++) {
            lsx_writew(ft, (uint16_t)(lsx_ms_adpcm_i_coef[i][0]));
            lsx_writew(ft, (uint16_t)(lsx_ms_adpcm_i_coef[i][1]));
        }
        break;
        case WAVE_FORMAT_GSM610:
        lsx_writew(ft, wSamplesPerBlock);
        break;
        default:
        break;
    }

    /* if not PCM, write the 'fact' chunk */
    if (isExtensible || wFormatTag != WAVE_FORMAT_PCM){
        lsx_writes(ft, "fact");
        lsx_writedw(ft,dwFactSize);
        lsx_writedw(ft,dwSamplesWritten);
    }

    lsx_writes(ft, "data");
    lsx_writedw(ft, dwDataLength);               /* data chunk size */

    if (!second_header) {
        lsx_debug("Writing Wave file: %s format, %d channel%s, %d samp/sec",
                wav_format_str(wFormatTag), wChannels,
                wChannels == 1 ? "" : "s", dwSamplesPerSecond);
        lsx_debug("        %d byte/sec, %d block align, %d bits/samp",
                dwAvgBytesPerSec, wBlockAlign, wBitsPerSample);
    } else {
        lsx_debug("Finished writing Wave file, %u data bytes %lu samples",
                dwDataLength, (unsigned long)wav->numSamples);
        if (wFormatTag == WAVE_FORMAT_GSM610){
            lsx_debug("GSM6.10 format: %li blocks %u padded samples %u padded data bytes",
                    blocksWritten, dwSamplesWritten, dwDataLength);
            if (wav->gsmbytecount != dwDataLength)
                lsx_warn("help ! internal inconsistency - data_written %u gsmbytecount %lu",
                        dwDataLength, (unsigned long)wav->gsmbytecount);

        }
    }
    return SOX_SUCCESS;
}

static size_t write_samples(sox_format_t * ft, const sox_sample_t *buf, size_t len)
{
        priv_t *   wav = (priv_t *) ft->priv;
        ptrdiff_t total_len = len;

        ft->sox_errno = SOX_SUCCESS;

        switch (wav->formatTag)
        {
        case WAVE_FORMAT_IMA_ADPCM:
        case WAVE_FORMAT_ADPCM:
            while (len>0) {
                short *p = wav->samplePtr;
                short *top = wav->sampleTop;

                if (top>p+len) top = p+len;
                len -= top-p; /* update residual len */
                while (p < top)
                   *p++ = (*buf++) >> 16;

                wav->samplePtr = p;
                if (p == wav->sampleTop)
                    xxxAdpcmWriteBlock(ft);

            }
            return total_len - len;
            break;

        case WAVE_FORMAT_GSM610:
            len = wavgsmwrite(ft, buf, len);
            wav->numSamples += (len/ft->signal.channels);
            return len;
            break;

        default:
            len = lsx_rawwrite(ft, buf, len);
            wav->numSamples += (len/ft->signal.channels);
            return len;
        }
}

static int stopwrite(sox_format_t * ft)
{
        priv_t *   wav = (priv_t *) ft->priv;

        ft->sox_errno = SOX_SUCCESS;


        /* Call this to flush out any remaining data. */
        switch (wav->formatTag)
        {
        case WAVE_FORMAT_IMA_ADPCM:
        case WAVE_FORMAT_ADPCM:
            xxxAdpcmWriteBlock(ft);
            break;
        case WAVE_FORMAT_GSM610:
            wavgsmstopwrite(ft);
            break;
        }

        /* Add a pad byte if the number of data bytes is odd.
           See wavwritehdr() above for the calculation. */
        if (wav->formatTag != WAVE_FORMAT_GSM610)
          lsx_padbytes(ft, (size_t)((wav->numSamples + wav->samplesPerBlock - 1)/wav->samplesPerBlock*wav->blockAlign) % 2);

        free(wav->packet);
        free(wav->samples);
        free(wav->lsx_ms_adpcm_i_coefs);

        /* All samples are already written out. */
        /* If file header needs fixing up, for example it needs the */
        /* the number of samples in a field, seek back and write them here. */
        if (ft->signal.length && wav->numSamples <= 0xffffffff && 
            wav->numSamples == ft->signal.length)
          return SOX_SUCCESS;
        if (!ft->seekable)
          return SOX_EOF;

        if (lsx_seeki(ft, (off_t)0, SEEK_SET) != 0)
        {
                lsx_fail_errno(ft,SOX_EOF,"Can't rewind output file to rewrite .wav header.");
                return SOX_EOF;
        }

        return (wavwritehdr(ft, 1));
}

/*
 * Return a string corresponding to the wave format type.
 */
static char *wav_format_str(unsigned wFormatTag)
{
        switch (wFormatTag)
        {
                case WAVE_FORMAT_UNKNOWN:
                        return "Microsoft Official Unknown";
                case WAVE_FORMAT_PCM:
                        return "Microsoft PCM";
                case WAVE_FORMAT_ADPCM:
                        return "Microsoft ADPCM";
                case WAVE_FORMAT_IEEE_FLOAT:
                       return "IEEE Float";
                case WAVE_FORMAT_ALAW:
                        return "Microsoft A-law";
                case WAVE_FORMAT_MULAW:
                        return "Microsoft U-law";
                case WAVE_FORMAT_OKI_ADPCM:
                        return "OKI ADPCM format.";
                case WAVE_FORMAT_IMA_ADPCM:
                        return "IMA ADPCM";
                case WAVE_FORMAT_DIGISTD:
                        return "Digistd format.";
                case WAVE_FORMAT_DIGIFIX:
                        return "Digifix format.";
                case WAVE_FORMAT_DOLBY_AC2:
                        return "Dolby AC2";
                case WAVE_FORMAT_GSM610:
                        return "GSM 6.10";
                case WAVE_FORMAT_ROCKWELL_ADPCM:
                        return "Rockwell ADPCM";
                case WAVE_FORMAT_ROCKWELL_DIGITALK:
                        return "Rockwell DIGITALK";
                case WAVE_FORMAT_G721_ADPCM:
                        return "G.721 ADPCM";
                case WAVE_FORMAT_G728_CELP:
                        return "G.728 CELP";
                case WAVE_FORMAT_MPEG:
                        return "MPEG";
                case WAVE_FORMAT_MPEGLAYER3:
                        return "MPEG Layer 3";
                case WAVE_FORMAT_G726_ADPCM:
                        return "G.726 ADPCM";
                case WAVE_FORMAT_G722_ADPCM:
                        return "G.722 ADPCM";
                default:
                        return "Unknown";
        }
}

static int seek(sox_format_t * ft, uint64_t offset)
{
  priv_t *   wav = (priv_t *) ft->priv;

  if (ft->encoding.bits_per_sample & 7)
    lsx_fail_errno(ft, SOX_ENOTSUP, "seeking not supported with this encoding");
  else if (wav->formatTag == WAVE_FORMAT_GSM610) {
    int alignment;
    size_t gsmoff;

    /* rounding bytes to blockAlign so that we
     * don't have to decode partial block. */
    gsmoff = offset * wav->blockAlign / wav->samplesPerBlock +
             wav->blockAlign * ft->signal.channels / 2;
    gsmoff -= gsmoff % (wav->blockAlign * ft->signal.channels);

    ft->sox_errno = lsx_seeki(ft, (off_t)(gsmoff + wav->dataStart), SEEK_SET);
    if (ft->sox_errno == SOX_SUCCESS) {
      /* offset is in samples */
      uint64_t new_offset = offset;
      alignment = offset % wav->samplesPerBlock;
      if (alignment != 0)
          new_offset += (wav->samplesPerBlock - alignment);
      wav->numSamples = ft->signal.length - (new_offset / ft->signal.channels);
    }
  } else {
    double wide_sample = offset - (offset % ft->signal.channels);
    double to_d = wide_sample * ft->encoding.bits_per_sample / 8;
    off_t to = to_d;
    ft->sox_errno = (to != to_d)? SOX_EOF : lsx_seeki(ft, (off_t)wav->dataStart + (off_t)to, SEEK_SET);
    if (ft->sox_errno == SOX_SUCCESS)
      wav->numSamples -= (size_t)wide_sample / ft->signal.channels;
  }

  return ft->sox_errno;
}

LSX_FORMAT_HANDLER(wav)
{
  static char const * const names[] = {"wav", "wavpcm", "amb", NULL};
  static unsigned const write_encodings[] = {
    SOX_ENCODING_SIGN2, 16, 24, 32, 0,
    SOX_ENCODING_UNSIGNED, 8, 0,
    SOX_ENCODING_ULAW, 8, 0,
    SOX_ENCODING_ALAW, 8, 0,
    SOX_ENCODING_GSM, 0,
    SOX_ENCODING_MS_ADPCM, 4, 0,
    SOX_ENCODING_IMA_ADPCM, 4, 0,
    SOX_ENCODING_FLOAT, 32, 64, 0,
    0};
  static sox_format_handler_t const handler = {SOX_LIB_VERSION_CODE,
    "Microsoft audio format", names, SOX_FILE_LIT_END,
    startread, read_samples, stopread,
    startwrite, write_samples, stopwrite,
    seek, write_encodings, NULL, sizeof(priv_t)
  };
  return &handler;
}

debug log:

solving f868dab4b294 ...
found f868dab4b294 in https://public-inbox.org/sox-devel/20180427235359.7497-1-mans@mansr.com/
found 3b07e5e25fd3 in https://public-inbox.org/sox-devel/20180427175056.3552-1-mans@mansr.com/
found 5202556c0e31 in https://80x24.org/mirrors/sox.git
preparing index
index prepared:
100644 5202556c0e31906046fd71f5ee56803a9f2df90c	src/wav.c

applying [1/2] https://public-inbox.org/sox-devel/20180427175056.3552-1-mans@mansr.com/
diff --git a/src/wav.c b/src/wav.c
index 5202556c0e31..3b07e5e25fd3 100644


applying [2/2] https://public-inbox.org/sox-devel/20180427235359.7497-1-mans@mansr.com/
diff --git a/src/wav.c b/src/wav.c
index 3b07e5e25fd3..f868dab4b294 100644

Checking patch src/wav.c...
Applied patch src/wav.c cleanly.
Checking patch src/wav.c...
Applied patch src/wav.c cleanly.

index at:
100644 f868dab4b2942cd57013005db04cb57c72b6b68b	src/wav.c

(*) Git path names are given by the tree(s) the blob belongs to.
    Blobs themselves have no identifier aside from the hash of its contents.^

Code repositories for project(s) associated with this public inbox

	https://80x24.org/mirrors/sox.git

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).