File: aiff_header.C

package info (click to toggle)
mixviews 1.20-10.1
  • links: PTS
  • area: main
  • in suites: potato
  • size: 2,928 kB
  • ctags: 5,960
  • sloc: cpp: 32,879; ansic: 2,110; makefile: 445; sh: 17
file content (485 lines) | stat: -rw-r--r-- 15,972 bytes parent folder | download | duplicates (2)
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
// aiff_header.C

/******************************************************************************
 *
 *  MiXViews - an X window system based sound & data editor/processor
 *
 *  Copyright (c) 1993, 1994 Regents of the University of California
 *
 *  Author:     Douglas Scott
 *  Date:       December 13, 1994
 *
 *  Permission to use, copy and modify this software and its documentation
 *  for research and/or educational purposes and without fee is hereby granted,
 *  provided that the above copyright notice appear in all copies and that
 *  both that copyright notice and this permission notice appear in
 *  supporting documentation. The author reserves the right to distribute this
 *  software and its documentation.  The University of California and the author
 *  make no representations about the suitability of this software for any 
 *  purpose, and in no event shall University of California be liable for any
 *  damage, loss of data, or profits resulting from its use.
 *  It is provided "as is" without express or implied warranty.
 *
 ******************************************************************************/


#ifdef __GNUG__
#pragma implementation
#endif

#include <assert.h>
#include <stdarg.h>
#include "localdefs.h"
#include "application.h"
#include "aiff_header.h"
#include "comment.h"
#include "datafile.h"
#include "typeconvert.h"

// this file contains two completely separate implementations of the
// AIFFSoundHeader class -- one for SGI machines and one for all others

#ifdef sgi

AIFFSoundHeader::AIFFSoundHeader(DataType format, int rate, int chans,
    double peak, AFtype compression) : SoundHeader(format, rate, chans, peak, 0),
        audioFileHandle(nil), compression_type(compression) {
    header_type = Aifc;
    AFseterrorhandler((AFerrfunc) &AIFFSoundHeader::errorHandler);    
}

AIFFSoundHeader::~AIFFSoundHeader() {
    if(audioFileHandle) AFclosefile(audioFileHandle);
}

AFtype
AIFFSoundHeader::frameCount() {
        return (audioFileHandle) ? AFgetframecnt(audioFileHandle, AF_DEFAULT_TRACK) : 0;
}

int
AIFFSoundHeader::readInfo(DataFile* file) {
    BUG("AIFFSoundHeader::readInfo()");
    int fd = file->fdesc();
    AFtype fileType;
    if ((fileType = AFidentifyfd(fd)) < 0) {
	if (!Application::globalResourceIsTrue("ReadRawFiles"))
	    Application::alert("SoundHeader::readInfo: Sound file is not an AIFF-C or AIFF file.");
    }
    else if((audioFileHandle = AFopenfd(fd, "r", AF_NULL_FILESETUP))
            != AF_NULL_FILEHANDLE) {
        AFtype sampType, bitsPerSamp;
        if (fileType == AF_FILE_MPEG1BITSTREAM)
            header_type = Mpeg1;
        AFgetsampfmt(audioFileHandle, AF_DEFAULT_TRACK, &sampType, &bitsPerSamp);
        compression_type = AFgetcompression(audioFileHandle, AF_DEFAULT_TRACK);
        data_type = (bitsPerSamp <= 8) ? SignedCharData
            : (bitsPerSamp <= 16) ? ShortData :
            (bitsPerSamp <= 32) ? IntData : NoData;
        nchans = int(AFgetchannels(audioFileHandle, AF_DEFAULT_TRACK));
        samprate = int(AFgetrate(audioFileHandle, AF_DEFAULT_TRACK));
        AFtype totalFrames = AFgetframecnt(audioFileHandle, AF_DEFAULT_TRACK);
        int totalSize = totalFrames * nchans * sampleSize();
        if(compression_type == AF_COMPRESSION_NONE && file->dataSize() < totalSize) {
            Application::alert("Warning:",
                "File size does not match header frame count.");
            totalSize = file->dataSize();
        }
        setDataSize(totalSize);
        setDataOffset(file->dataSize() - dataSize());
        return checkHeader();
    }
    return false;
}

int
AIFFSoundHeader::readComment(DataFile*) {
    AFtype* miscIDs = nil;
    AFtype numIDs = AFgetmiscids(audioFileHandle, miscIDs);    // get size
    miscIDs = new AFtype[numIDs];
    AFgetmiscids(audioFileHandle, miscIDs);                    // get actual IDs
    for(int idx=0; idx < int(numIDs); idx++) {
        AFtype id = miscIDs[idx];
        AFtype chunkType = AFgetmisctype(audioFileHandle, id);
        // look for either annotation or author chunk, whichever comes first
        if(chunkType == AF_MISC_AIFF_ANNO || chunkType == AF_MISC_AIFF_AUTH) {
            AFtype chunkSize = AFgetmiscsize(audioFileHandle, id);
            char* buf = new char[chunkSize + 1];
            if(AFreadmisc(audioFileHandle, id, (void *) buf, chunkSize)
                    == chunkSize) {
                if(buf != nil)
                    setComment(buf);
            }
            delete [] buf;
            break;
        }
    }
    delete [] miscIDs;
    return true;
}

int
AIFFSoundHeader::seekInFile(DataFile*, int byteOffset) {
    AFtype frameOffset = byteOffset / (sampleSize() * nChans());
    return (AFseekframe(audioFileHandle, AF_DEFAULT_TRACK, frameOffset) >= 0);
}

int
AIFFSoundHeader::writeInfo(DataFile* file) {
    BUG("AIFFSoundHeader::writeInfo()");
    AFfilesetup fileSetup = AFnewfilesetup();
    AFinitfilefmt(fileSetup, AF_FILE_AIFFC);
    AFinitchannels(fileSetup, AF_DEFAULT_TRACK,  AFtype(nChans()));
    AFinitrate(fileSetup, AF_DEFAULT_TRACK, double(sampleRate()));
    DataType type = dataType();
    AFtype sampBits = (type == SignedCharData) ? 8 :
                    (type == MuLawData || type == ShortData) ? 16 : 32;
    AFinitcompression(fileSetup, AF_DEFAULT_TRACK,
        (type == MuLawData) ? AF_COMPRESSION_G711_ULAW : AF_COMPRESSION_NONE);
    AFinitsampfmt(fileSetup, AF_DEFAULT_TRACK, AF_SAMPFMT_TWOSCOMP, sampBits);
    // if comment is available, initialize for its addition to the file
    Comment* com = getComment();
    AFtype commLen = (com == nil) ? 0 : com->len() + 1;
    if(commLen > 1) {
        AFtype idlist[1];
        idlist[0] = 314159;
        AFinitmiscids(fileSetup, idlist, 1L);
        AFinitmisctype(fileSetup, idlist[0], AF_MISC_AIFF_ANNO);
        AFinitmiscsize(fileSetup, idlist[0], commLen);
    }
    // this will truncate file if it already exists
    int status = true;
    if((audioFileHandle = AFopenfd(file->fdesc(), "w", fileSetup)) == NULL) {
        Application::alert("SoundHeader::writeInfo: error in AFopenfd().");
        status = false;
    }
    AFfreefilesetup(fileSetup);
    return status;
}

int
AIFFSoundHeader::writeComment(DataFile *) {
    Comment* com = getComment();
    AFtype commLen = (com == nil) ? 0 : com->len() + 1;
    int status = true;
    if(commLen > 1) {
        if(AFwritemisc(audioFileHandle, 314159, (void *) ((char *) *com), commLen) != commLen)
            status = false;
    }
    return status;
}

// these return number of frames written

AFtype
AIFFSoundHeader::readSound(char** buffer, AFtype frames) {
    BUG("AIFFSoundHeader::readSound()");
    AFtype framesRead = 0;
    if(audioFileHandle != nil) {
        AFtype totalFrames = frameCount();
        AFtype readFrames = frames <= totalFrames ? frames : totalFrames;
        framesRead = AFreadframes(audioFileHandle, AF_DEFAULT_TRACK,
            *buffer, readFrames);
    }
    else
        Application::alert("AIFFSoundHeader::readSound:  null file handle");
    return framesRead;
};

AFtype
AIFFSoundHeader::writeSound(char* buffer, AFtype frames) {
    BUG("AIFFSoundHeader::writeSound()");
    AFtype framesWritten = 0;
    if(audioFileHandle != nil) {
        framesWritten = AFwriteframes(audioFileHandle, AF_DEFAULT_TRACK,
            buffer, frames);
        if(framesWritten > 0 && AFsyncfile(audioFileHandle) < 0) {
            Application::alert("AIFFSoundHeader::writeSound:  AFsyncfile error.");
            framesWritten = 0;
        }
    }
    else
        Application::alert("AIFFSoundHeader::readSound: null file pointer.");
    return framesWritten;
};

int
AIFFSoundHeader::checkHeader() {
    int status = Super::checkHeader();
    if(status)
        if(compression_type == AF_COMPRESSION_UNKNOWN) {
            Application::alert("checkHeader: unknown compression format.");
            status = false;
        }
    return status;
}

boolean
AIFFSoundHeader::isValid(DataType t) {
    return (t == SignedCharData || t == MuLawData
        || t == ShortData || t == IntData);
}

void
AIFFSoundHeader::errorHandler(MXINT32 arg1, const char* fmt, ...) {
    char string[256];
    va_list args;
    va_start(args, fmt);
    vsprintf(string, fmt, args);
    va_end(args);
#ifdef debug
    fprintf(stderr, "Error handler called: \"%s\"\n", string);
    fflush(stderr);
#endif
    Application::alert(string);
}

#else    /* sgi */

#include "valuesetter.h"

AIFFSoundHeader::AIFFSoundHeader(DataType format, int rate,
        int chans, double peak, AFtype compression)
        : SoundHeader(format, rate, chans, peak, FORM),
          compression_type(compression) {
    header_type = Aifc;
}

AIFFSoundHeader::~AIFFSoundHeader() {
}

int
AIFFSoundHeader::readInfo(DataFile* file) {
    file->seek(0);
    int status = false;
    char *errString = nil;
    MXINT32 formOffset = 0;
    MXINT32 blockSize = 0;
    int nsamps = 0;
    FormChunk formChunk;
    if (formChunk.read(file)) {
        if (!formChunk.isValid()) {
            Application::error("readInfo:", "Header form type is not AIFF or AIF-C.");
            goto Error;
        }
        boolean isAIFC = formChunk.isAIFC();
        MXINT32 totalSize = formChunk.size() + 8;
        StandardChunk chunk;
        MXINT32 chunkSize = 0;
        do {            // search for COMM chunk
            status = file->skip(chunkSize + odd(chunkSize)).good()
                && chunk.read(file);
            chunkSize = chunk.size();
        } while(status && !chunk.isA("COMM"));
        if(!status)    {    // reached EOF
            Application::error("readInfo:", "Missing common data chunk.");
            goto Error;
        }
        else {
            CommonData commonData(isAIFC);
            if(commonData.read(file))
                nsamps = parseCommonData(commonData);
        }
        chunkSize = 0;
        do {            // search for SSND chunk
            status = file->skip(chunkSize + odd(chunkSize)).good()
                && chunk.read(file);
            chunkSize = chunk.size();
        } while(status && !chunk.isA("SSND"));
        if(!status)    {    // reached EOF
            Application::error("readInfo:", "Missing sound data chunk.");
            goto Error;
        }
        else {
            setDataSize(chunkSize - 8);    // minus size of two MXINT32s
            SoundData soundData;
            if((status = soundData.read(file)) == true) {
                formOffset = soundData.offset;
                blockSize = soundData.blockSize;
            }
        }
        if (blockSize != 0)    {
            Application::alert("readInfo:", "Sound data chunk blocksize != 0.");
            status = false;
        }
        else {
            char msg[80];
            int computedSize = nsamps * nchans * sampleSize();
            if(dataSize() != computedSize) {
                sprintf(msg, "SSND chunksize (%d) != size from frame count (%d).",
                    dataSize(), computedSize);
                Application::alert("readInfo:", msg);
                setDataSize(computedSize);
            }
            else if(totalSize != file->dataSize()) {
                sprintf(msg, "Actual file size (%d) != header file size (%ld).",
                    file->dataSize(), totalSize);
                Application::alert("readInfo:", msg);
            }
            file->skip(formOffset);        // if any -- usually 0
            setDataOffset(int(file->tell()));
            status = true;
        }
    }
    else
        Application::error("readInfo:", "read error while reading FORM chunk.");
    Error: ;
    return status && checkHeader();
}

int
AIFFSoundHeader::parseCommonData(const AIFFSoundHeader::CommonData& commonData) {
    nchans = commonData.chans;
    compression_type = commonData.compression();
    switch (commonData.sampleSize) {
    case 8:
        data_type = (compression_type == AF_COMPRESSION_NONE) ?
            SignedCharData : MuLawData;
        break;
    case 16:
        data_type = ShortData;
        break;
    case 32:
        data_type = IntData;
        break;
    default:
        data_type = NoData;    // for now, nothing else allowed
        break;
    }; 
    samprate = int(float(commonData.rate));
    return int(commonData.frames);
}

int
AIFFSoundHeader::readComment(DataFile* file) {
    return true;
}

int
AIFFSoundHeader::writeInfo(DataFile* file) {
    static const MXINT32 headerLength = 4 + 12 + 8 + 38 + 8 + 8;
    file->seek(0);
    FormChunk formChunk(dataSize() + headerLength);
    int status = formChunk.write(file);
    FormatChunk formatChunk;
    FormatVersion formatVersion;
    status = status && formatChunk.write(file) && formatVersion.write(file);
    CommonChunk commonChunk;
    status = status && commonChunk.write(file);
    if(status) {
        CommonData common(
            true,                    // for now, write out AIF-C standard
            nChans(),
            dataSize() / (nChans() * sampleSize()),
            short(sampleSize() << 3),
            double(sampleRate())
        );
        status = common.write(file);
        SoundChunk soundChunk(dataSize());
        SoundData soundData;
        status = status && soundChunk.write(file) && soundData.write(file);
    }
    if(status == false)
        Application::error("AIFFSoundHeader::writeInfo:");
    return status;
}

int
AIFFSoundHeader::writeComment(DataFile* file) {
    return true;
}

int
AIFFSoundHeader::checkHeader() {
    int status = Super::checkHeader();
    if(status)
        if(compression_type != 0) {
            Application::alert("Cannot read compressed AIFC soundfiles on this platform.");
            status = false;
        }
    return status;
}

boolean
AIFFSoundHeader::isValid(DataType t) {
    return (t == SignedCharData || t == ShortData || t == IntData);
}

//********

ValueSetterBase**
AIFFSoundHeader::FormChunk::valueSetters() {
    static ValueSetterBase* setterList[NumElements + 1];
    delete setterList[0];
    setterList[0] = newValueSetter(&formType);
    return setterList;
}

int
AIFFSoundHeader::FormChunk::read(DataFile* file) {
    return StandardChunk::doRead(file, StandardChunk::valueSetters())
        && doRead(file, valueSetters());
}

int
AIFFSoundHeader::FormChunk::write(DataFile* file) {
    return doWrite(file, StandardChunk::valueSetters())
        && doWrite(file, valueSetters());
}

boolean
AIFFSoundHeader::FormChunk::isValid() {
    return isA("FORM")
        && (formType == "AIFF" || formType == "AIFC") && size() > 0;
}

ValueSetterBase**
AIFFSoundHeader::FormatVersion::valueSetters() {
    static ValueSetterBase* setterList[NumElements + 1];
    delete setterList[0];
    setterList[0] = newValueSetter(&timeStamp);
    return setterList;
}

ValueSetterBase**
AIFFSoundHeader::CommonData::valueSetters() {
    static ValueSetterBase* setterList[NumElements + 1];
    delete setterList[0];
    setterList[0] = newValueSetter(&chans);
    delete setterList[1];
    setterList[1] = newValueSetter(&frames);
    delete setterList[2];
    setterList[2] = newValueSetter(&sampleSize);
    delete setterList[3];
    setterList[3] = newValueSetter(&rate);
    delete setterList[4]; setterList[4] = nil;
    delete setterList[5]; setterList[5] = nil;
    if(isAIFC) {
        setterList[4] = newValueSetter(&compressionType);
        setterList[5] = newValueSetter(&compressionName);
    }
    return setterList;
}

ValueSetterBase**
AIFFSoundHeader::SoundData::valueSetters() {
    static ValueSetterBase* setterList[NumElements + 1];
    delete setterList[0];
    setterList[0] = newValueSetter(&offset);
    delete setterList[1];
    setterList[1] = newValueSetter(&blockSize);
    return setterList;
}

#endif    /* sgi */

// the rest are the same for both platforms

boolean
AIFFSoundHeader::isMagic() {
    return (magic() == FORM || magic() == MROF || magic() == MPEG1_MAGIC);
}

boolean
AIFFSoundHeader::magicIsSwapped() { return magic() == MROF; }