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