summaryrefslogtreecommitdiff
path: root/mp3_afh.c
blob: ecfced83272ab682421ca9610943576c1654d981 (plain)
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
/* SPDX-License-Identifier: GPL-2.0 */

/** \file mp3_afh.c para_server's mp3 audio format handler */

/*
 * This file is based in part on mp3tech.c and mp3tech.h, Copyright (C)
 * 2000-2001 Cedric Tefft <cedric@earthling.net>, which in turn is 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>
 */

#include <id3tag.h>

#include "para.h"
#include "error.h"
#include "afh.h"
#include "string.h"
#include "fd.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

struct mp3header {
	unsigned long sync;
	unsigned int version;
	unsigned int layer;
	unsigned int crc;
	unsigned int bitrate;
	unsigned int freq;
	unsigned int padding;
	unsigned int mode;
};

static const 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 */
};

static const int mp3info_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 */
}
};

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

static char *get_utf8(id3_ucs4_t const *string)
{
	if (!string)
		return NULL;
	return (char *)id3_ucs4_utf8duplicate(string);
}

static char *get_stringlist(union id3_field *field)
{
	unsigned int k, nstrings = id3_field_getnstrings(field);
	char *result = NULL;

	for (k = 0; k < nstrings; k++) {
		char *tmp = (char *)get_utf8(id3_field_getstrings(field, k));
		if (result) {
			char *tmp2 = result;
			result = make_message("%s %s", tmp2, tmp);
			free(tmp);
			free(tmp2);
		} else
			result = tmp;
	}
	return result;
}

static char *get_string(union id3_field *field)
{
	id3_ucs4_t const *string = id3_field_getfullstring(field);

	return get_utf8(string);
}

static char *get_strings(struct id3_frame *fr)
{
	for (int j = 0; j < fr->nfields; j++) {
		union id3_field *field = id3_frame_field(fr, j);
		enum id3_field_type type = id3_field_type(field);

		if (type == ID3_FIELD_TYPE_STRINGLIST)
			return get_stringlist(field);
		if (type == ID3_FIELD_TYPE_STRINGFULL)
			return get_string(field);
	}
	return NULL;
}

/* this only sets values which are undefined so far */
static void parse_frames(struct id3_tag *id3_t, struct taginfo *tags)
{
	int i;

	for (i = 0; i < id3_t->nframes; i++) {
		struct id3_frame *fr = id3_t->frames[i];
		if (!strcmp(fr->id, ID3_FRAME_TITLE)) {
			if (!tags->title)
				tags->title = get_strings(fr);
			continue;
		}
		if (!strcmp(fr->id, ID3_FRAME_ARTIST)) {
			if (!tags->artist)
				tags->artist = get_strings(fr);
			continue;
		}
		if (!strcmp(fr->id, ID3_FRAME_ALBUM)) {
			if (!tags->album)
				tags->album = get_strings(fr);
			continue;
		}
		if (!strcmp(fr->id, ID3_FRAME_YEAR)) {
			if (!tags->year)
				tags->year = get_strings(fr);
			continue;
		}
		if (!strcmp(fr->id, ID3_FRAME_COMMENT)) {
			if (!tags->comment)
				tags->comment = get_strings(fr);
			continue;
		}
	}
}

static int get_id3(unsigned char *map, size_t numbytes,
		struct taginfo *tags)
{
	int ret = 0;
	struct id3_tag *id3_t;

	/* id3v2 tags are usually located at the beginning. */
	id3_t = id3_tag_parse(map, numbytes);
	if (id3_t) {
		parse_frames(id3_t, tags);
		ret |= 2;
		id3_tag_delete(id3_t);
	}
	/* Also look for an id3v1 tag at the end of the file. */
	if (numbytes >= 128) {
		id3_t = id3_tag_parse(map + numbytes - 128, 128);
		if (id3_t) {
			parse_frames(id3_t, tags);
			ret |= 1;
			id3_tag_delete(id3_t);
		}
	}
	return ret;
}

/*
 * The two helpers below are called during tag replacement if libid3tag is
 * present. They are implemented and exported in the library but libid3tag.h
 * does not declare them, so we declare them here.
 */

/** \cond libid3tag */

/*
 * To replace a tag with libid3tag one has to pass frames of id3 fields
 * to particular functions of the id3tag library. The various field types
 * specify text encoding, language, string, etc. This function initializes
 * a field to the default value for the given type. It does not allocate
 * memory and always succeeds.
 */
void id3_field_init(union id3_field *field, enum id3_field_type type);

/*
 * Reset a field, deallocating memory if necessary.
 *
 * This first frees any memory already allocated, then calls id3_field_init()
 * to initialize the field, re-using the old field type. The field pointer
 * must not be NULL.
 */
void id3_field_finish(union id3_field *field);

/** \endcond libid3tag */

/*
 * Frames of type ID3_FRAME_COMMENT contain three fields of type language,
 * string, and fullstring. The third field contains the actual comment.
 */
static int set_comment_fields(struct id3_frame *fr, id3_ucs4_t *ucs4_val)
{
	int ret;
	union id3_field *field;

	field = id3_frame_field(fr, 1);
	id3_field_init(field, ID3_FIELD_TYPE_LANGUAGE);

	field = id3_frame_field(fr, 2);
	id3_field_init(field, ID3_FIELD_TYPE_STRING);

	field = id3_frame_field(fr, 3);
	id3_field_init(field, ID3_FIELD_TYPE_STRINGFULL);
	ret = id3_field_setfullstring(field, ucs4_val);
	if (ret < 0)
		return -E_ID3_SETSTRING;
	return 1;
}

/*
 * UCS-4 stands for Universal Character Set where each character uses exactly
 * 32 bits. It is also known as UTF-32, see ISO 10646.
 *
 * We have to use UCS-4 as an intermediate representation because the functions
 * of libid3tag which set the tag content expect an array of UCS-4 characters.
 * Fortunately, libid3tag contains conversion functions from and to UTF-8.
 */
static int replace_tag(char const *id, const char *val, struct id3_tag *id3_t,
		int options)
{
	int ret;
	struct id3_frame *fr;
	union id3_field *field;
	id3_ucs4_t *ucs4_val;

	/* First, detach all frames that match the given id. */
	while ((fr = id3_tag_findframe(id3_t, id, 0))) {
		PARA_INFO_LOG("deleting %s frame\n", id);
		ret = id3_tag_detachframe(id3_t, fr);
		if (ret < 0)
			return -E_ID3_DETACH;
		id3_frame_delete(fr);
	}
	if (!val || !*val)
		return 0;
	fr = id3_frame_new(id);
	PARA_DEBUG_LOG("frame desc: %s, %u fields\n", fr->description, fr->nfields);

	/* Frame 0 contains the encoding. We always use UTF-8. */
	field = id3_frame_field(fr, 0);
	id3_field_init(field, ID3_FIELD_TYPE_TEXTENCODING);
	ret = id3_field_settextencoding(field, ID3_FIELD_TEXTENCODING_UTF_8);
	if (ret < 0)
		return -E_ID3_SETENCODING;
	/* create UCS-4 representation */
	ucs4_val = id3_utf8_ucs4duplicate((const id3_utf8_t *)val);

	if (strcmp(id, ID3_FRAME_COMMENT) == 0)
		ret = set_comment_fields(fr, ucs4_val);
	else {
		/* Non-comment frames contain the value in field 1. */
		field = id3_frame_field(fr, 1);
		if (options & ID3_TAG_OPTION_ID3V1) {
			id3_ucs4_t *ptr[] = {ucs4_val, NULL};
			id3_field_init(field, ID3_FIELD_TYPE_STRINGLIST);
			ret = id3_field_setstrings(field, 1, ptr);
		} else {
			id3_field_init(field, ID3_FIELD_TYPE_STRINGFULL);
			ret = id3_field_setfullstring(field, ucs4_val);
		}
	}
	free(ucs4_val);
	if (ret < 0)
		return -E_ID3_SETSTRING;

	PARA_INFO_LOG("attaching %s frame, value: %s\n", id, val);
	ret = id3_tag_attachframe(id3_t, fr);
	if (ret < 0)
		return -E_ID3_ATTACH;
	return 1;
}

static int replace_tags(struct id3_tag *id3_t, struct taginfo *tags)
{
	int ret, options = id3_tag_options(id3_t, 0, 0);

	ret = replace_tag(ID3_FRAME_ARTIST, tags->artist, id3_t, options);
	if (ret < 0)
		return ret;
	ret = replace_tag(ID3_FRAME_TITLE, tags->title, id3_t, options);
	if (ret < 0)
		return ret;
	ret = replace_tag(ID3_FRAME_ALBUM, tags->album, id3_t, options);
	if (ret < 0)
		return ret;
	ret = replace_tag(ID3_FRAME_YEAR, tags->year, id3_t, options);
	if (ret < 0)
		return ret;
	ret = replace_tag(ID3_FRAME_COMMENT, tags->comment, id3_t, options);
	if (ret < 0)
		return ret;
	return 1;
}

/* id3_tag_delete() does not seem to work due to refcount issues. */
static void free_tag(struct id3_tag *id3_t)
{
	int i, j;

	if (!id3_t)
		return;
	for (i = 0; i < id3_t->nframes; i++) {
		struct id3_frame *fr = id3_t->frames[i];
		for (j = 0; j < fr->nfields; j++) {
			union id3_field *field = &fr->fields[j];
			id3_field_finish(field);
		}
		free(fr);
	}
	free(id3_t->frames);
	free(id3_t);
}

static int mp3_rewrite_tags(const char *map, size_t mapsize,
		struct taginfo *tags, int fd)
{
	int ret;
	id3_length_t old_v2size, new_v2size;
	id3_byte_t v1_buffer[128], *v2_buffer;
	size_t data_sz;
	struct id3_tag *v1_tag = NULL, *v2_tag = NULL;

	if (mapsize >= 128) {
		v1_tag = id3_tag_parse((const id3_byte_t *)map + mapsize - 128,
			128);
		if (v1_tag) {
			PARA_NOTICE_LOG("replacing id3v1 tag\n");
			ret = replace_tags(v1_tag, tags);
			if (ret < 0)
				goto out;
			id3_tag_render(v1_tag, v1_buffer);
		}
	}
	old_v2size = 0;
	v2_tag = id3_tag_parse((const id3_byte_t *)map, mapsize);
	if (v2_tag) {
		PARA_NOTICE_LOG("replacing id3v2 tag\n");
		old_v2size = v2_tag->paddedsize;
	} else {
		PARA_NOTICE_LOG("adding id3v2 tag\n");
		v2_tag = id3_tag_new();
		assert(v2_tag);
	}
	/*
	 * Turn off all options to avoid creating an extended header.  id321
	 * does not understand it.
	 */
	id3_tag_options(v2_tag, ~0U, 0);
	ret = replace_tags(v2_tag, tags);
	if (ret < 0)
		goto out;
	new_v2size = id3_tag_render(v2_tag, NULL);
	v2_buffer = alloc(new_v2size);
	id3_tag_render(v2_tag, v2_buffer);
	PARA_INFO_LOG("writing v2 tag (%lu bytes)\n", new_v2size);
	ret = write_all(fd, (char *)v2_buffer, new_v2size);
	free(v2_buffer);
	if (ret < 0)
		goto out;
	data_sz = mapsize - old_v2size;
	if (v1_tag && data_sz >= 128)
		data_sz -= 128;
	PARA_INFO_LOG("writing data part (%zu bytes)\n", data_sz);
	ret = write_all(fd, map + old_v2size, data_sz);
	if (ret < 0)
		goto out;
	if (v1_tag) {
		PARA_INFO_LOG("writing v1 tag\n");
		ret = write_all(fd, (char *)v1_buffer, 128);
	}
out:
	free_tag(v1_tag);
	free_tag(v2_tag);
	return ret;
}

static int header_frequency(struct mp3header *h)
{
	if (h->version > 2 || h->freq > 3)
		return -E_HEADER_FREQ;
	return frequencies[h->version][h->freq];
}

static const char *header_mode(const struct mp3header *h)
{
	const char * const mode_text[] = {"stereo", "joint stereo",
		"dual channel", "mono"};

	if (h->mode >= ARRAY_SIZE(mode_text))
		return "invalid";
	return mode_text[h->mode];
}

static int header_channels(struct mp3header *h)
{
	if (h->mode > 3)
		return 0;
	if (h->mode < 3)
		return 2;
	return 1;
}

static int header_bitrate(struct mp3header *h)
{
	if (!h->layer || h->layer > 3 || h->bitrate > 14 || !h->bitrate)
		return -E_HEADER_BITRATE;
	return mp3info_bitrate[h->version & 1][3 - h->layer][h->bitrate - 1];
}

static int frame_length(struct mp3header *header)
{
	int hb, hf = header_frequency(header);

	if (hf < 0)
		return hf;
	hb = header_bitrate(header);
	if (hb < 0)
		return hb;
	if (header->sync != 0xFFE || header->layer > 3)
		return -E_FRAME;
	return frame_size_index[3 - header->layer] *
		((header->version & 1) + 1) * hb / hf
		+ header->padding;
}

static int compare_headers(struct mp3header *h1, struct mp3header *h2)
{
	if ((*(unsigned int*)h1) == (*(unsigned int*)h2))
		return 1;
	if ((h1->version == h2->version) &&
			(h1->layer == h2->layer) &&
			(h1->crc == h2->crc) &&
			(h1->freq == h2->freq) &&
			(h1->mode == h2->mode))
		return 1;
	return 0;
}

/*
 * get next MP3 frame header.
 *
 * On success, the header frame length is returned and the given header
 * structure that is filled in.  A return value of zero means that we did not
 * retrieve a valid frame header, and a negative return value indicates an
 * error.
 */
static int get_header(unsigned char *map, size_t numbytes, off_t *fpos,
	struct mp3header *header)
{
	int fl, ret;

	if (*fpos + FRAME_HEADER_SIZE > numbytes) {
		*fpos = numbytes - 1;
		header->sync = 0;
		return 0;
	}
	header->layer = (map[*fpos + 1] >> 1) & 3;
	header->sync = (((int)map[*fpos]<<4) | ((int)(map[*fpos + 1]&0xE0)>>4));
	if (map[*fpos + 1] & 0x10)
		header->version = (map[*fpos + 1] >> 3) & 1;
	else
		header->version = 2;
	if ((header->sync != 0xFFE) || (header->layer != 1)) {
		ret = 0;
		header->sync = 0;
		goto out;
	}
	header->crc = map[*fpos + 1] & 1;
	header->bitrate = (map[*fpos + 2] >> 4) & 0x0F;
	header->freq = (map[*fpos + 2] >> 2) & 0x3;
	header->padding = (map[*fpos + 2] >>1) & 0x1;
	header->mode = (map[*fpos + 3] >> 6) & 0x3;
	fl = frame_length(header);
	ret = (fl >= MIN_FRAME_SIZE)? fl : -E_FRAME_LENGTH;
out:
	*fpos += FRAME_HEADER_SIZE;
	return ret;
}

/*
 * find the next mp3 header
 *
 * Return the length of the next frame header or zero if the end of the file is
 * reached.
 */
static int seek_next_header(unsigned char *map, size_t numbytes, off_t *fpos,
	struct mp3header *result)
{
	int k, l = 0, first_len;
	struct mp3header h, h2;
	long valid_start = 0;

	for (; *fpos < numbytes; (*fpos)++) {
		if (map[*fpos] != 0xff)
			continue;
		valid_start = *fpos;
		first_len = get_header(map, numbytes, fpos, &h);
		if (first_len <= 0)
			continue;
		*fpos += first_len - FRAME_HEADER_SIZE;
		for (k = 1; k < MIN_CONSEC_GOOD_FRAMES; k++) {
			if ((l = get_header(map, numbytes, fpos, &h2)) <= 0)
				break;
			if (!compare_headers(&h, &h2))
				break;
			*fpos += l - FRAME_HEADER_SIZE;
		}
		if (k == MIN_CONSEC_GOOD_FRAMES) {
			*fpos = valid_start;
			*result = h2;
			return first_len;
		}
	}
	return 0;
}

static int find_valid_start(unsigned char *map, size_t numbytes, off_t *fpos,
	struct mp3header *header)
{
	int frame_len;

	frame_len = get_header(map, numbytes, fpos, header);
	if (frame_len < 0)
		return frame_len;
	if (!frame_len) {
		frame_len = seek_next_header(map, numbytes, fpos, header);
		if (frame_len <= 0)
			return frame_len;
	} else
		*fpos -= FRAME_HEADER_SIZE;
	if (frame_len <= 1)
		return -E_FRAME_LENGTH;
	return frame_len;
}

static int read_info(unsigned char *map, size_t numbytes,
		struct afh_info *afhi)
{
	uint64_t freq_sum = 0, br_sum = 0;
	int fl = 0, ret, len = 0, old_br = -1, vbr = 0;
	struct timeval total_time = {0, 0};
	unsigned chunk_table_size = 1000; /* gets increased on demand */
	off_t fpos = 0;
	struct mp3header header;
	const char *tag_versions[] = {"no", "id3v1", "id3v2", "id3v1+id3v2"};

	afhi->chunks_total = 0;
	afhi->chunk_table = arr_alloc(chunk_table_size, sizeof(uint32_t));
	while (1) {
		int freq, br;
		struct timeval tmp, cct; /* current chunk time */
		fpos += len;
		len = find_valid_start(map, numbytes, &fpos, &header);
		if (len <= 0) {
			size_t end;
			ret = -E_MP3_INFO;
			if (!afhi->chunks_total)
				goto err_out;
			end = afhi->chunk_table[afhi->chunks_total - 1] + fl;
			afhi->chunk_table[afhi->chunks_total]
				= PARA_MIN(end, numbytes);
			break;
		}
		ret = header_frequency(&header);
		if (ret < 0)
			continue;
		freq = ret;
		ret = header_bitrate(&header);
		if (ret < 0)
			continue;
		br = ret;
		ret = frame_length(&header);
		if (ret < 0)
			continue;
		fl = ret;
		tmp.tv_sec = fl - header.padding;
		tmp.tv_usec = 0;
		tv_divide(br * 125, &tmp, &cct);
		tv_add(&cct, &total_time, &tmp);
		total_time = tmp;
		if (afhi->chunks_total >= chunk_table_size) {
			chunk_table_size *= 2;
			afhi->chunk_table = arr_realloc(afhi->chunk_table,
				chunk_table_size, sizeof(uint32_t));
		}
		afhi->chunk_table[afhi->chunks_total] = fpos;
		afhi->chunks_total++;
		freq_sum += freq;
		br_sum += br;
		if (afhi->chunks_total != 1 && old_br != br)
			vbr = 1;
		old_br = br;
	}
	ret = -E_MP3_INFO;
	if (!freq_sum || !br_sum)
		goto err_out;
	afhi->bitrate = br_sum / afhi->chunks_total;
	afhi->frequency = freq_sum / afhi->chunks_total;
	afhi->channels = header_channels(&header);
	afhi->seconds_total = (tv2ms(&total_time) + 500) / 1000;
	tv_divide(afhi->chunks_total, &total_time, &afhi->chunk_tv);
	PARA_DEBUG_LOG("%" PRIu32 " chunks, each %lums\n", afhi->chunks_total,
		tv2ms(&afhi->chunk_tv));
	set_max_chunk_size(afhi);
	ret = get_id3(map, numbytes, &afhi->tags);
	afhi->techinfo = make_message("%cbr, %s, %s tags", vbr? 'v' : 'c',
		header_mode(&header), tag_versions[ret]);
	return 1;
err_out:
	free(afhi->chunk_table);
	return ret;
}

/*
 * Read mp3 information from audio file
 */
static int mp3_get_file_info(char *map, size_t numbytes, struct afh_info *afhi)
{
	int ret;

	ret = read_info((unsigned char *)map, numbytes, afhi);
	if (ret < 0)
		return ret;
	if (afhi->chunks_total == 0)
		return -E_MP3_INFO;
	return 1;
}

static const char * const mp3_suffixes[] = {"mp3", NULL};

/** The mp3 audio format handler. */
const struct audio_format_handler mp3_afh = {
	.get_file_info = mp3_get_file_info,
	.suffixes = mp3_suffixes,
	.rewrite_tags = mp3_rewrite_tags,
};