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