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