Fri Jul 15 2011 11:58:12

Asterisk developer's documentation


format_wav.c
Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2005, Digium, Inc.
00005  *
00006  * Mark Spencer <markster@digium.com>
00007  *
00008  * See http://www.asterisk.org for more information about
00009  * the Asterisk project. Please do not directly contact
00010  * any of the maintainers of this project for assistance;
00011  * the project provides a web site, mailing lists and IRC
00012  * channels for your use.
00013  *
00014  * This program is free software, distributed under the terms of
00015  * the GNU General Public License Version 2. See the LICENSE file
00016  * at the top of the source tree.
00017  */
00018 
00019 /*! \file
00020  *
00021  * \brief Work with WAV in the proprietary Microsoft format.
00022  * Microsoft WAV format (8000hz Signed Linear)
00023  * \arg File name extension: wav (lower case)
00024  * \ingroup formats
00025  */
00026  
00027 #include "asterisk.h"
00028 
00029 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 315258 $")
00030 
00031 #include "asterisk/mod_format.h"
00032 #include "asterisk/module.h"
00033 #include "asterisk/endian.h"
00034 
00035 /* Some Ideas for this code came from makewave.c by Jeffrey Chilton */
00036 
00037 /* Portions of the conversion code are by guido@sienanet.it */
00038 
00039 #define  WAV_BUF_SIZE   320
00040 
00041 struct wav_desc { /* format-specific parameters */
00042    int bytes;
00043    int lasttimeout;
00044    int maxlen;
00045    struct timeval last;
00046 };
00047 
00048 #define BLOCKSIZE 160
00049 
00050 #if __BYTE_ORDER == __LITTLE_ENDIAN
00051 #define htoll(b) (b)
00052 #define htols(b) (b)
00053 #define ltohl(b) (b)
00054 #define ltohs(b) (b)
00055 #else
00056 #if __BYTE_ORDER == __BIG_ENDIAN
00057 #define htoll(b)  \
00058           (((((b)      ) & 0xFF) << 24) | \
00059           ((((b) >>  8) & 0xFF) << 16) | \
00060          ((((b) >> 16) & 0xFF) <<  8) | \
00061          ((((b) >> 24) & 0xFF)      ))
00062 #define htols(b) \
00063           (((((b)      ) & 0xFF) << 8) | \
00064          ((((b) >> 8) & 0xFF)      ))
00065 #define ltohl(b) htoll(b)
00066 #define ltohs(b) htols(b)
00067 #else
00068 #error "Endianess not defined"
00069 #endif
00070 #endif
00071 
00072 
00073 static int check_header_fmt(FILE *f, int hsize)
00074 {
00075    short format, chans, bysam, bisam;
00076    int bysec;
00077    int freq;
00078    if (hsize < 16) {
00079       ast_log(LOG_WARNING, "Unexpected header size %d\n", ltohl(hsize));
00080       return -1;
00081    }
00082    if (fread(&format, 1, 2, f) != 2) {
00083       ast_log(LOG_WARNING, "Read failed (format)\n");
00084       return -1;
00085    }
00086    if (ltohs(format) != 1) {
00087       ast_log(LOG_WARNING, "Not a wav file %d\n", ltohs(format));
00088       return -1;
00089    }
00090    if (fread(&chans, 1, 2, f) != 2) {
00091       ast_log(LOG_WARNING, "Read failed (format)\n");
00092       return -1;
00093    }
00094    if (ltohs(chans) != 1) {
00095       ast_log(LOG_WARNING, "Not in mono %d\n", ltohs(chans));
00096       return -1;
00097    }
00098    if (fread(&freq, 1, 4, f) != 4) {
00099       ast_log(LOG_WARNING, "Read failed (freq)\n");
00100       return -1;
00101    }
00102    if (ltohl(freq) != DEFAULT_SAMPLE_RATE) {
00103       ast_log(LOG_WARNING, "Unexpected frequency %d\n", ltohl(freq));
00104       return -1;
00105    }
00106    /* Ignore the byte frequency */
00107    if (fread(&bysec, 1, 4, f) != 4) {
00108       ast_log(LOG_WARNING, "Read failed (BYTES_PER_SECOND)\n");
00109       return -1;
00110    }
00111    /* Check bytes per sample */
00112    if (fread(&bysam, 1, 2, f) != 2) {
00113       ast_log(LOG_WARNING, "Read failed (BYTES_PER_SAMPLE)\n");
00114       return -1;
00115    }
00116    if (ltohs(bysam) != 2) {
00117       ast_log(LOG_WARNING, "Can only handle 16bits per sample: %d\n", ltohs(bysam));
00118       return -1;
00119    }
00120    if (fread(&bisam, 1, 2, f) != 2) {
00121       ast_log(LOG_WARNING, "Read failed (Bits Per Sample): %d\n", ltohs(bisam));
00122       return -1;
00123    }
00124    /* Skip any additional header */
00125    if (fseek(f,ltohl(hsize)-16,SEEK_CUR) == -1 ) {
00126       ast_log(LOG_WARNING, "Failed to skip remaining header bytes: %d\n", ltohl(hsize)-16 );
00127       return -1;
00128    }
00129    return 0;
00130 }
00131 
00132 static int check_header(FILE *f)
00133 {
00134    int type, size, formtype;
00135    int data;
00136    if (fread(&type, 1, 4, f) != 4) {
00137       ast_log(LOG_WARNING, "Read failed (type)\n");
00138       return -1;
00139    }
00140    if (fread(&size, 1, 4, f) != 4) {
00141       ast_log(LOG_WARNING, "Read failed (size)\n");
00142       return -1;
00143    }
00144    size = ltohl(size);
00145    if (fread(&formtype, 1, 4, f) != 4) {
00146       ast_log(LOG_WARNING, "Read failed (formtype)\n");
00147       return -1;
00148    }
00149    if (memcmp(&type, "RIFF", 4)) {
00150       ast_log(LOG_WARNING, "Does not begin with RIFF\n");
00151       return -1;
00152    }
00153    if (memcmp(&formtype, "WAVE", 4)) {
00154       ast_log(LOG_WARNING, "Does not contain WAVE\n");
00155       return -1;
00156    }
00157    /* Skip any facts and get the first data block */
00158    for(;;)
00159    { 
00160       char buf[4];
00161        
00162        /* Begin data chunk */
00163        if (fread(&buf, 1, 4, f) != 4) {
00164          ast_log(LOG_WARNING, "Read failed (block header format)\n");
00165          return -1;
00166        }
00167        /* Data has the actual length of data in it */
00168        if (fread(&data, 1, 4, f) != 4) {
00169          ast_log(LOG_WARNING, "Read failed (block '%.4s' header length)\n", buf);
00170          return -1;
00171        }
00172        data = ltohl(data);
00173       if (memcmp(&buf, "fmt ", 4) == 0) {
00174          if (check_header_fmt(f, data))
00175             return -1;
00176          continue;
00177       }
00178        if(memcmp(buf, "data", 4) == 0 ) 
00179          break;
00180       ast_log(LOG_DEBUG, "Skipping unknown block '%.4s'\n", buf);
00181        if (fseek(f,data,SEEK_CUR) == -1 ) {
00182          ast_log(LOG_WARNING, "Failed to skip '%.4s' block: %d\n", buf, data);
00183          return -1;
00184        }
00185    }
00186 #if 0
00187    curpos = lseek(fd, 0, SEEK_CUR);
00188    truelength = lseek(fd, 0, SEEK_END);
00189    lseek(fd, curpos, SEEK_SET);
00190    truelength -= curpos;
00191 #endif   
00192    return data;
00193 }
00194 
00195 static int update_header(FILE *f)
00196 {
00197    off_t cur,end;
00198    int datalen,filelen,bytes;
00199    
00200    cur = ftello(f);
00201    fseek(f, 0, SEEK_END);
00202    end = ftello(f);
00203    /* data starts 44 bytes in */
00204    bytes = end - 44;
00205    datalen = htoll(bytes);
00206    /* chunk size is bytes of data plus 36 bytes of header */
00207    filelen = htoll(36 + bytes);
00208    
00209    if (cur < 0) {
00210       ast_log(LOG_WARNING, "Unable to find our position\n");
00211       return -1;
00212    }
00213    if (fseek(f, 4, SEEK_SET)) {
00214       ast_log(LOG_WARNING, "Unable to set our position\n");
00215       return -1;
00216    }
00217    if (fwrite(&filelen, 1, 4, f) != 4) {
00218       ast_log(LOG_WARNING, "Unable to set write file size\n");
00219       return -1;
00220    }
00221    if (fseek(f, 40, SEEK_SET)) {
00222       ast_log(LOG_WARNING, "Unable to set our position\n");
00223       return -1;
00224    }
00225    if (fwrite(&datalen, 1, 4, f) != 4) {
00226       ast_log(LOG_WARNING, "Unable to set write datalen\n");
00227       return -1;
00228    }
00229    if (fseeko(f, cur, SEEK_SET)) {
00230       ast_log(LOG_WARNING, "Unable to return to position\n");
00231       return -1;
00232    }
00233    return 0;
00234 }
00235 
00236 static int write_header(FILE *f)
00237 {
00238    unsigned int hz=htoll(8000);
00239    unsigned int bhz = htoll(16000);
00240    unsigned int hs = htoll(16);
00241    unsigned short fmt = htols(1);
00242    unsigned short chans = htols(1);
00243    unsigned short bysam = htols(2);
00244    unsigned short bisam = htols(16);
00245    unsigned int size = htoll(0);
00246    /* Write a wav header, ignoring sizes which will be filled in later */
00247    fseek(f,0,SEEK_SET);
00248    if (fwrite("RIFF", 1, 4, f) != 4) {
00249       ast_log(LOG_WARNING, "Unable to write header\n");
00250       return -1;
00251    }
00252    if (fwrite(&size, 1, 4, f) != 4) {
00253       ast_log(LOG_WARNING, "Unable to write header\n");
00254       return -1;
00255    }
00256    if (fwrite("WAVEfmt ", 1, 8, f) != 8) {
00257       ast_log(LOG_WARNING, "Unable to write header\n");
00258       return -1;
00259    }
00260    if (fwrite(&hs, 1, 4, f) != 4) {
00261       ast_log(LOG_WARNING, "Unable to write header\n");
00262       return -1;
00263    }
00264    if (fwrite(&fmt, 1, 2, f) != 2) {
00265       ast_log(LOG_WARNING, "Unable to write header\n");
00266       return -1;
00267    }
00268    if (fwrite(&chans, 1, 2, f) != 2) {
00269       ast_log(LOG_WARNING, "Unable to write header\n");
00270       return -1;
00271    }
00272    if (fwrite(&hz, 1, 4, f) != 4) {
00273       ast_log(LOG_WARNING, "Unable to write header\n");
00274       return -1;
00275    }
00276    if (fwrite(&bhz, 1, 4, f) != 4) {
00277       ast_log(LOG_WARNING, "Unable to write header\n");
00278       return -1;
00279    }
00280    if (fwrite(&bysam, 1, 2, f) != 2) {
00281       ast_log(LOG_WARNING, "Unable to write header\n");
00282       return -1;
00283    }
00284    if (fwrite(&bisam, 1, 2, f) != 2) {
00285       ast_log(LOG_WARNING, "Unable to write header\n");
00286       return -1;
00287    }
00288    if (fwrite("data", 1, 4, f) != 4) {
00289       ast_log(LOG_WARNING, "Unable to write header\n");
00290       return -1;
00291    }
00292    if (fwrite(&size, 1, 4, f) != 4) {
00293       ast_log(LOG_WARNING, "Unable to write header\n");
00294       return -1;
00295    }
00296    return 0;
00297 }
00298 
00299 static int wav_open(struct ast_filestream *s)
00300 {
00301    /* We don't have any header to read or anything really, but
00302       if we did, it would go here.  We also might want to check
00303       and be sure it's a valid file.  */
00304    struct wav_desc *tmp = (struct wav_desc *)s->_private;
00305    if ((tmp->maxlen = check_header(s->f)) < 0)
00306       return -1;
00307    return 0;
00308 }
00309 
00310 static int wav_rewrite(struct ast_filestream *s, const char *comment)
00311 {
00312    /* We don't have any header to read or anything really, but
00313       if we did, it would go here.  We also might want to check
00314       and be sure it's a valid file.  */
00315 
00316    if (write_header(s->f))
00317       return -1;
00318    return 0;
00319 }
00320 
00321 static void wav_close(struct ast_filestream *s)
00322 {
00323    char zero = 0;
00324    struct wav_desc *fs = (struct wav_desc *)s->_private;
00325 
00326    if (s->filename) {
00327       update_header(s->f);
00328    }
00329 
00330    /* Pad to even length */
00331    if (fs->bytes & 0x1) {
00332       if (!fwrite(&zero, 1, 1, s->f)) {
00333          ast_log(LOG_WARNING, "fwrite() failed: %s\n", strerror(errno));
00334       }
00335    }
00336 }
00337 
00338 static struct ast_frame *wav_read(struct ast_filestream *s, int *whennext)
00339 {
00340    int res;
00341    int samples;   /* actual samples read */
00342 #if __BYTE_ORDER == __BIG_ENDIAN
00343    int x;
00344 #endif
00345    short *tmp;
00346    int bytes = WAV_BUF_SIZE;  /* in bytes */
00347    off_t here;
00348    /* Send a frame from the file to the appropriate channel */
00349    struct wav_desc *fs = (struct wav_desc *)s->_private;
00350 
00351    here = ftello(s->f);
00352    if (fs->maxlen - here < bytes)      /* truncate if necessary */
00353       bytes = fs->maxlen - here;
00354    if (bytes < 0)
00355       bytes = 0;
00356 /*    ast_debug(1, "here: %d, maxlen: %d, bytes: %d\n", here, s->maxlen, bytes); */
00357    s->fr.frametype = AST_FRAME_VOICE;
00358    s->fr.subclass = AST_FORMAT_SLINEAR;
00359    s->fr.mallocd = 0;
00360    AST_FRAME_SET_BUFFER(&s->fr, s->buf, AST_FRIENDLY_OFFSET, bytes);
00361    
00362    if ( (res = fread(s->fr.data.ptr, 1, s->fr.datalen, s->f)) <= 0 ) {
00363       if (res)
00364          ast_log(LOG_WARNING, "Short read (%d) (%s)!\n", res, strerror(errno));
00365       return NULL;
00366    }
00367    s->fr.datalen = res;
00368    s->fr.samples = samples = res / 2;
00369 
00370    tmp = (short *)(s->fr.data.ptr);
00371 #if __BYTE_ORDER == __BIG_ENDIAN
00372    /* file format is little endian so we need to swap */
00373    for( x = 0; x < samples; x++)
00374       tmp[x] = (tmp[x] << 8) | ((tmp[x] & 0xff00) >> 8);
00375 #endif
00376 
00377    *whennext = samples;
00378    return &s->fr;
00379 }
00380 
00381 static int wav_write(struct ast_filestream *fs, struct ast_frame *f)
00382 {
00383 #if __BYTE_ORDER == __BIG_ENDIAN
00384    int x;
00385    short tmp[8000], *tmpi;
00386 #endif
00387    struct wav_desc *s = (struct wav_desc *)fs->_private;
00388    int res;
00389 
00390    if (f->frametype != AST_FRAME_VOICE) {
00391       ast_log(LOG_WARNING, "Asked to write non-voice frame!\n");
00392       return -1;
00393    }
00394    if (f->subclass != AST_FORMAT_SLINEAR) {
00395       ast_log(LOG_WARNING, "Asked to write non-SLINEAR frame (%d)!\n", f->subclass);
00396       return -1;
00397    }
00398    if (!f->datalen)
00399       return -1;
00400 
00401 #if __BYTE_ORDER == __BIG_ENDIAN
00402    /* swap and write */
00403    if (f->datalen > sizeof(tmp)) {
00404       ast_log(LOG_WARNING, "Data length is too long\n");
00405       return -1;
00406    }
00407    tmpi = f->data.ptr;
00408    for (x=0; x < f->datalen/2; x++) 
00409       tmp[x] = (tmpi[x] << 8) | ((tmpi[x] & 0xff00) >> 8);
00410 
00411    if ((res = fwrite(tmp, 1, f->datalen, fs->f)) != f->datalen ) {
00412 #else
00413    /* just write */
00414    if ((res = fwrite(f->data.ptr, 1, f->datalen, fs->f)) != f->datalen ) {
00415 #endif
00416       ast_log(LOG_WARNING, "Bad write (%d): %s\n", res, strerror(errno));
00417       return -1;
00418    }
00419 
00420    s->bytes += f->datalen;
00421       
00422    return 0;
00423 
00424 }
00425 
00426 static int wav_seek(struct ast_filestream *fs, off_t sample_offset, int whence)
00427 {
00428    off_t min, max, cur, offset = 0, samples;
00429 
00430    samples = sample_offset * 2; /* SLINEAR is 16 bits mono, so sample_offset * 2 = bytes */
00431    min = 44; /* wav header is 44 bytes */
00432    cur = ftello(fs->f);
00433    fseeko(fs->f, 0, SEEK_END);
00434    max = ftello(fs->f);
00435    if (whence == SEEK_SET)
00436       offset = samples + min;
00437    else if (whence == SEEK_CUR || whence == SEEK_FORCECUR)
00438       offset = samples + cur;
00439    else if (whence == SEEK_END)
00440       offset = max - samples;
00441         if (whence != SEEK_FORCECUR) {
00442       offset = (offset > max)?max:offset;
00443    }
00444    /* always protect the header space. */
00445    offset = (offset < min)?min:offset;
00446    return fseeko(fs->f, offset, SEEK_SET);
00447 }
00448 
00449 static int wav_trunc(struct ast_filestream *fs)
00450 {
00451    if (ftruncate(fileno(fs->f), ftello(fs->f)))
00452       return -1;
00453    return update_header(fs->f);
00454 }
00455 
00456 static off_t wav_tell(struct ast_filestream *fs)
00457 {
00458    off_t offset;
00459    offset = ftello(fs->f);
00460    /* subtract header size to get samples, then divide by 2 for 16 bit samples */
00461    return (offset - 44)/2;
00462 }
00463 
00464 static const struct ast_format wav_f = {
00465    .name = "wav",
00466    .exts = "wav",
00467    .format = AST_FORMAT_SLINEAR,
00468    .open =  wav_open,
00469    .rewrite = wav_rewrite,
00470    .write = wav_write,
00471    .seek = wav_seek,
00472    .trunc = wav_trunc,
00473    .tell =  wav_tell,
00474    .read = wav_read,
00475    .close = wav_close,
00476    .buf_size = WAV_BUF_SIZE + AST_FRIENDLY_OFFSET,
00477    .desc_size = sizeof(struct wav_desc),
00478 };
00479 
00480 static int load_module(void)
00481 {
00482    if (ast_format_register(&wav_f))
00483       return AST_MODULE_LOAD_FAILURE;
00484    return AST_MODULE_LOAD_SUCCESS;
00485 }
00486 
00487 static int unload_module(void)
00488 {
00489    return ast_format_unregister(wav_f.name);
00490 }  
00491 
00492 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Microsoft WAV format (8000Hz Signed Linear)",
00493    .load = load_module,
00494    .unload = unload_module,
00495    .load_pri = 10,
00496 );