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