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