Merge branch 'refs/heads/t/mixer-fix'
[paraslash.git] / afh_common.c
1 /* Copyright (C) 1997 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
2
3 /** \file afh_common.c Common audio format handler functions. */
4
5 #include <sys/mman.h> /* mmap */
6 #include <sys/types.h>
7 #include <regex.h>
8
9 #include "para.h"
10 #include "error.h"
11 #include "string.h"
12 #include "afh.h"
13
14 typedef void afh_init_func(struct audio_format_handler *);
15
16 /*
17 * Declaration of the audio format handler init functions.
18 *
19 * These symbols are referenced in the afl array below.
20 *
21 * Most audio format handlers depend on an external library and are not
22 * compiled in if the library is not installed. Hence it is well possible that
23 * not all of these functions are defined. It does not hurt to declare them
24 * anyway, and this avoids another set of ifdefs.
25 */
26 extern afh_init_func mp3_afh_init, ogg_afh_init, aac_afh_init, wma_afh_init,
27 spx_afh_init, flac_afh_init, opus_afh_init;
28
29 /** The list of all status items */
30 const char *status_item_list[] = {STATUS_ITEMS};
31
32 /**
33 * The list of supported audio formats.
34 *
35 * We always define the full array of audio formats even if some audio formats
36 * were not compiled in. This is because for each audio file the number of its
37 * audio format is stored in the database. We don't want these numbers to become
38 * stale just because the user installed a new version of paraslash that
39 * supports a different set of audio formats.
40 *
41 * It can still be easily detected whether an audio format is compiled in by
42 * checking if the init function pointer is not \p NULL.
43 */
44 static struct audio_format_handler afl[] = {
45 {
46 .name = "mp3",
47 .init = mp3_afh_init,
48 },
49 {
50 .name = "ogg",
51 #if defined(HAVE_OGG) && defined(HAVE_VORBIS)
52 .init = ogg_afh_init,
53 #endif
54 },
55 {
56 .name = "aac",
57 #if defined(HAVE_FAAD)
58 .init = aac_afh_init,
59 #endif
60 },
61 {
62 .name = "wma",
63 .init = wma_afh_init,
64 },
65 {
66 .name = "spx",
67 #if defined(HAVE_OGG) && defined(HAVE_SPEEX)
68 .init = spx_afh_init,
69 #endif
70 },
71 {
72 .name = "flac",
73 #if defined(HAVE_OGG) && defined(HAVE_FLAC)
74 .init = flac_afh_init,
75 #endif
76 },
77 {
78 .name = "opus",
79 #if defined(HAVE_OGG) && defined(HAVE_OPUS)
80 .init = opus_afh_init,
81 #endif
82 },
83 {
84 .name = NULL,
85 }
86 };
87
88 static inline int next_audio_format(int format)
89 {
90 for (;;) {
91 if (!afl[format].name)
92 return format;
93 format++;
94 if (afl[format].init)
95 return format;
96 }
97 }
98
99 /** Iterate over each supported audio format. */
100 #define FOR_EACH_AUDIO_FORMAT(i) for (i = 0; afl[i].name; i = next_audio_format(i))
101
102 /**
103 * Call the init function of each supported audio format handler.
104 */
105 void afh_init(void)
106 {
107 int i;
108
109 PARA_NOTICE_LOG("supported audio formats: %s\n", AUDIO_FORMAT_HANDLERS);
110 FOR_EACH_AUDIO_FORMAT(i) {
111 PARA_INFO_LOG("initializing %s handler\n",
112 audio_format_name(i));
113 afl[i].init(&afl[i]);
114 }
115 }
116
117 /**
118 * Tell whether an audio format handler provides chunk tables.
119 *
120 * Each audio format handler either provides a chunk table or supports dynamic
121 * chunks.
122 *
123 * \param audio_format_id Offset in the afl array.
124 *
125 * \return True if dynamic chunks are supported, false if the audio format
126 * handler provides chunk tables.
127 */
128 bool afh_supports_dynamic_chunks(int audio_format_id)
129 {
130 return afl[audio_format_id].get_chunk;
131 }
132
133 /**
134 * Guess the audio format judging from filename.
135 *
136 * \param name The filename.
137 *
138 * \return This function returns \p -E_AUDIO_FORMAT if it has no idea what kind
139 * of audio file this might be. Otherwise the (non-negative) number of the
140 * audio format is returned.
141 */
142 int guess_audio_format(const char *name)
143 {
144 int i,j, len = strlen(name);
145
146 FOR_EACH_AUDIO_FORMAT(i) {
147 for (j = 0; afl[i].suffixes[j]; j++) {
148 const char *p = afl[i].suffixes[j];
149 int plen = strlen(p);
150 if (len < plen + 1)
151 continue;
152 if (name[len - plen - 1] != '.')
153 continue;
154 if (strcasecmp(name + len - plen, p))
155 continue;
156 // PARA_DEBUG_LOG("might be %s\n", audio_format_name(i));
157 return i;
158 }
159 }
160 return -E_AUDIO_FORMAT;
161 }
162
163 /**
164 * Get the name of the given audio format.
165 *
166 * \param i The audio format number.
167 *
168 * \return This returns a pointer to statically allocated memory so it
169 * must not be freed by the caller.
170 */
171 const char *audio_format_name(int i)
172 {
173 if (i < 0 || i >= ARRAY_SIZE(afl) - 1)
174 return "???";
175 return afl[i].name;
176 }
177
178 static int get_file_info(int format, const char *path, char *data,
179 size_t size, int fd, struct afh_info *afhi)
180 {
181 int ret;
182 const char *fmt = audio_format_name(format);
183
184 memset(afhi, 0, sizeof(*afhi));
185 ret = afl[format].get_file_info(data, size, fd, afhi);
186 if (ret < 0) {
187 PARA_WARNING_LOG("%s: %s format not detected: %s\n",
188 path, fmt, para_strerror(-ret));
189 return ret;
190 }
191 PARA_NOTICE_LOG("%s: detected %s format\n", path, fmt);
192 return format;
193 }
194
195 /**
196 * Call get_file_info() to obtain an afhi structure.
197 *
198 * \param path The full path of the audio file.
199 * \param data Pointer to the contents of the (mapped) file.
200 * \param size The file size in bytes.
201 * \param fd The open file descriptor.
202 * \param afhi Result pointer.
203 *
204 * \return The number of the audio format on success, \p -E_AUDIO_FORMAT if no
205 * compiled in audio format handler is able to handler the file.
206 *
207 * This function tries to find an audio format handler that can interpret the
208 * file given by \a data and \a size.
209 *
210 * It first tries to determine the audio format from the filename given by \a
211 * path. If this doesn't work, all other audio format handlers are tried until
212 * one is found that can handle the file.
213 */
214 int compute_afhi(const char *path, char *data, size_t size, int fd,
215 struct afh_info *afhi)
216 {
217 int ret, i, format;
218
219 format = guess_audio_format(path);
220 if (format >= 0) {
221 ret = get_file_info(format, path, data, size, fd, afhi);
222 if (ret >= 0)
223 goto success;
224 }
225 FOR_EACH_AUDIO_FORMAT(i) {
226 if (i == format) /* we already tried this one to no avail */
227 continue;
228 ret = get_file_info(i, path, data, size, fd, afhi);
229 if (ret >= 0)
230 goto success;
231 }
232 return -E_AUDIO_FORMAT;
233 success:
234 if (!afhi->techinfo)
235 afhi->techinfo = para_strdup(NULL);
236 if (!afhi->tags.artist)
237 afhi->tags.artist = para_strdup(NULL);
238 if (!afhi->tags.title)
239 afhi->tags.title = para_strdup(NULL);
240 if (!afhi->tags.year)
241 afhi->tags.year = para_strdup(NULL);
242 if (!afhi->tags.album)
243 afhi->tags.album = para_strdup(NULL);
244 if (!afhi->tags.comment)
245 afhi->tags.comment = para_strdup(NULL);
246 PARA_DEBUG_LOG("techinfo: %s\n", afhi->techinfo);
247 PARA_DEBUG_LOG("artist: %s\n", afhi->tags.artist);
248 PARA_DEBUG_LOG("title: %s\n", afhi->tags.title);
249 PARA_DEBUG_LOG("year: %s\n", afhi->tags.year);
250 PARA_DEBUG_LOG("album: %s\n", afhi->tags.album);
251 PARA_DEBUG_LOG("comment: %s\n", afhi->tags.comment);
252 return ret;
253 }
254
255 /**
256 * Deallocate the contents of an afh_info structure.
257 *
258 * \param afhi The structure to clear.
259 *
260 * This only frees the memory the various pointer fields of \a afhi point to.
261 * It does *not* free \a afhi itself.
262 */
263 void clear_afhi(struct afh_info *afhi)
264 {
265 if (!afhi)
266 return;
267 free(afhi->chunk_table);
268 free(afhi->techinfo);
269 free(afhi->tags.artist);
270 free(afhi->tags.title);
271 free(afhi->tags.year);
272 free(afhi->tags.album);
273 free(afhi->tags.comment);
274 }
275
276 static inline size_t get_chunk_len(long unsigned chunk_num,
277 const struct afh_info *afhi)
278 {
279 return afhi->chunk_table[chunk_num + 1] - afhi->chunk_table[chunk_num];
280 }
281
282 /**
283 * Get one chunk of audio data.
284 *
285 * This implicitly calls the ->open method of the audio format handler at the
286 * first call.
287 *
288 * \param chunk_num The number of the chunk to get.
289 * \param afhi Describes the audio file.
290 * \param audio_format_id Determines the afh.
291 * \param map The memory mapped audio file.
292 * \param mapsize Passed to the afh's ->open() method.
293 * \param buf Result pointer.
294 * \param len The length of the chunk in bytes.
295 * \param afh_context Value/result, determines whether ->open() is called.
296 *
297 * Upon return, \a buf will point so memory inside \a map. The returned buffer
298 * must therefore not be freed by the caller.
299 *
300 * \return Standard.
301 */
302 __must_check int afh_get_chunk(long unsigned chunk_num, struct afh_info *afhi,
303 uint8_t audio_format_id, const void *map, size_t mapsize,
304 const char **buf, size_t *len, void **afh_context)
305 {
306 struct audio_format_handler *afh = afl + audio_format_id;
307
308 if (afh_supports_dynamic_chunks(audio_format_id)) {
309 int ret;
310
311 if (!*afh_context) {
312 ret = afh->open(map, mapsize, afh_context);
313 if (ret < 0)
314 return ret;
315 }
316 ret = afl[audio_format_id].get_chunk(chunk_num, *afh_context,
317 buf, len);
318 if (ret < 0) {
319 afh->close(*afh_context);
320 *afh_context = NULL;
321 }
322 return ret;
323 } else {
324 size_t pos = afhi->chunk_table[chunk_num];
325 *buf = map + pos;
326 *len = get_chunk_len(chunk_num, afhi);
327 return 0;
328 }
329 }
330
331 /**
332 * Deallocate resources allocated due to dynamic chunk handling.
333 *
334 * This function should be called if afh_get_chunk() was called at least once.
335 * It is OK to call it even for audio formats which do not support dynamic
336 * chunks, in which case the function does nothing.
337 *
338 * \param afh_context As returned from the ->open method of the afh.
339 * \param audio_format_id Determines the afh.
340 */
341 void afh_close(void *afh_context, uint8_t audio_format_id)
342 {
343 struct audio_format_handler *afh = afl + audio_format_id;
344
345 if (!afh_supports_dynamic_chunks(audio_format_id))
346 return;
347 if (!afh->close)
348 return;
349 if (!afh_context)
350 return;
351 afh->close(afh_context);
352 }
353
354 /**
355 * Find a suitable start chunk.
356 *
357 * \param approx_chunk_num Upper bound for the chunk number to return.
358 * \param afhi Needed for the chunk table.
359 * \param audio_format_id Determines the afh.
360 *
361 * \return For audio format handlers which support dynamic chunks, the function
362 * returns the given chunk number. Otherwise it returns the first non-empty
363 * chunk <= \a approx_chunk_num.
364 *
365 * \sa \ref afh_get_chunk().
366 */
367 int32_t afh_get_start_chunk(int32_t approx_chunk_num,
368 const struct afh_info *afhi, uint8_t audio_format_id)
369 {
370 int32_t k;
371
372 if (afh_supports_dynamic_chunks(audio_format_id))
373 return approx_chunk_num;
374
375 for (k = PARA_MAX(0, approx_chunk_num); k >= 0; k--)
376 if (get_chunk_len(k, afhi) > 0)
377 return k;
378 return 0;
379 }
380
381 /**
382 * Get the header of an audio file.
383 *
384 * \param afhi The audio file handler data describing the file.
385 * \param audio_format_id Determines the audio format handler.
386 * \param map The data of the audio file.
387 * \param mapsize The amount of bytes of the mmapped audio file.
388 * \param buf The length of the header is stored here.
389 * \param len Points to a buffer containing the header on return.
390 *
391 * This function sets \a buf to \p NULL and \a len to zero if \a map or \a
392 * afhi is \p NULL, or if the current audio format does not need special
393 * header treatment.
394 *
395 * Otherwise, it is checked whether the audio format handler given by
396 * \a audio_format_id defines a ->get_header() method. If it does, this
397 * method is called to obtain the header. If ->get_header() is \p NULL,
398 * a reference to the first chunk of the audio file is returned.
399 *
400 * Once the header is no longer needed, the caller must call \ref
401 * afh_free_header() to free the resources allocated by this function.
402 */
403 void afh_get_header(struct afh_info *afhi, uint8_t audio_format_id,
404 void *map, size_t mapsize, char **buf, size_t *len)
405 {
406 struct audio_format_handler *afh = afl + audio_format_id;
407
408 if (!map || !afhi || !afhi->header_len) {
409 *buf = NULL;
410 *len = 0;
411 return;
412 }
413 if (!afh->get_header) {
414 *len = afhi->header_len;
415 *buf = map;
416 return;
417 }
418 afh->get_header(map, mapsize, buf, len);
419 }
420
421 /**
422 * Deallocate any resources obtained from afh_get_header().
423 *
424 * \param header_buf Pointer obtained via afh_get_header().
425 * \param audio_format_id Determines the audio format handler.
426 */
427 void afh_free_header(char *header_buf, uint8_t audio_format_id)
428 {
429 struct audio_format_handler *afh = afl + audio_format_id;
430
431 if (afh->get_header)
432 free(header_buf);
433 }
434
435 /**
436 * Pretty-print the contents of a struct afh_info into a buffer.
437 *
438 * \param audio_format_num The audio format number.
439 * \param afhi Pointer to the structure that contains the information.
440 * \param result Pretty-printed ahfi is here after the call.
441 *
442 * The \a result buffer is dynamically allocated and should be freed by the
443 * caller.
444 *
445 * \return The number of bytes. This function never fails.
446 */
447 unsigned afh_get_afhi_txt(int audio_format_num, struct afh_info *afhi, char **result)
448 {
449 return xasprintf(result, "%s: %dkbit/s\n" /* bitrate */
450 "%s: %s\n" /* format */
451 "%s: %dHz\n" /* frequency */
452 "%s: %d\n" /* channels */
453 "%s: %" PRIu32 "\n" /* seconds total */
454 "%s: %lu: %lu\n" /* chunk time */
455 "%s: %" PRIu32 "\n" /* num chunks */
456 "%s: %" PRIu32 "\n" /* max chunk size */
457 "%s: %s\n" /* techinfo */
458 "%s: %s\n" /* artist */
459 "%s: %s\n" /* title */
460 "%s: %s\n" /* year */
461 "%s: %s\n" /* album */
462 "%s: %s\n", /* comment */
463 status_item_list[SI_bitrate], afhi->bitrate,
464 status_item_list[SI_format], audio_format_name(audio_format_num),
465 status_item_list[SI_frequency], afhi->frequency,
466 status_item_list[SI_channels], afhi->channels,
467 status_item_list[SI_seconds_total], afhi->seconds_total,
468 status_item_list[SI_chunk_time], (long unsigned)afhi->chunk_tv.tv_sec,
469 (long unsigned)afhi->chunk_tv.tv_usec,
470 status_item_list[SI_num_chunks], afhi->chunks_total,
471 status_item_list[SI_max_chunk_size], afhi->max_chunk_size,
472 status_item_list[SI_techinfo], afhi->techinfo? afhi->techinfo : "",
473 status_item_list[SI_artist], afhi->tags.artist? afhi->tags.artist : "",
474 status_item_list[SI_title], afhi->tags.title? afhi->tags.title : "",
475 status_item_list[SI_year], afhi->tags.year? afhi->tags.year : "",
476 status_item_list[SI_album], afhi->tags.album? afhi->tags.album : "",
477 status_item_list[SI_comment], afhi->tags.comment? afhi->tags.comment : ""
478 );
479 }
480
481 /**
482 * Determine the maximal chunk size by investigating the chunk table.
483 *
484 * \param afhi Value/result.
485 *
486 * This function iterates over the chunk table and sets ->max_chunk_size
487 * accordingly. The function exists only for backward compatibility since as of
488 * version 0.6.0, para_server stores the maximal chunk size in its database.
489 * This function is only called if the database value is zero, indicating that
490 * the file was added by an older server version.
491 */
492 void set_max_chunk_size(struct afh_info *afhi)
493 {
494 uint32_t n, max = 0, old = 0;
495
496 for (n = 0; n <= afhi->chunks_total; n++) {
497 uint32_t val = afhi->chunk_table[n];
498 /*
499 * If the first chunk is the header, do not consider it for the
500 * calculation of the largest chunk size.
501 */
502 if (n == 0 || (n == 1 && afhi->header_len > 0)) {
503 old = val;
504 continue;
505 }
506 max = PARA_MAX(max, val - old);
507 old = val;
508 }
509 afhi->max_chunk_size = max;
510 }
511
512 /**
513 * Create a copy of the given file with altered meta tags.
514 *
515 * \param audio_format_id Specifies the audio format.
516 * \param map The (read-only) memory map of the input file.
517 * \param mapsize The size of the input file in bytes.
518 * \param tags The new tags.
519 * \param output_fd Altered file is created using this file descriptor.
520 * \param filename The name of the temporary output file.
521 *
522 * This calls the ->rewrite_tags method of the audio format handler associated
523 * with \a audio_format_id to create a copy of the memory-mapped file given
524 * by \a map and \a mapsize, but with altered tags according to \a tags. If
525 * the audio format handler for \a audio_format_id lacks this optional method,
526 * the function returns (the paraslash error code of) \p ENOTSUP.
527 *
528 * \return Standard.
529 */
530 int afh_rewrite_tags(int audio_format_id, void *map, size_t mapsize,
531 struct taginfo *tags, int output_fd, const char *filename)
532 {
533 struct audio_format_handler *afh = afl + audio_format_id;
534
535 if (!afh->rewrite_tags)
536 return -ERRNO_TO_PARA_ERROR(ENOTSUP);
537 return afh->rewrite_tags(map, mapsize, tags, output_fd, filename);
538 }