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