File: mp3.c

package info (click to toggle)
gjay 0.3.1-1
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 1,392 kB
  • ctags: 750
  • sloc: ansic: 7,123; sh: 4,351; makefile: 42; sed: 16
file content (556 lines) | stat: -rw-r--r-- 16,970 bytes parent folder | download
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
/*
 * GJay, copyright (c) 2002-3 Chuck Groom <cgroom@users.sourceforge.net>
 *       Copyright (c) 2010 Craig Small <csmall@enc.com.au>
 *
 * mp3.c: Functions for handling MP3 files and most MP3 data
 * structure manipulation.
 *
 * MP3 info manipulation taken from mp3info package's mp3tech.c, which is
 * copyright (C) 2000-2001  Cedric Tefft <cedric@earthling.net>, which is
 * in turn based in part on:
 *    MP3Info 0.5 by Ricardo Cerqueira <rmc@rccn.net>
 *    MP3Stat 0.9 by Ed Sweetman <safemode@voicenet.com> and 
 *     	             Johannes Overmann <overmann@iname.com>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 1, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 * USA
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "gjay.h"
#include "mp3.h"
#include "i18n.h"

/* MIN_CONSEC_GOOD_FRAMES defines how many consecutive valid MP3 frames
   we need to see before we decide we are looking at a real MP3 file */
#define MIN_CONSEC_GOOD_FRAMES 4
#define FRAME_HEADER_SIZE 4
#define MIN_FRAME_SIZE 21
#define NUM_SAMPLES 4
#define TEXT_FIELD_LEN  30
#define INT_FIELD_LEN   4

#define NUM_TAGS 16
#define TITLE_CHAR  "t"
#define ARTIST_CHAR "c"
#define ALBUM_CHAR  "a"
static char * id3_tag[NUM_TAGS] = {
    "TT2",  TITLE_CHAR,
    "TIT2", TITLE_CHAR,
    "TP1",  ARTIST_CHAR,
    "TPE1", ARTIST_CHAR,
    "TCM",  ARTIST_CHAR,
    "TCOM", ARTIST_CHAR,
    "TAL",  ALBUM_CHAR,
    "TALB", ALBUM_CHAR
};
    

int get_header(FILE *file,mp3header *header);
int frame_length(mp3header *header);
int header_layer(mp3header *h);
int header_bitrate(mp3header *h);
int sameConstant(mp3header *h1, mp3header *h2);
int get_id3(mp3info *mp3);
char *pad(char *string, int length);
char *unpad(char *string);
int write_tag(mp3info *mp3);
int header_frequency(mp3header *h);
char *header_emphasis(mp3header *h);
char *header_mode(mp3header *h);
int get_first_header(mp3info *mp3,long startpos);
int get_next_header(mp3info *mp3);


int layer_tab[4]= {0, 3, 2, 1};

int frequencies[3][4] = {
   {22050,24000,16000,50000},  /* MPEG 2.0 */
   {44100,48000,32000,50000},  /* MPEG 1.0 */
   {11025,12000,8000,50000}    /* MPEG 2.5 */
};

int bitrate[2][3][14] = { 
  { /* MPEG 2.0 */
    {32,48,56,64,80,96,112,128,144,160,176,192,224,256},  /* layer 1 */
    {8,16,24,32,40,48,56,64,80,96,112,128,144,160},       /* layer 2 */
    {8,16,24,32,40,48,56,64,80,96,112,128,144,160}        /* layer 3 */
  },

  { /* MPEG 1.0 */
    {32,64,96,128,160,192,224,256,288,320,352,384,416,448}, /* layer 1 */
    {32,48,56,64,80,96,112,128,160,192,224,256,320,384},    /* layer 2 */
    {32,40,48,56,64,80,96,112,128,160,192,224,256,320}      /* layer 3 */
  }
};

int frame_size_index[] = {24000, 72000, 72000};


char *mode_text[] = {
   "stereo", "joint stereo", "dual channel", "mono"
};

char *emphasis_text[] = {
  "none", "50/15 microsecs", "reserved", "CCITT J 17"
};


int get_mp3_info(mp3info *mp3,int scantype, int fullscan_vbr)
{
    int had_error = 0;
    int frame_type[15]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    float seconds=0,total_rate=0;
    int frames=0,frame_types=0,frames_so_far=0;
    int l,vbr_median=-1;
    int bitrate,lastrate;
    int counter=0;
    mp3header header;
    struct stat filestat;
    off_t sample_pos,data_start=0;

    stat(mp3->filename,&filestat);
    mp3->datasize=filestat.st_size;
    get_id3(mp3);

    if(scantype == SCAN_QUICK) {
	if(get_first_header(mp3,0L)) {
            data_start=ftell(mp3->file);
            lastrate=15-mp3->header.bitrate;
            while((counter < NUM_SAMPLES) && lastrate) {
                sample_pos=(counter*(mp3->datasize/NUM_SAMPLES+1))+data_start;
                if(get_first_header(mp3,sample_pos)) {
                    bitrate=15-mp3->header.bitrate;
                } else {
                    bitrate=-1;
                }
		
                if(bitrate != lastrate) {
                    mp3->vbr=1;
                    if(fullscan_vbr) {
                        counter=NUM_SAMPLES;
                        scantype=SCAN_FULL;
                    }
                }
                lastrate=bitrate;
                counter++;
			
            }
            if(!(scantype == SCAN_FULL)) {
                mp3->frames=(mp3->datasize-data_start)/(l=frame_length(&mp3->header));
                mp3->seconds = (int)((float)(frame_length(&mp3->header)*mp3->frames)/
                                     (float)(header_bitrate(&mp3->header)*125)+0.5);
                mp3->vbr_average = (float)header_bitrate(&mp3->header);
            }
	}

    }

    if(scantype == SCAN_FULL) {
  	if(get_first_header(mp3,0L)) {
            data_start=ftell(mp3->file);
            while((bitrate=get_next_header(mp3))) {
                frame_type[15-bitrate]++;
                frames++;
            }
            memcpy(&header,&(mp3->header),sizeof(mp3header));
            for(counter=0;counter<15;counter++) {
                if(frame_type[counter]) {
                    frame_types++;
                    header.bitrate=counter;
                    frames_so_far += frame_type[counter];
                    seconds += (float)(frame_length(&header)*frame_type[counter])/
                        (float)(header_bitrate(&header)*125);
                    total_rate += (float)((header_bitrate(&header))*frame_type[counter]);
                    if((vbr_median == -1) && (frames_so_far >= frames/2))
                        vbr_median=counter;
                }
            }
            mp3->seconds=(int)(seconds+0.5);
            mp3->header.bitrate=vbr_median;
            mp3->vbr_average=total_rate/(float)frames;
            mp3->frames=frames;
            if(frame_types > 1) {
                mp3->vbr=1;
            }
	}
    }
    return had_error;
}


int get_first_header(mp3info *mp3, long startpos) 
{
    int k, l=0,c;
    mp3header h, h2;
    long valid_start=0;
  
    fseek(mp3->file,startpos,SEEK_SET);
    while (1) {
        while((c=fgetc(mp3->file)) != 255 && (c != EOF));
        if(c == 255) {
            ungetc(c,mp3->file);
            valid_start=ftell(mp3->file);
            if((l=get_header(mp3->file,&h))) {
                fseek(mp3->file,l-FRAME_HEADER_SIZE,SEEK_CUR);
                for(k=1; (k < MIN_CONSEC_GOOD_FRAMES) && (mp3->datasize-ftell(mp3->file) >= FRAME_HEADER_SIZE); k++) {
                    if(!(l=get_header(mp3->file,&h2))) break;
                    if(!sameConstant(&h,&h2)) break;
                    fseek(mp3->file,l-FRAME_HEADER_SIZE,SEEK_CUR);
                }
                if(k == MIN_CONSEC_GOOD_FRAMES) {
                    fseek(mp3->file,valid_start,SEEK_SET);
                    memcpy(&(mp3->header),&h2,sizeof(mp3header));
                    mp3->header_isvalid=1;
                    return 1;
                } 
            }
        } else {
            return 0;
        }
    }

    return 0;  
}

/* get_next_header() - read header at current position or look for 
   the next valid header if there isn't one at the current position
*/
int get_next_header(mp3info *mp3) 
{
    int l=0,c,skip_bytes=0;
    mp3header h;
  
    while(1) {
        while((c=fgetc(mp3->file)) != 255 && (ftell(mp3->file) < mp3->datasize)) skip_bytes++;
        if(c == 255) {
            ungetc(c,mp3->file);
            if((l=get_header(mp3->file,&h))) {
                if(skip_bytes) mp3->badframes++;
                fseek(mp3->file,l-FRAME_HEADER_SIZE,SEEK_CUR);
                return 15-h.bitrate;
            } else {
		skip_bytes += FRAME_HEADER_SIZE;
            }
        } else {
            if(skip_bytes) mp3->badframes++;
            return 0;
        }
    }
}


/* Get next MP3 frame header.
   Return codes:
   positive value = Frame Length of this header
   0 = No, we did not retrieve a valid frame header
*/

int get_header(FILE *file,mp3header *header)
{
    unsigned char buffer[FRAME_HEADER_SIZE];
    int fl;

    if(fread(&buffer,FRAME_HEADER_SIZE,1,file)<1) {
	header->sync=0;
	return 0;
    }
    header->sync=(((int)buffer[0]<<4) | ((int)(buffer[1]&0xE0)>>4));
    if(buffer[1] & 0x10) header->version=(buffer[1] >> 3) & 1;
    else header->version=2;
    header->layer=(buffer[1] >> 1) & 3;
    header->bitrate=(buffer[2] >> 4) & 0x0F;
    if((header->sync != 0xFFE) || (header->layer != 1) || (header->bitrate == 0xF)) {
	header->sync=0;
	return 0;
    }
    header->crc=buffer[1] & 1;
    header->freq=(buffer[2] >> 2) & 0x3;
    header->padding=(buffer[2] >>1) & 0x1;
    header->extension=(buffer[2]) & 0x1;
    header->mode=(buffer[3] >> 6) & 0x3;
    header->mode_extension=(buffer[3] >> 4) & 0x3;
    header->copyright=(buffer[3] >> 3) & 0x1;
    header->original=(buffer[3] >> 2) & 0x1;
    header->emphasis=(buffer[3]) & 0x3;

    /* Final sanity checks: bitrate 1111b and frequency 11b are reserved (invalid) */
    if (header->bitrate == 0x0f || header->bitrate == 0) {
      g_warning( _("Invalid bitrate %0x in mp3 header.\n"), header->bitrate);
      return 0;
    }

    if (header->freq == 0x03) {
      g_warning(_("Invalid frequency %0x in mp3 header.\n"), header->freq);
      return 0;
    }
    return ((fl=frame_length(header)) >= MIN_FRAME_SIZE ? fl : 0); 
}

int frame_length(mp3header *header) {
    return header->sync == 0xFFE ? 
        (frame_size_index[3-header->layer]*((header->version&1)+1)*
         header_bitrate(header)/header_frequency(header))+
        header->padding : 1;
}

int header_layer(mp3header *h) {return layer_tab[h->layer];}

int header_bitrate(mp3header *h) {
    assert(h->bitrate > 0);
    return bitrate[h->version & 1][3-h->layer][h->bitrate-1];
}

int header_frequency(mp3header *h) {
    return frequencies[h->version][h->freq];
}

char *header_emphasis(mp3header *h) {
    return emphasis_text[h->emphasis];
}

char *header_mode(mp3header *h) {
    return mode_text[h->mode];
}

int sameConstant(mp3header *h1, mp3header *h2) {
    if((*(uint*)h1) == (*(uint*)h2)) return 1;

    if((h1->version       == h2->version         ) &&
       (h1->layer         == h2->layer           ) &&
       (h1->crc           == h2->crc             ) &&
       (h1->freq          == h2->freq            ) &&
       (h1->mode          == h2->mode            ) &&
       (h1->copyright     == h2->copyright       ) &&
       (h1->original      == h2->original        ) &&
       (h1->emphasis      == h2->emphasis        )) 
        return 1;
    else return 0;
}


int get_id3(mp3info *mp3) {
  char fbuf[4];

  if(mp3->datasize < 128) {
    g_warning(_("mp3 file '%s' is smaller than 128 bytes.\n"),
        mp3->filename);
    return 4;
  }
	if(fseek(mp3->file, -128, SEEK_END )) {
    g_warning(_("Couldn't read last 128 bytes of '%s'\n"),mp3->filename);
    return 4;
  } 
  fread(fbuf,1,3,mp3->file); fbuf[3] = '\0';
  mp3->id3.genre[0]=255;

  if (memcmp("TAG", fbuf, 3) != 0) {
    return 4;
  }

  mp3->id3_isvalid=1;
  mp3->datasize -= 128;
  fseek(mp3->file, -125, SEEK_END);
  fread(mp3->id3.title,1,30,mp3->file); mp3->id3.title[30] = '\0';
  fread(mp3->id3.artist,1,30,mp3->file); mp3->id3.artist[30] = '\0';
  fread(mp3->id3.album,1,30,mp3->file); mp3->id3.album[30] = '\0';
  fread(mp3->id3.year,1,4,mp3->file); mp3->id3.year[4] = '\0';
  fread(mp3->id3.comment,1,30,mp3->file); mp3->id3.comment[30] = '\0';
  if (mp3->id3.comment[28] == '\0') {
    mp3->id3.track[0] = mp3->id3.comment[29];
  }
  fread(mp3->id3.genre,1,1,mp3->file);
  unpad(mp3->id3.title);
  unpad(mp3->id3.artist);
  unpad(mp3->id3.album);
  unpad(mp3->id3.year);
  unpad(mp3->id3.comment);
  return 0;
}

char *pad(char *string, int length) {
  int l;

  l=strlen(string);
  while(l<length) {
      string[l] = ' ';
      l++;
  }

  string[l]='\0';
  return string;
}

/* Remove trailing whitespace from the end of a string */

char *unpad(char *string) {
  char *pos=string+strlen(string)-1;

  while(pos >= string && isspace(pos[0]))
    (pos--)[0]='\0';
  return string;
}

/*
 * Build an ID3 tag and write it to the file
 * Returns positive int on success, 0 on failure
 */

int write_tag(mp3info *mp3) {

    char buf[129];

    strcpy(buf,"TAG");
    pad(mp3->id3.title,TEXT_FIELD_LEN);
    strncat(buf,mp3->id3.title,TEXT_FIELD_LEN);
    pad(mp3->id3.artist,TEXT_FIELD_LEN);
    strncat(buf,mp3->id3.artist,TEXT_FIELD_LEN);
    pad(mp3->id3.album,TEXT_FIELD_LEN);
    strncat(buf,mp3->id3.album,TEXT_FIELD_LEN);
    pad(mp3->id3.year,INT_FIELD_LEN);
    strncat(buf,mp3->id3.year,INT_FIELD_LEN);
    pad(mp3->id3.comment,TEXT_FIELD_LEN);
    strncat(buf,mp3->id3.comment,TEXT_FIELD_LEN);
    strncat(buf,(char*)(mp3->id3.genre),1);
    if (mp3->id3.track[0] != '\0') {
        buf[125]='\0';
        buf[126]=mp3->id3.track[0];
    }
    fseek(mp3->file,-128*mp3->id3_isvalid,SEEK_END);
    return (int)fwrite(buf,1,128,mp3->file);
}


/*
 * Try to read the mp3 ID3 tags from file fp. Return 0 on success.
 */
int get_id3_tags( FILE   * fp, 
                  gchar ** title,
                  gchar ** artist,
                  gchar ** album) {
    unsigned char buffer[BUFFER_SIZE];    
    int k, off, len, s;
    char tag[BUFFER_SIZE];
    int result = 1;

    assert(artist && album && title);

    if (!fp)
        return 1;

    rewind(fp);

    if (fread(buffer, 1, BUFFER_SIZE, fp) == 0)
        return 1;
    if (memcmp(buffer, "ID3", 3) == 0) {
        result = 0; // success
        for (off = 10; off < 1024; ) {
            for (k = 0; k < NUM_TAGS; k+=2) {
                if (strcasecmp((char*)(buffer + off), id3_tag[k]) == 0) {
                    if (buffer[off + 5]) {
                        s = 7;
                        len = buffer[off + 5] - 1;
                    } else if (buffer[off + 7]) {
                        s = 11;
                        len = buffer[off + 7] - 1;
                    } else {
                        /* Well, we tried and failed... */
                        continue;
                    }
                    bzero(tag, BUFFER_SIZE);
                    memcpy(tag, buffer + off + s, len);
                    if (id3_tag[k+1][0] == TITLE_CHAR[0]) {
                        *title = strdup_to_utf8(tag);
                    } else if (id3_tag[k+1][0] == ARTIST_CHAR[0]) {
                        *artist = strdup_to_utf8(tag);
                    } else if (id3_tag[k+1][0] == ALBUM_CHAR[0]) {
                        *album = strdup_to_utf8(tag);
                    } 
                    off += s + len;
                    break;
                }
            }
            if (k < NUM_TAGS)
                continue;
            if (isalpha(buffer[off]) &&
                isalpha(buffer[off + 1]) &&
                isalpha(buffer[off + 2])) {
                off += 6 + buffer[off + 5];
            } else {
                break;
            }
        }
    } else {
        fseek(fp, -128, SEEK_END);
        fread(buffer, 1, 128, fp);
        if (strncmp((char*)buffer, "TAG", 3) == 0) {
            result = 0; // success

            bzero(tag, TEXT_FIELD_LEN + 1);
            memcpy(tag, buffer + 3, TEXT_FIELD_LEN);
            *title = strdup_to_utf8(tag);

            bzero(tag, TEXT_FIELD_LEN + 1);
            memcpy(tag, buffer + 3 + TEXT_FIELD_LEN, TEXT_FIELD_LEN);
            *artist = strdup_to_utf8(tag);

            bzero(tag, TEXT_FIELD_LEN + 1);
            memcpy(tag, buffer + 3 + TEXT_FIELD_LEN*2, TEXT_FIELD_LEN);
            *album = strdup_to_utf8(tag);
        }
    }    
    return result;
}

gboolean
read_mp3_file_type( gchar    * path,
                      gint     * length,
                      gchar   ** title,
                      gchar   ** artist,
                      gchar   ** album)
{
  mp3info mp3;

  memset(&mp3, 0, sizeof(mp3info));
  mp3.filename = path;
  mp3.file = fopen(path, "r");
  if (!mp3.file) {
    g_warning(_("Unable to read song data for '%s'\n"), path);
    return FALSE;
  }
  if ( get_mp3_info(&mp3, SCAN_QUICK, 1) == 0)
  {
    *length = mp3.seconds;
    if (mp3.id3_isvalid) 
    {
      *artist = strdup_to_utf8(mp3.id3.artist);
      *album = strdup_to_utf8(mp3.id3.album);
      *title = strdup_to_utf8(mp3.id3.title);
    } else {
      /* Use alternate methods of looking for ID3 tags 
       * This is needed to support, among other things, 
       * mp3s generated by iTunes */
      get_id3_tags(mp3.file, title, artist, album);
    }
  }
  fclose(mp3.file);
  if (mp3.header_isvalid)
    return TRUE;
  return FALSE;
}