]> git.tuebingen.mpg.de Git - paraslash.git/blob - aft.c
afs com_add(): Recognize also audio formats different from mp3.
[paraslash.git] / aft.c
1 #include "para.h"
2 #include "error.h"
3 #include <sys/mman.h>
4 #include <fnmatch.h>
5 #include "afh.h"
6 #include "afs.h"
7 #include "net.h"
8 #include "string.h"
9 #include "vss.h"
10
11 #define AFS_AUDIO_FILE_DIR "/home/mp3"
12
13 static struct osl_table *audio_file_table;
14
15 /**
16  * Describes the layout of the mmapped-afs info struct.
17  *
18  * \sa struct afs_info.
19  */
20 enum afsi_offsets {
21         /** Where .last_played is stored. */
22         AFSI_LAST_PLAYED_OFFSET = 0,
23         /** Storage position of the attributes bitmap. */
24         AFSI_ATTRIBUTES_OFFSET = 8,
25         /** Storage position of the .num_played field. */
26         AFSI_NUM_PLAYED_OFFSET = 16,
27         /** Storage position of the .image_id field. */
28         AFSI_IMAGE_ID_OFFSET = 20,
29         /** Storage position of the .lyrics_id field. */
30         AFSI_LYRICS_ID_OFFSET = 24,
31         /** Storage position of the .audio_format_id field. */
32         AFSI_AUDIO_FORMAT_ID_OFFSET = 28,
33         /** On-disk storage space needed. */
34         AFSI_SIZE = 29
35 };
36
37 /**
38  * Convert a struct afs_info to an osl object.
39  *
40  * \param afsi Pointer to the audio file info to be converted.
41  * \param obj Result pointer.
42  *
43  * \sa load_afsi().
44  */
45 void save_afsi(struct afs_info *afsi, struct osl_object *obj)
46 {
47         char *buf = obj->data;
48
49         write_u64(buf + AFSI_LAST_PLAYED_OFFSET, afsi->last_played);
50         write_u64(buf + AFSI_ATTRIBUTES_OFFSET, afsi->attributes);
51         write_u32(buf + AFSI_NUM_PLAYED_OFFSET, afsi->num_played);
52         write_u32(buf + AFSI_IMAGE_ID_OFFSET, afsi->image_id);
53         write_u32(buf + AFSI_LYRICS_ID_OFFSET, afsi->lyrics_id);
54         write_u8(buf + AFSI_AUDIO_FORMAT_ID_OFFSET,
55                 afsi->audio_format_id);
56 }
57
58 /**
59  *  Get the audio file selector info struct stored in an osl object.
60  *
61  * \param afsi Points to the audio_file info structure to be filled in.
62  * \param obj The osl object holding the data.
63  *
64  * \return Positive on success, negative on errors. Possible errors: \p E_BAD_AFS.
65  *
66  * \sa save_afsi().
67  */
68 int load_afsi(struct afs_info *afsi, struct osl_object *obj)
69 {
70         char *buf = obj->data;
71         if (obj->size < AFSI_SIZE)
72                 return -E_BAD_AFS;
73         afsi->last_played = read_u64(buf + AFSI_LAST_PLAYED_OFFSET);
74         afsi->attributes = read_u64(buf + AFSI_ATTRIBUTES_OFFSET);
75         afsi->num_played = read_u32(buf + AFSI_NUM_PLAYED_OFFSET);
76         afsi->image_id = read_u32(buf + AFSI_IMAGE_ID_OFFSET);
77         afsi->lyrics_id = read_u32(buf + AFSI_LYRICS_ID_OFFSET);
78         afsi->audio_format_id = read_u8(buf +
79                 AFSI_AUDIO_FORMAT_ID_OFFSET);
80         return 1;
81 }
82
83 /** The columns of the audio file table. */
84 enum audio_file_table_columns {
85         /** The hash on the content of the audio file. */
86         AFTCOL_HASH,
87         /** The full path in the filesystem. */
88         AFTCOL_PATH,
89         /** The audio file selector info. */
90         AFTCOL_AFSI,
91         /** The audio format handler info. */
92         AFTCOL_AFHI,
93         /** The chunk table info and the chunk table of the audio file. */
94         AFTCOL_CHUNKS,
95         /** The number of columns of this table. */
96         NUM_AFT_COLUMNS
97 };
98
99 static struct osl_column_description aft_cols[] = {
100         [AFTCOL_HASH] = {
101                 .storage_type = OSL_MAPPED_STORAGE,
102                 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE | OSL_UNIQUE,
103                 .name = "hash",
104                 .compare_function = osl_hash_compare,
105                 .data_size = HASH_SIZE
106         },
107         [AFTCOL_PATH] = {
108                 .storage_type = OSL_MAPPED_STORAGE,
109                 .storage_flags = OSL_RBTREE | OSL_UNIQUE,
110                 .name = "path",
111                 .compare_function = string_compare,
112         },
113         [AFTCOL_AFSI] = {
114                 .storage_type = OSL_MAPPED_STORAGE,
115                 .storage_flags = OSL_FIXED_SIZE,
116                 .name = "afs_info",
117                 .data_size = AFSI_SIZE
118         },
119         [AFTCOL_AFHI] = {
120                 .storage_type = OSL_MAPPED_STORAGE,
121                 .name = "afh_info",
122         },
123         [AFTCOL_CHUNKS] = {
124                 .storage_type = OSL_DISK_STORAGE,
125                 .name = "chunks",
126         }
127 };
128
129 static const struct osl_table_description audio_file_table_desc = {
130         .dir = DATABASE_DIR,
131         .name = "audio_files",
132         .num_columns = NUM_AFT_COLUMNS,
133         .flags = OSL_LARGE_TABLE,
134         .column_descriptions = aft_cols
135 };
136
137 static char *prefix_path(const char *prefix, int len, const char *path)
138 {
139         int speclen;
140         char *n;
141
142         for (;;) {
143                 char c;
144                 if (*path != '.')
145                         break;
146                 c = path[1];
147                 /* "." */
148                 if (!c) {
149                         path++;
150                         break;
151                 }
152                 /* "./" */
153                 if (c == '/') {
154                         path += 2;
155                         continue;
156                 }
157                 if (c != '.')
158                         break;
159                 c = path[2];
160                 if (!c)
161                         path += 2;
162                 else if (c == '/')
163                         path += 3;
164                 else
165                         break;
166                 /* ".." and "../" */
167                 /* Remove last component of the prefix */
168                 do {
169                         if (!len)
170                                 return NULL;
171                         len--;
172                 } while (len && prefix[len-1] != '/');
173                 continue;
174         }
175         if (!len)
176                 return para_strdup(path);
177         speclen = strlen(path);
178         n = para_malloc(speclen + len + 1);
179         memcpy(n, prefix, len);
180         memcpy(n + len, path, speclen+1);
181         return n;
182 }
183
184 /*
185  * We fundamentally don't like some paths: we don't want
186  * dot or dot-dot anywhere.
187  *
188  * Also, we don't want double slashes or slashes at the
189  * end that can make pathnames ambiguous.
190  */
191 static int verify_dotfile(const char *rest)
192 {
193         /*
194          * The first character was '.', but that has already been discarded, we
195          * now test the rest.
196          */
197         switch (*rest) {
198         /* "." is not allowed */
199         case '\0': case '/':
200                 return 1;
201
202         case '.':
203                 if (rest[1] == '\0' || rest[1] == '/')
204                         return -1;
205         }
206         return 1;
207 }
208
209 static int verify_path(const char *path, char **resolved_path)
210 {
211         const char *orig_path = path;
212         char c;
213         const char prefix[] = AFS_AUDIO_FILE_DIR "/";
214         const size_t prefix_len = strlen(prefix);
215
216         PARA_DEBUG_LOG("path: %s\n", path);
217         c = *path++;
218         if (!c)
219                 return -E_BAD_PATH;
220         while (c) {
221                 if (c == '/') {
222                         c = *path++;
223                         switch (c) {
224                         default:
225                                 continue;
226                         case '/': case '\0':
227                                 break;
228                         case '.':
229                                 if (verify_dotfile(path) > 0)
230                                         continue;
231                         }
232                         *resolved_path = NULL;
233                         return -E_BAD_PATH;
234                 }
235                 c = *path++;
236         }
237         if (*orig_path == '/')
238                 *resolved_path = prefix_path("", 0, orig_path);
239         else
240                 *resolved_path = prefix_path(prefix, prefix_len, orig_path);
241         PARA_DEBUG_LOG("resolved: %s\n", *resolved_path);
242         return *resolved_path? 1: -E_BAD_PATH;
243 }
244
245 enum afhi_offsets {
246         AFHI_SECONDS_TOTAL_OFFSET = 0,
247         AFHI_BITRATE_OFFSET = 4,
248         AFHI_FREQUENCY_OFFSET = 8,
249         AFHI_CHANNELS_OFFSET = 12,
250         AFHI_INFO_STRING_OFFSET = 13,
251         MIN_AFHI_SIZE = 14
252 };
253
254 static unsigned sizeof_afhi_buf(const struct audio_format_info *afhi)
255 {
256         if (!afhi)
257                 return 0;
258         return strlen(afhi->info_string) + MIN_AFHI_SIZE;
259 }
260
261 static void save_afhi(struct audio_format_info *afhi, char *buf)
262 {
263         if (!afhi)
264                 return;
265         write_u32(buf + AFHI_SECONDS_TOTAL_OFFSET,
266                 afhi->seconds_total);
267         write_u32(buf + AFHI_BITRATE_OFFSET, afhi->bitrate);
268         write_u32(buf + AFHI_FREQUENCY_OFFSET, afhi->frequency);
269         write_u8(buf + AFHI_CHANNELS_OFFSET, afhi->channels);
270         strcpy(buf + AFHI_INFO_STRING_OFFSET, afhi->info_string); /* OK */
271         PARA_DEBUG_LOG("last byte written: %p\n", buf + AFHI_INFO_STRING_OFFSET + strlen(afhi->info_string));
272 }
273
274 static void load_afhi(const char *buf, struct audio_format_info *afhi)
275 {
276         afhi->seconds_total = read_u32(buf + AFHI_SECONDS_TOTAL_OFFSET);
277         afhi->bitrate = read_u32(buf + AFHI_BITRATE_OFFSET);
278         afhi->frequency = read_u32(buf + AFHI_FREQUENCY_OFFSET);
279         afhi->channels = read_u8(buf + AFHI_CHANNELS_OFFSET);
280         strcpy(afhi->info_string, buf + AFHI_INFO_STRING_OFFSET);
281 }
282
283 static unsigned sizeof_chunk_info_buf(struct audio_format_info *afhi)
284 {
285         if (!afhi)
286                 return 0;
287         return 4 * afhi->chunks_total + 20;
288
289 }
290
291 /** The offsets of the data contained in the AFTCOL_CHUNKS column. */
292 enum chunk_info_offsets {
293         /** The total number of chunks (4 bytes). */
294         CHUNKS_TOTAL_OFFSET = 0,
295         /** The length of the audio file header (4 bytes). */
296         HEADER_LEN_OFFSET = 4,
297         /** The start of the audio file header (4 bytes). */
298         HEADER_OFFSET_OFFSET = 8,
299         /** The seconds part of the chunk time (4 bytes). */
300         CHUNK_TV_TV_SEC_OFFSET = 12,
301         /** The microseconds part of the chunk time (4 bytes). */
302         CHUNK_TV_TV_USEC = 16,
303         /** Chunk table entries start here. */
304         CHUNK_TABLE_OFFSET = 20,
305 };
306
307 /* TODO: audio format handlers could just produce this */
308 static void save_chunk_info(struct audio_format_info *afhi, char *buf)
309 {
310         int i;
311
312         if (!afhi)
313                 return;
314         write_u32(buf + CHUNKS_TOTAL_OFFSET, afhi->chunks_total);
315         write_u32(buf + HEADER_LEN_OFFSET, afhi->header_len);
316         write_u32(buf + HEADER_OFFSET_OFFSET, afhi->header_offset);
317         write_u32(buf + CHUNK_TV_TV_SEC_OFFSET, afhi->chunk_tv.tv_sec);
318         write_u32(buf + CHUNK_TV_TV_USEC, afhi->chunk_tv.tv_usec);
319         for (i = 0; i < afhi->chunks_total; i++)
320                 write_u32(buf + CHUNK_TABLE_OFFSET + 4 * i, afhi->chunk_table[i]);
321 }
322
323 static int load_chunk_info(struct osl_object *obj, struct audio_format_info *afhi)
324 {
325         char *buf = obj->data;
326         int i;
327
328         if (obj->size < CHUNK_TABLE_OFFSET)
329                 return -E_BAD_DATA_SIZE;
330
331         afhi->chunks_total = read_u32(buf + CHUNKS_TOTAL_OFFSET);
332         afhi->header_len = read_u32(buf + HEADER_LEN_OFFSET);
333         afhi->header_offset = read_u32(buf + HEADER_OFFSET_OFFSET);
334         afhi->chunk_tv.tv_sec = read_u32(buf + CHUNK_TV_TV_SEC_OFFSET);
335         afhi->chunk_tv.tv_usec = read_u32(buf + CHUNK_TV_TV_USEC);
336
337         if (afhi->chunks_total * 4 + CHUNK_TABLE_OFFSET > obj->size)
338                 return -E_BAD_DATA_SIZE;
339         afhi->chunk_table = para_malloc(afhi->chunks_total * sizeof(size_t));
340         for (i = 0; i < afhi->chunks_total; i++)
341                 afhi->chunk_table[i] = read_u32(buf + CHUNK_TABLE_OFFSET + 4 * i);
342         return 1;
343 }
344
345 /**
346  * Get the row of the audio file table corresponding to the given path.
347  *
348  * \param path The full path of the audio file.
349  * \param row Result pointer.
350  *
351  * \return The return value of the underlying call to osl_get_row().
352  */
353 int aft_get_row_of_path(char *path, struct osl_row **row)
354 {
355         struct osl_object obj = {.data = path, .size = strlen(path) + 1};
356
357         PARA_NOTICE_LOG("audio_file_table: %p\n", audio_file_table);
358         return osl_get_row(audio_file_table, AFTCOL_PATH, &obj, row);
359 }
360
361 /**
362  * Get the row of the audio file table corresponding to the given hash value.
363  *
364  * \param hash The hash value of the desired audio file.
365  * \param row resul pointer.
366  *
367  * \return The return value of the underlying call to osl_get_row().
368  */
369 int aft_get_row_of_hash(HASH_TYPE *hash, struct osl_row **row)
370 {
371         const struct osl_object obj = {.data = hash, .size = HASH_SIZE};
372         return osl_get_row(audio_file_table, AFTCOL_HASH, &obj, row);
373 }
374
375 /**
376  * Get the osl object holding the audio file selector info of a row.
377  *
378  * \param row Pointer to a row in the audio file table.
379  * \param obj Result pointer.
380  *
381  * \return The return value of the underlying call to osl_get_object().
382  */
383 int get_afsi_object_of_row(const void *row, struct osl_object *obj)
384 {
385         return osl_get_object(audio_file_table, row, AFTCOL_AFSI, obj);
386 }
387
388 /**
389  * Get the osl object holding the audio file selector info, given a path.
390  *
391  *
392  * \param path The full path of the audio file.
393  * \param obj Result pointer.
394  *
395  * \return Positive on success, negative on errors.
396  */
397 int get_afsi_object_of_path(char *path, struct osl_object *obj)
398 {
399         struct osl_row *row;
400         int ret = aft_get_row_of_path(path, &row);
401         if (ret < 0)
402                 return ret;
403         return get_afsi_object_of_row(row, obj);
404 }
405
406 /**
407  * Get the audio file selector info, given a row of the audio file table.
408  *
409  * \param row Pointer to a row in the audio file table.
410  * \param afsi Result pointer.
411  *
412  * \return Positive on success, negative on errors.
413  */
414 int get_afsi_of_row(const struct osl_row *row, struct afs_info *afsi)
415 {
416         struct osl_object obj;
417         int ret = get_afsi_object_of_row(row, &obj);
418         if (ret < 0)
419                 return ret;
420         return load_afsi(afsi, &obj);
421 }
422
423 /**
424  * Get the path of an audio file, given a row of the audio file table.
425  *
426  * \param row Pointer to a row in the audio file table.
427  * \param path Result pointer.
428  *
429  * \return Positive on success, negative on errors.
430  */
431 int get_audio_file_path_of_row(const struct osl_row *row, char **path)
432 {
433         struct osl_object path_obj;
434         int ret = osl_get_object(audio_file_table, row, AFTCOL_PATH,
435                 &path_obj);
436         if (ret < 0)
437                 return ret;
438         *path = path_obj.data;
439         return 1;
440 }
441
442 /**
443  * Get the object containing the hash value of an audio file, given a row.
444  *
445  * \param row Pointer to a row of the audio file table.
446  * \param obj Result pointer.
447  *
448  * \return The return value of the underlying call to osl_get_object().
449  *
450  * \sa get_hash_of_row().
451  */
452 int get_hash_object_of_aft_row(const void *row, struct osl_object *obj)
453 {
454         return osl_get_object(audio_file_table, row, AFTCOL_HASH, obj);
455 }
456
457 /**
458  * Get the hash value of an audio file, given a row of the audio file table.
459  *
460  * \param row Pointer to a row of the audio file table.
461  * \param hash Result pointer.
462  *
463  * \a hash points to mapped data and must not be freed by the caller.
464  *
465  * \return The return value of the underlying call to
466  * get_hash_object_of_aft_row().
467  */
468 static int get_hash_of_row(const void *row, HASH_TYPE **hash)
469 {
470         struct osl_object obj;
471         int ret = get_hash_object_of_aft_row(row, &obj);
472
473         if (ret < 0)
474                 return ret;
475         *hash = obj.data;
476         return 1;
477 }
478
479 /**
480  * Get the audio format handler info, given a row of the audio file table.
481  *
482  * \param row Pointer to a row of the audio file table.
483  * \param afhi Result pointer.
484  *
485  * \return The return value of the underlying call to osl_get_object().
486  *
487  * \sa get_chunk_table_of_row().
488  */
489 int get_afhi_of_row(const void *row, struct audio_format_info *afhi)
490 {
491         struct osl_object obj;
492         int ret = osl_get_object(audio_file_table, row, AFTCOL_AFHI,
493                 &obj);
494         if (ret < 0)
495                 return ret;
496         load_afhi(obj.data, afhi);
497         return 1;
498 }
499
500 /**
501  * Get the chunk table of an audio file, given a row of the audio file table.
502  *
503  * \param row Pointer to a row of the audio file table.
504  * \param afhi Result pointer.
505  *
506  * \return The return value of the underlying call to osl_open_disk_object().
507  *
508  * \sa get_afhi_of_row().
509  */
510 int get_chunk_table_of_row(const void *row, struct audio_format_info *afhi)
511 {
512         struct osl_object obj;
513         int ret = osl_open_disk_object(audio_file_table, row, AFTCOL_CHUNKS,
514                 &obj);
515         if (ret < 0)
516                 return ret;
517         ret = load_chunk_info(&obj, afhi);
518         osl_close_disk_object(&obj);
519         return ret;
520 }
521
522 /**
523  * Mmap the given audio file and update statistics.
524  *
525  * \param aft_row Determines the audio file to be opened and updated.
526  * \param afd Result pointer.
527  *
528  * On success, the numplayed field of the audio file selector info is increased
529  * and the lastplayed time is set to the current time. Finally, the score of
530  * the audio file is updated.
531  *
532  * \return Positive on success, negative on errors.
533  */
534 int open_and_update_audio_file(struct osl_row *aft_row, struct audio_file_data *afd)
535 {
536         HASH_TYPE *aft_hash, file_hash[HASH_SIZE];
537         struct osl_object afsi_obj;
538         struct afs_info new_afsi;
539         int ret = get_hash_of_row(aft_row, &aft_hash);
540
541         if (ret < 0)
542                 return ret;
543         ret = get_audio_file_path_of_row(aft_row, &afd->path);
544         if (ret < 0)
545                 return ret;
546         ret = get_afsi_object_of_row(aft_row, &afsi_obj);
547         if (ret < 0)
548                 return ret;
549         ret = load_afsi(&afd->afsi, &afsi_obj);
550         if (ret < 0)
551                 return ret;
552         ret = get_afhi_of_row(aft_row, &afd->afhi);
553         if (ret < 0)
554                 return ret;
555         ret = get_chunk_table_of_row(aft_row, &afd->afhi);
556         if (ret < 0)
557                 return ret;
558         ret = mmap_full_file(afd->path, O_RDONLY, &afd->map);
559         if (ret < 0)
560                 goto err;
561         hash_function(afd->map.data, afd->map.size, file_hash);
562         ret = -E_HASH_MISMATCH;
563         if (hash_compare(file_hash, aft_hash))
564                 goto err;
565         new_afsi = afd->afsi;
566         new_afsi.num_played++;
567         new_afsi.last_played = time(NULL);
568         save_afsi(&new_afsi, &afsi_obj); /* in-place update */
569         if (afd->current_play_mode == PLAY_MODE_PLAYLIST)
570                 ret = playlist_update_audio_file(aft_row);
571         else
572                 ret = mood_update_audio_file(aft_row, &afd->afsi);
573         return ret;
574 err:
575         free(afd->afhi.chunk_table);
576         return ret;
577 }
578
579 time_t now;
580
581 static int get_local_time(uint64_t *seconds, char *buf, size_t size)
582 {
583         struct tm t;
584
585         if (!localtime_r((time_t *)seconds, &t))
586                 return -E_LOCALTIME;
587         if (*seconds + 6 * 30 * 24 * 3600 > now) {
588                 if (!strftime(buf, size, "%b %e %k:%M", &t))
589                         return -E_STRFTIME;
590                 return 1;
591         }
592         if (!strftime(buf, size, "%b %e  %Y", &t))
593                 return -E_STRFTIME;
594         return 1;
595 }
596
597 #define GET_NUM_DIGITS(x, num) { \
598         typeof((x)) _tmp = PARA_ABS(x); \
599         *num = 1; \
600         if ((x)) \
601                 while ((_tmp) > 9) { \
602                         (_tmp) /= 10; \
603                         (*num)++; \
604                 } \
605         }
606
607 static short unsigned get_duration(int seconds_total, char *buf, short unsigned max_width)
608 {
609         short unsigned width;
610         int s = seconds_total;
611         unsigned hours = s / 3600, mins = (s % 3600) / 60, secs = s % 60;
612
613         if (s < 3600) { /* less than one hour => m:ss or mm:ss */
614                 GET_NUM_DIGITS(mins, &width); /* 1 or 2 */
615                 width += 3; /* 4 or 5 */
616                 if (buf)
617                         sprintf(buf, "%*u:%02u", max_width - width + 1, mins, secs);
618                 return width;
619         }
620         /* more than one hour => h:mm:ss, hh:mm:ss, hhh:mm:ss, ... */
621         GET_NUM_DIGITS(hours, &width);
622         width += 6;
623         if (buf)
624                 sprintf(buf, "%*u:%02u:%02u", max_width - width + 1, hours, mins, secs);
625         return width;
626 }
627
628 static char *make_attribute_line(const char *att_bitmap, struct afs_info *afsi)
629 {
630         char *att_text, *att_line;
631
632         get_attribute_text(&afsi->attributes, " ", &att_text);
633         if (!att_text)
634                 return para_strdup(att_bitmap);
635         att_line = make_message("%s (%s)", att_bitmap, att_text);
636         free(att_text);
637         return att_line;
638 }
639
640 static char *make_lyrics_line(struct afs_info *afsi)
641 {
642         char *lyrics_name;
643         lyr_get_name_by_id(afsi->lyrics_id, &lyrics_name);
644         if (!lyrics_name)
645                 return make_message("%u", afsi->lyrics_id);
646         return make_message("%u (%s)", afsi->lyrics_id, lyrics_name);
647 }
648
649 static char *make_image_line(struct afs_info *afsi)
650 {
651         char *image_name;
652         img_get_name_by_id(afsi->image_id, &image_name);
653         if (!image_name)
654                 return make_message("%u", afsi->image_id);
655         return make_message("%u (%s)", afsi->image_id, image_name);
656 }
657
658 static int print_list_item(struct ls_data *d, struct ls_options *opts,
659         struct para_buffer *b)
660 {
661         int ret;
662         char att_buf[65];
663         char last_played_time[30];
664         char duration_buf[30]; /* nobody has an audio file long enough to overflow this */
665         char score_buf[30] = "";
666         struct afs_info *afsi = &d->afsi;
667         struct audio_format_info *afhi = &d->afhi;
668         struct ls_widths *w = &opts->widths;
669         int have_score = opts->flags & LS_FLAG_ADMISSIBLE_ONLY;
670
671         if (opts->mode == LS_MODE_SHORT) {
672                 para_printf(b, "%s\n", d->path);
673                 return 1;
674         }
675         get_attribute_bitmap(&afsi->attributes, att_buf);
676         ret = get_local_time(&afsi->last_played, last_played_time,
677                 sizeof(last_played_time));
678         if (ret < 0)
679                 return ret;
680         get_duration(afhi->seconds_total, duration_buf, w->duration_width);
681         if (have_score) {
682                 if (opts->mode == LS_MODE_LONG)
683                         sprintf(score_buf, "%*li ", w->score_width, d->score);
684                 else
685                         sprintf(score_buf, "%li ", d->score);
686         }
687
688         if (opts->mode == LS_MODE_LONG) {
689                 para_printf(b,
690                         "%s"    /* score */
691                         "%s "   /* attributes */
692                         "%*d "  /* image_id  */
693                         "%*d "  /* lyrics_id */
694                         "%*d "  /* bitrate */
695                         "%s "   /* audio format */
696                         "%*d "  /* frequency */
697                         "%d "   /* channels */
698                         "%s "   /* duration */
699                         "%*d "  /* num_played */
700                         "%s "   /* last_played */
701                         "%s\n", /* path */
702                         score_buf,
703                         att_buf,
704                         w->image_id_width, afsi->image_id,
705                         w->lyrics_id_width, afsi->lyrics_id,
706                         w->bitrate_width, afhi->bitrate,
707                         audio_format_name(afsi->audio_format_id), /* FIXME */
708                         w->frequency_width, afhi->frequency,
709                         afhi->channels,
710                         duration_buf,
711                         w->num_played_width, afsi->num_played,
712                         last_played_time,
713                         d->path
714                 );
715                 return 1;
716         }
717         if (opts->mode == LS_MODE_VERBOSE) {
718                 char asc_hash[2 * HASH_SIZE + 1];
719                 char *att_line, *lyrics_line, *image_line;
720
721                 hash_to_asc(d->hash, asc_hash);
722                 att_line = make_attribute_line(att_buf, afsi);
723                 lyrics_line = make_lyrics_line(afsi);
724                 image_line = make_image_line(afsi);
725                 para_printf(b,
726                         "%s: %s\n" /* path */
727                         "%s%s%s" /* score */
728                         "attributes: %s\n"
729                         "hash: %s\n"
730                         "image_id: %s\n"
731                         "lyrics_id: %s\n"
732                         "bitrate: %dkbit/s\n"
733                         "format: %s\n"
734                         "frequency: %dHz\n"
735                         "channels: %d\n"
736                         "duration: %s\n"
737                         "num_played: %d\n"
738                         "last_played: %s\n\n",
739                         (opts->flags & LS_FLAG_FULL_PATH)?
740                                 "path" : "file", d->path,
741                         have_score? "score: " : "", score_buf,
742                                 have_score? "\n" : "",
743                         att_line,
744                         asc_hash,
745                         image_line,
746                         lyrics_line,
747                         afhi->bitrate,
748                         "mp3", /* FIXME */
749                         afhi->frequency,
750                         afhi->channels,
751                         duration_buf,
752                         afsi->num_played,
753                         last_played_time
754                 );
755                 free(att_line);
756                 free(lyrics_line);
757                 free(image_line);
758                 return 1;
759         }
760         return 1;
761 }
762
763 static int ls_audio_format_compare(const void *a, const void *b)
764 {
765         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
766         return NUM_COMPARE(d1->afsi.audio_format_id, d2->afsi.audio_format_id);
767 }
768
769 static int ls_duration_compare(const void *a, const void *b)
770 {
771         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
772         return NUM_COMPARE(d1->afhi.seconds_total, d2->afhi.seconds_total);
773 }
774
775 static int ls_bitrate_compare(const void *a, const void *b)
776 {
777         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
778         return NUM_COMPARE(d1->afhi.bitrate, d2->afhi.bitrate);
779 }
780
781 static int ls_lyrics_id_compare(const void *a, const void *b)
782 {
783         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
784         return NUM_COMPARE(d1->afsi.lyrics_id, d2->afsi.lyrics_id);
785 }
786
787 static int ls_image_id_compare(const void *a, const void *b)
788 {
789         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
790         return NUM_COMPARE(d1->afsi.image_id, d2->afsi.image_id);
791 }
792
793 static int ls_channels_compare(const void *a, const void *b)
794 {
795         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
796         return NUM_COMPARE(d1->afhi.channels, d2->afhi.channels);
797 }
798
799 static int ls_frequency_compare(const void *a, const void *b)
800 {
801         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
802         return NUM_COMPARE(d1->afhi.frequency, d2->afhi.frequency);
803 }
804
805 static int ls_num_played_compare(const void *a, const void *b)
806 {
807         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
808         return NUM_COMPARE(d1->afsi.num_played, d2->afsi.num_played);
809 }
810
811 static int ls_last_played_compare(const void *a, const void *b)
812 {
813         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
814         return NUM_COMPARE(d1->afsi.last_played, d2->afsi.last_played);
815 }
816
817 static int ls_score_compare(const void *a, const void *b)
818 {
819         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
820         return NUM_COMPARE(d1->score, d2->score);
821 }
822
823 static int ls_path_compare(const void *a, const void *b)
824 {
825         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
826         return strcmp(d1->path, d2->path);
827 }
828
829 static int sort_matching_paths(struct ls_options *options)
830 {
831         size_t nmemb = options->num_matching_paths;
832         size_t size = sizeof(uint32_t);
833         int (*compar)(const void *, const void *);
834         int i;
835
836         options->data_ptr = para_malloc(nmemb * sizeof(*options->data_ptr));
837         for (i = 0; i < nmemb; i++)
838                 options->data_ptr[i] = options->data + i;
839
840         /* In these cases the array is already sorted */
841         if (options->sorting == LS_SORT_BY_PATH
842                 && !(options->flags & LS_FLAG_ADMISSIBLE_ONLY)
843                 && (options->flags & LS_FLAG_FULL_PATH))
844                 return 1;
845         if (options->sorting == LS_SORT_BY_SCORE &&
846                         options->flags & LS_FLAG_ADMISSIBLE_ONLY)
847                 return 1;
848
849         switch (options->sorting) {
850         case LS_SORT_BY_PATH:
851                 compar = ls_path_compare; break;
852         case LS_SORT_BY_SCORE:
853                 compar = ls_score_compare; break;
854         case LS_SORT_BY_LAST_PLAYED:
855                 compar = ls_last_played_compare; break;
856         case LS_SORT_BY_NUM_PLAYED:
857                 compar = ls_num_played_compare; break;
858         case LS_SORT_BY_FREQUENCY:
859                 compar = ls_frequency_compare; break;
860         case LS_SORT_BY_CHANNELS:
861                 compar = ls_channels_compare; break;
862         case LS_SORT_BY_IMAGE_ID:
863                 compar = ls_image_id_compare; break;
864         case LS_SORT_BY_LYRICS_ID:
865                 compar = ls_lyrics_id_compare; break;
866         case LS_SORT_BY_BITRATE:
867                 compar = ls_bitrate_compare; break;
868         case LS_SORT_BY_DURATION:
869                 compar = ls_duration_compare; break;
870         case LS_SORT_BY_AUDIO_FORMAT:
871                 compar = ls_audio_format_compare; break;
872         default:
873                 return -E_BAD_SORT;
874         }
875         qsort(options->data_ptr, nmemb, size, compar);
876         return 1;
877 }
878
879 /* row is either an aft_row or a row of the score table */
880 /* TODO: Only compute widths if we need them */
881 static int prepare_ls_row(struct osl_row *row, void *ls_opts)
882 {
883         int ret, i;
884         struct ls_options *options = ls_opts;
885         struct ls_data *d;
886         struct ls_widths *w;
887         unsigned short num_digits;
888         unsigned tmp;
889         struct osl_row *aft_row;
890         long score;
891         char *path;
892
893         if (options->flags & LS_FLAG_ADMISSIBLE_ONLY) {
894                 ret = get_score_and_aft_row(row, &score, &aft_row);
895                 if (ret < 0)
896                         return ret;
897         } else
898                 aft_row = row;
899         ret = get_audio_file_path_of_row(aft_row, &path);
900         if (ret < 0)
901                 return ret;
902         if (!(options->flags & LS_FLAG_FULL_PATH)) {
903                 char *p = strrchr(path, '/');
904                 if (p)
905                         path = p + 1;
906         }
907         if (options->num_patterns) {
908                 for (i = 0; i < options->num_patterns; i++) {
909                         ret = fnmatch(options->patterns[i], path, FNM_PATHNAME);
910                         if (!ret)
911                                 break;
912                         if (ret == FNM_NOMATCH)
913                                 continue;
914                         return -E_FNMATCH;
915                 }
916                 if (i >= options->num_patterns) /* no match */
917                         return 1;
918         }
919         tmp = options->num_matching_paths++;
920         if (options->num_matching_paths > options->array_size) {
921                 options->array_size++;
922                 options->array_size *= 2;
923                 options->data = para_realloc(options->data, options->array_size
924                         * sizeof(*options->data));
925         }
926         d = options->data + tmp;
927         ret = get_afsi_of_row(aft_row, &d->afsi);
928         if (ret < 0)
929                 return ret;
930         ret = get_afhi_of_row(aft_row, &d->afhi);
931         if (ret < 0)
932                 return ret;
933         d->path = path;
934         ret = get_hash_of_row(aft_row, &d->hash);
935         if (ret < 0)
936                 return ret;
937         w = &options->widths;
938         GET_NUM_DIGITS(d->afsi.image_id, &num_digits);
939         w->image_id_width = PARA_MAX(w->image_id_width, num_digits);
940         GET_NUM_DIGITS(d->afsi.lyrics_id, &num_digits);
941         w->lyrics_id_width = PARA_MAX(w->lyrics_id_width, num_digits);
942         GET_NUM_DIGITS(d->afhi.bitrate, &num_digits);
943         w->bitrate_width = PARA_MAX(w->bitrate_width, num_digits);
944         GET_NUM_DIGITS(d->afhi.frequency, &num_digits);
945         w->frequency_width = PARA_MAX(w->frequency_width, num_digits);
946         GET_NUM_DIGITS(d->afsi.num_played, &num_digits);
947         w->num_played_width = PARA_MAX(w->num_played_width, num_digits);
948         /* just get the number of chars to print this amount of time */
949         tmp = get_duration(d->afhi.seconds_total, NULL, 0);
950         w->duration_width = PARA_MAX(w->duration_width, tmp);
951         if (options->flags & LS_FLAG_ADMISSIBLE_ONLY) {
952                 GET_NUM_DIGITS(score, &num_digits);
953                 num_digits++; /* add one for the sign (space or "-") */
954                 w->score_width = PARA_MAX(w->score_width, num_digits);
955                 d->score = score;
956         }
957         return 1;
958 }
959
960 static int com_ls_callback(const struct osl_object *query,
961                 struct osl_object *ls_output)
962 {
963         struct ls_options *opts = query->data;
964         char *p, *pattern_start = (char *)query->data + sizeof(*opts);
965         struct para_buffer b = {.buf = NULL, .size = 0};
966         int i = 0, ret;
967
968         PARA_NOTICE_LOG("%d patterns\n", opts->num_patterns);
969         if (opts->num_patterns) {
970                 opts->patterns = para_malloc(opts->num_patterns * sizeof(char *));
971                 for (i = 0, p = pattern_start; i < opts->num_patterns; i++) {
972                         opts->patterns[i] = p;
973                         p += strlen(p) + 1;
974                         PARA_NOTICE_LOG("pattern %d: %s\n", i, opts->patterns[i]);
975                 }
976         } else
977                 opts->patterns = NULL;
978         if (opts->flags & LS_FLAG_ADMISSIBLE_ONLY)
979                 ret = admissible_file_loop(opts, prepare_ls_row);
980         else
981                 ret = osl_rbtree_loop(audio_file_table, AFTCOL_PATH, opts,
982                         prepare_ls_row);
983         if (ret < 0)
984                 goto out;
985         ret = opts->num_patterns? -E_NO_MATCH : 1;
986         if (!opts->num_matching_paths) {
987                 PARA_NOTICE_LOG("no match, ret: %d\n", ret);
988                 goto out;
989         }
990         ret = sort_matching_paths(opts);
991         if (ret < 0)
992                 goto out;
993         if (opts->flags & LS_FLAG_REVERSE)
994                 for (i = opts->num_matching_paths - 1; i >= 0; i--) {
995                         ret = print_list_item(opts->data_ptr[i], opts, &b);
996                         if (ret < 0)
997                                 break;
998                 }
999         else
1000                 for (i = 0; i < opts->num_matching_paths; i++) {
1001                         ret = print_list_item(opts->data_ptr[i], opts, &b);
1002                         if (ret < 0)
1003                                 break;
1004                 }
1005         ret = 1;
1006 out:
1007         ls_output->data = b.buf;
1008         ls_output->size = b.size;
1009         free(opts->data);
1010         free(opts->data_ptr);
1011         free(opts->patterns);
1012         return ret;
1013 }
1014
1015 /*
1016  * TODO: flags -h (sort by hash)
1017  *
1018  * long list: list hash, attributes as (xx--x-x-), file size, lastplayed
1019  * full list: list everything, including afsi, afhi, atts as clear text
1020  *
1021  * */
1022 int com_afs_ls(int fd, int argc, char * const * const argv)
1023 {
1024         int i, ret;
1025         unsigned flags = 0;
1026         enum ls_sorting_method sort = LS_SORT_BY_PATH;
1027         enum ls_listing_mode mode = LS_MODE_SHORT;
1028         struct ls_options opts = {.patterns = NULL};
1029         struct osl_object query = {.data = &opts, .size = sizeof(opts)},
1030                 ls_output;
1031
1032         for (i = 1; i < argc; i++) {
1033                 const char *arg = argv[i];
1034                 if (arg[0] != '-')
1035                         break;
1036                 if (!strcmp(arg, "--")) {
1037                         i++;
1038                         break;
1039                 }
1040                 if (!strncmp(arg, "-l", 2)) {
1041                         if (!*(arg + 2)) {
1042                                 mode = LS_MODE_LONG;
1043                                 continue;
1044                         }
1045                         if (*(arg + 3))
1046                                 return -E_AFT_SYNTAX;
1047                         switch(*(arg + 2)) {
1048                         case 's':
1049                                 mode = LS_MODE_SHORT;
1050                                 continue;
1051                         case 'l':
1052                                 mode = LS_MODE_LONG;
1053                                 continue;
1054                         case 'v':
1055                                 mode = LS_MODE_VERBOSE;
1056                                 continue;
1057                         case 'm':
1058                                 mode = LS_MODE_MBOX;
1059                                 continue;
1060                         default:
1061                                 return -E_AFT_SYNTAX;
1062                         }
1063                 }
1064                 if (!strcmp(arg, "-p")) {
1065                         flags |= LS_FLAG_FULL_PATH;
1066                         continue;
1067                 }
1068                 if (!strcmp(arg, "-a")) {
1069                         flags |= LS_FLAG_ADMISSIBLE_ONLY;
1070                         continue;
1071                 }
1072                 if (!strcmp(arg, "-r")) {
1073                         flags |= LS_FLAG_REVERSE;
1074                         continue;
1075                 }
1076                 if (!strncmp(arg, "-s", 2)) {
1077                         if (!*(arg + 2) || *(arg + 3))
1078                                 return -E_AFT_SYNTAX;
1079                         switch(*(arg + 2)) {
1080                         case 'p':
1081                                 sort = LS_SORT_BY_PATH;
1082                                 continue;
1083                         case 's': /* -ss implies -a */
1084                                 sort = LS_SORT_BY_SCORE;
1085                                 flags |= LS_FLAG_ADMISSIBLE_ONLY;
1086                                 continue;
1087                         case 'l':
1088                                 sort = LS_SORT_BY_LAST_PLAYED;
1089                                 continue;
1090                         case 'n':
1091                                 sort = LS_SORT_BY_NUM_PLAYED;
1092                                 continue;
1093                         case 'f':
1094                                 sort = LS_SORT_BY_FREQUENCY;
1095                                 continue;
1096                         case 'c':
1097                                 sort = LS_SORT_BY_CHANNELS;
1098                                 continue;
1099                         case 'i':
1100                                 sort = LS_SORT_BY_IMAGE_ID;
1101                                 continue;
1102                         case 'y':
1103                                 sort = LS_SORT_BY_LYRICS_ID;
1104                                 continue;
1105                         case 'b':
1106                                 sort = LS_SORT_BY_BITRATE;
1107                                 continue;
1108                         case 'd':
1109                                 sort = LS_SORT_BY_DURATION;
1110                                 continue;
1111                         case 'a':
1112                                 sort = LS_SORT_BY_AUDIO_FORMAT;
1113                                 continue;
1114                         default:
1115                                 return -E_AFT_SYNTAX;
1116                         }
1117                 }
1118                 return -E_AFT_SYNTAX;
1119         }
1120         time(&now);
1121         opts.flags = flags;
1122         opts.sorting = sort;
1123         opts.mode = mode;
1124         opts.num_patterns = argc - i;
1125         ret = send_option_arg_callback_request(&query, opts.num_patterns,
1126                 argv + i, com_ls_callback, &ls_output);
1127         if (ret >= 0 && ls_output.data) {
1128                 send_buffer(fd, (char *)ls_output.data);
1129                 free(ls_output.data);
1130         }
1131         return ret;
1132 }
1133
1134 /**
1135  * Call the given function for each file in the audio file table.
1136  *
1137  * \param private_data An arbitrary data pointer, passed to \a func.
1138  * \param func The custom function to be called.
1139  *
1140  * \return The return value of the underlying call to osl_rbtree_loop().
1141  */
1142 int audio_file_loop(void *private_data, osl_rbtree_loop_func *func)
1143 {
1144         return osl_rbtree_loop(audio_file_table, AFTCOL_HASH, private_data,
1145                 func);
1146 }
1147
1148 static struct osl_row *find_hash_sister(HASH_TYPE *hash)
1149 {
1150         const struct osl_object obj = {.data = hash, .size = HASH_SIZE};
1151         struct osl_row *row;
1152
1153         osl_get_row(audio_file_table, AFTCOL_HASH, &obj, &row);
1154         return row;
1155 }
1156
1157 enum aft_row_offsets {
1158         AFTROW_AFHI_OFFSET_POS = 0,
1159         AFTROW_CHUNKS_OFFSET_POS = 2,
1160         AFTROW_AUDIO_FORMAT_OFFSET = 4,
1161         AFTROW_FLAGS_OFFSET = 5,
1162         AFTROW_HASH_OFFSET = 9,
1163         AFTROW_PATH_OFFSET = (AFTROW_HASH_OFFSET + HASH_SIZE),
1164 };
1165
1166 /* never save the afsi, as the server knows it too. Note that afhi might be NULL.
1167  * In this case, afhi won't be stored in the buffer  */
1168 static void save_audio_file_info(HASH_TYPE *hash, const char *path,
1169                 struct audio_format_info *afhi, uint32_t flags,
1170                 uint8_t audio_format_num, struct osl_object *obj)
1171 {
1172         size_t path_len = strlen(path) + 1;
1173         size_t afhi_size = sizeof_afhi_buf(afhi);
1174         size_t size = AFTROW_PATH_OFFSET + path_len + afhi_size
1175                 + sizeof_chunk_info_buf(afhi);
1176         char *buf = para_malloc(size);
1177         uint16_t pos;
1178
1179         write_u8(buf + AFTROW_AUDIO_FORMAT_OFFSET, audio_format_num);
1180         write_u32(buf + AFTROW_FLAGS_OFFSET, flags);
1181
1182         memcpy(buf + AFTROW_HASH_OFFSET, hash, HASH_SIZE);
1183         strcpy(buf + AFTROW_PATH_OFFSET, path);
1184
1185         pos = AFTROW_PATH_OFFSET + path_len;
1186         PARA_DEBUG_LOG("size: %zu, afhi starts at %d\n", size, pos);
1187         PARA_DEBUG_LOG("last afhi byte: %p, pos %zu\n", buf + pos + afhi_size - 1,
1188                 pos + afhi_size - 1);
1189         write_u16(buf + AFTROW_AFHI_OFFSET_POS, pos);
1190         save_afhi(afhi, buf + pos);
1191
1192         pos += afhi_size;
1193         PARA_DEBUG_LOG("size: %zu, chunks start at %d\n", size, pos);
1194         write_u16(buf + AFTROW_CHUNKS_OFFSET_POS, pos);
1195         save_chunk_info(afhi, buf + pos);
1196         PARA_DEBUG_LOG("last byte in buf: %p\n", buf + size - 1);
1197         obj->data = buf;
1198         obj->size = size;
1199 }
1200
1201 /*
1202 input:
1203 ~~~~~~
1204 HS:     hash sister
1205 PB:     path brother
1206 F:      force flag given
1207
1208 output:
1209 ~~~~~~~
1210 AFHI:   whether afhi and chunk table are computed and sent
1211 ACTION: table modifications to be performed
1212
1213 +---+----+-----+------+---------------------------------------------------+
1214 | HS | PB | F  | AFHI | ACTION
1215 +---+----+-----+------+---------------------------------------------------+
1216 | Y |  Y |  Y  |  Y   | if HS != PB: remove PB. HS: force afhi update,
1217 |                     | update path, keep afsi
1218 +---+----+-----+------+---------------------------------------------------+
1219 | Y |  Y |  N  |  N   | if HS == PB: do not send callback request at all.
1220 |                     | otherwise: remove PB, HS: update path, keep afhi,
1221 |                     | afsi.
1222 +---+----+-----+------+---------------------------------------------------+
1223 | Y |  N |  Y  |  Y   | (rename) force afhi update of HS, update path of
1224 |                     | HS, keep afsi
1225 +---+----+-----+------+---------------------------------------------------+
1226 | Y |  N |  N  |  N   | (file rename) update path of HS, keep afsi, afhi
1227 +---+----+-----+------+---------------------------------------------------+
1228 | N |  Y |  Y  |  Y   | (file change) update afhi, hash, of PB, keep afsi
1229 |                     | (force has no effect)
1230 +---+----+-----+------+---------------------------------------------------+
1231 | N |  Y |  N  |  Y   | (file change) update afhi, hash of PB, keep afsi
1232 +---+----+-----+------+---------------------------------------------------+
1233 | N |  N |  Y  |  Y   | (new file) create new entry (force has no effect)
1234 +---+----+-----+------+---------------------------------------------------+
1235 | N |  N |  N  |  Y   | (new file) create new entry
1236 +---+----+-----+------+---------------------------------------------------+
1237
1238 afhi <=> force or no HS
1239
1240 */
1241
1242
1243 #define ADD_FLAG_LAZY 1
1244 #define ADD_FLAG_FORCE 2
1245 #define ADD_FLAG_VERBOSE 4
1246
1247 static int com_add_callback(const struct osl_object *query,
1248                 __a_unused struct osl_object *result)
1249 {
1250         char *buf = query->data, *path;
1251         struct osl_row *pb, *aft_row;
1252         const struct osl_row *hs;
1253         struct osl_object objs[NUM_AFT_COLUMNS];
1254         HASH_TYPE *hash;
1255         char asc[2 * HASH_SIZE + 1];
1256         int ret;
1257         char afsi_buf[AFSI_SIZE];
1258         uint32_t flags = read_u32(buf + AFTROW_FLAGS_OFFSET);
1259         struct afs_info default_afsi = {.last_played = 0};
1260
1261         hash = (HASH_TYPE *)buf + AFTROW_HASH_OFFSET;
1262         hash_to_asc(hash, asc);;
1263         objs[AFTCOL_HASH].data = buf + AFTROW_HASH_OFFSET;
1264         objs[AFTCOL_HASH].size = HASH_SIZE;
1265
1266         path = buf + AFTROW_PATH_OFFSET;
1267         objs[AFTCOL_PATH].data = path;
1268         objs[AFTCOL_PATH].size = strlen(path) + 1;
1269
1270         PARA_DEBUG_LOG("request to add %s with hash %s\n", path, asc);
1271         hs = find_hash_sister(hash);
1272         ret = aft_get_row_of_path(path, &pb);
1273         if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1274                 return ret;
1275         if (hs && pb && hs == pb && !(flags & ADD_FLAG_FORCE)) {
1276                 if (flags & ADD_FLAG_VERBOSE)
1277                         PARA_NOTICE_LOG("ignoring duplicate %p\n", path);
1278                 return 1;
1279         }
1280         if (hs && hs != pb) {
1281                 struct osl_object obj;
1282                 if (pb) { /* hs trumps pb, remove pb */
1283                         if (flags & ADD_FLAG_VERBOSE)
1284                                 PARA_NOTICE_LOG("removing path brother\n");
1285                         ret = osl_del_row(audio_file_table, pb);
1286                         if (ret < 0)
1287                                 return ret;
1288                         pb = NULL;
1289                 }
1290                 /* file rename, update hs' path */
1291                 ret = osl_get_object(audio_file_table, hs, AFTCOL_PATH, &obj);
1292                 if (flags & ADD_FLAG_VERBOSE)
1293                         PARA_NOTICE_LOG("rename %s -> %s\n", (char *)obj.data, path);
1294                 ret = osl_update_object(audio_file_table, hs, AFTCOL_PATH,
1295                         &objs[AFTCOL_PATH]);
1296                 if (ret < 0)
1297                         return ret;
1298                 if (!(flags & ADD_FLAG_FORCE))
1299                         return ret;
1300         }
1301         /* no hs or force mode, child must have sent afhi */
1302         uint16_t afhi_offset = read_u16(buf + AFTROW_AFHI_OFFSET_POS);
1303         uint16_t chunks_offset = read_u16(buf + AFTROW_CHUNKS_OFFSET_POS);
1304
1305         objs[AFTCOL_AFHI].data = buf + afhi_offset;
1306         objs[AFTCOL_AFHI].size = chunks_offset - afhi_offset;
1307         if (!objs[AFTCOL_AFHI].size) /* "impossible" */
1308                 return -E_NO_AFHI;
1309         objs[AFTCOL_CHUNKS].data = buf + chunks_offset;
1310         objs[AFTCOL_CHUNKS].size = query->size - chunks_offset;
1311         if (pb && !hs) { /* update pb's hash */
1312                 char old_asc[2 * HASH_SIZE + 1];
1313                 HASH_TYPE *old_hash;
1314                 ret = get_hash_of_row(pb, &old_hash);
1315                 if (ret < 0)
1316                         return ret;
1317                 hash_to_asc(old_hash, old_asc);
1318                 if (flags & ADD_FLAG_VERBOSE)
1319                         PARA_NOTICE_LOG("file change: %s %s -> %s\n", path,
1320                                 old_asc, asc);
1321                 ret = osl_update_object(audio_file_table, pb, AFTCOL_HASH,
1322                         &objs[AFTCOL_HASH]);
1323                 if (ret < 0)
1324                         return ret;
1325         }
1326         if (hs || pb) { /* (hs != NULL and pb != NULL) implies hs == pb */
1327                 const void *row = pb? pb : hs;
1328                 /* update afhi and chunk_table */
1329                 if (flags & ADD_FLAG_VERBOSE)
1330                         PARA_NOTICE_LOG("updating audio format handler info (%zd bytes)\n",
1331                                 objs[AFTCOL_AFHI].size);
1332                 ret = osl_update_object(audio_file_table, row, AFTCOL_AFHI,
1333                         &objs[AFTCOL_AFHI]);
1334                 if (ret < 0)
1335                         return ret;
1336                 if (flags & ADD_FLAG_VERBOSE)
1337                         PARA_NOTICE_LOG("updating chunk table\n");
1338                 ret = osl_update_object(audio_file_table, row, AFTCOL_CHUNKS,
1339                         &objs[AFTCOL_CHUNKS]);
1340                 if (ret < 0)
1341                         return ret;
1342                 ret = mood_update_audio_file(row, NULL);
1343                 if (ret < 0)
1344                         return ret;
1345         }
1346         /* new entry, use default afsi */
1347         default_afsi.last_played = time(NULL) - 365 * 24 * 60 * 60;
1348         default_afsi.audio_format_id = read_u8(buf + AFTROW_AUDIO_FORMAT_OFFSET);
1349
1350         if (flags & ADD_FLAG_VERBOSE)
1351                 PARA_NOTICE_LOG("adding %s\n", path);
1352         objs[AFTCOL_AFSI].data = &afsi_buf;
1353         objs[AFTCOL_AFSI].size = AFSI_SIZE;
1354         save_afsi(&default_afsi, &objs[AFTCOL_AFSI]);
1355         ret = osl_add_and_get_row(audio_file_table, objs, &aft_row);
1356         if (ret < 0)
1357                 return ret;
1358         return mood_update_audio_file(aft_row, NULL);
1359 }
1360
1361 struct private_add_data {
1362         int fd;
1363         uint32_t flags;
1364 };
1365
1366 static int path_brother_callback(const struct osl_object *query,
1367                 struct osl_object *result)
1368 {
1369         char *path = query->data;
1370         struct osl_row *path_brother;
1371         int ret = aft_get_row_of_path(path, &path_brother);
1372         if (ret < 0)
1373                 return ret;
1374         result->data = para_malloc(sizeof(path_brother));
1375         result->size = sizeof(path_brother);
1376         *(struct osl_row **)(result->data) = path_brother;
1377         return 1;
1378 }
1379
1380 static int hash_sister_callback(const struct osl_object *query,
1381                 struct osl_object *result)
1382 {
1383         HASH_TYPE *hash = query->data;
1384         struct osl_row *hash_sister;
1385
1386         hash_sister = find_hash_sister(hash);
1387         if (!hash_sister)
1388                 return -E_RB_KEY_NOT_FOUND;
1389         result->data = para_malloc(sizeof(hash_sister));
1390         result->size = sizeof(hash_sister);
1391         *(struct osl_row **)(result->data) = hash_sister;
1392         return 1;
1393 }
1394
1395
1396 static int add_one_audio_file(const char *arg, const void *private_data)
1397 {
1398         int ret;
1399         uint8_t format_num = -1;
1400         const struct private_add_data *pad = private_data;
1401         struct audio_format_info afhi, *afhi_ptr = NULL;
1402         struct osl_row *pb = NULL, *hs = NULL; /* path brother/hash sister */
1403         struct osl_object map, obj, query, result;
1404         char *path;
1405         HASH_TYPE hash[HASH_SIZE];
1406
1407         afhi.header_offset = 0;
1408         afhi.header_len = 0;
1409         ret = verify_path(arg, &path);
1410         if (ret < 0)
1411                 return ret;
1412         query.data = path;
1413         query.size = strlen(path) + 1;
1414         ret = send_callback_request(path_brother_callback, &query, &result);
1415         if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1416                 goto out_free;
1417         if (ret >= 0) {
1418                 pb = *(struct osl_row **)result.data;
1419                 free(result.data);
1420         }
1421         ret = 1;
1422         if (pb && (pad->flags & ADD_FLAG_LAZY)) { /* lazy is really cheap */
1423                 if (pad->flags & ADD_FLAG_VERBOSE)
1424                         PARA_NOTICE_LOG("lazy-ignore: %s\n", path);
1425                 goto out_free;
1426         }
1427         /* We still want to add this file. Compute its hash. */
1428         ret = mmap_full_file(path, O_RDONLY, &map);
1429         if (ret < 0)
1430                 goto out_free;
1431         hash_function(map.data, map.size, hash);
1432
1433         /* Check whether database contains file with the same hash. */
1434         query.data = hash;
1435         query.size = HASH_SIZE;
1436         ret = send_callback_request(hash_sister_callback, &query, &result);
1437         if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1438                 goto out_free;
1439         if (ret >= 0) {
1440                 hs = *(struct osl_row **)result.data;
1441                 free(result.data);
1442         }
1443         /* Return success if we already know this file. */
1444         ret = 1;
1445         if (pb && hs && hs == pb && (!(pad->flags & ADD_FLAG_FORCE))) {
1446                 if (pad->flags & ADD_FLAG_VERBOSE)
1447                         PARA_NOTICE_LOG("not forcing update: %s\n", path);
1448                 goto out_unmap;
1449         }
1450         /*
1451          * we won't recalculate the audio format info and the chunk table if
1452          * there is a hash sister unless in FORCE mode.
1453          */
1454         if (!hs || (pad->flags & ADD_FLAG_FORCE)) {
1455                 ret = compute_afhi(path, map.data, map.size, &afhi);
1456                 if (ret < 0) {
1457                         PARA_WARNING_LOG("audio format of %s not recognized, skipping\n", path);
1458                         ret = 1;
1459                         goto out_unmap;
1460                 }
1461                 format_num = ret;
1462                 afhi_ptr = &afhi;
1463         }
1464         munmap(map.data, map.size);
1465         save_audio_file_info(hash, path, afhi_ptr, pad->flags, format_num, &obj);
1466         /* Ask afs to consider this entry for adding. */
1467         ret = send_callback_request(com_add_callback, &obj, NULL);
1468         goto out_free;
1469
1470 out_unmap:
1471         munmap(map.data, map.size);
1472 out_free:
1473         free(obj.data);
1474         free(path);
1475         if (afhi_ptr)
1476                 free(afhi_ptr->chunk_table);
1477         return ret;
1478 }
1479
1480 int com_add(int fd, int argc, char * const * const argv)
1481 {
1482         int i, ret;
1483         struct private_add_data pad = {.fd = fd, .flags = 0};
1484         struct stat statbuf;
1485
1486         PARA_NOTICE_LOG("argv[1]: %s\n", argv[1]);
1487         for (i = 1; i < argc; i++) {
1488                 const char *arg = argv[i];
1489                 if (arg[0] != '-')
1490                         break;
1491                 if (!strcmp(arg, "--")) {
1492                         i++;
1493                         break;
1494                 }
1495                 if (!strcmp(arg, "-l")) {
1496                         pad.flags |= ADD_FLAG_LAZY;
1497                         continue;
1498                 }
1499                 if (!strcmp(arg, "-f")) {
1500                         pad.flags |= ADD_FLAG_FORCE;
1501                         continue;
1502                 }
1503                 if (!strcmp(arg, "-v")) {
1504                         pad.flags |= ADD_FLAG_VERBOSE;
1505                         continue;
1506                 }
1507         }
1508         if (argc <= i)
1509                 return -E_AFT_SYNTAX;
1510         for (; i < argc; i++) {
1511                 ret = stat(argv[i], &statbuf);
1512                 if (ret < 0)
1513                         return -E_AFS_STAT;
1514                 if (S_ISDIR(statbuf.st_mode)) {
1515                         ret = for_each_file_in_dir(argv[i],
1516                                 add_one_audio_file, &pad);
1517                         if (ret < 0)
1518                                 return ret;
1519                         continue;
1520                 }
1521                 ret = add_one_audio_file(argv[i], &pad);
1522                 if (ret < 0)
1523                         goto out;
1524         }
1525         ret = 1;
1526 out:
1527         return ret;
1528
1529 }
1530
1531 struct com_touch_options {
1532         long num_played;
1533         long last_played;
1534         long lyrics_id;
1535         long image_id;
1536 };
1537
1538 static int com_touch_callback(const struct osl_object *query,
1539                 __a_unused struct osl_object *result)
1540 {
1541         struct com_touch_options *cto = query->data;
1542         char *p = (char *)query->data + sizeof(*cto);
1543         size_t len;
1544         int ret, no_options = cto->num_played < 0 && cto->last_played < 0 &&
1545                 cto->lyrics_id < 0 && cto->image_id < 0;
1546
1547         for (;p < (char *)query->data + query->size; p += len + 1) {
1548                 struct afs_info old_afsi, new_afsi;
1549                 struct osl_object obj;
1550                 struct osl_row *row;
1551
1552                 len = strlen(p);
1553                 ret = aft_get_row_of_path(p, &row);
1554                 if (ret < 0)
1555                         return ret;
1556                 ret = get_afsi_object_of_row(row, &obj);
1557                 if (ret < 0)
1558                         return ret;
1559                 ret = load_afsi(&old_afsi, &obj);
1560                 if (ret < 0)
1561                         return ret;
1562                 new_afsi = old_afsi;
1563                 if (no_options) {
1564                         new_afsi.num_played++;
1565                         new_afsi.last_played = time(NULL);
1566                 } else {
1567                         if (cto->lyrics_id >= 0)
1568                                 new_afsi.lyrics_id = cto->lyrics_id;
1569                         if (cto->image_id >= 0)
1570                                 new_afsi.image_id = cto->image_id;
1571                         if (cto->num_played >= 0)
1572                                 new_afsi.num_played = cto->num_played;
1573                         if (cto->last_played >= 0)
1574                                 new_afsi.last_played = cto->last_played;
1575                 }
1576                 save_afsi(&new_afsi, &obj); /* in-place update */
1577                 ret = mood_update_audio_file(row, &old_afsi);
1578                 if (ret < 0)
1579                         return ret;
1580         }
1581         return 1;
1582 }
1583
1584 int com_touch(__a_unused int fd, int argc, char * const * const argv)
1585 {
1586         struct com_touch_options cto = {
1587                 .num_played = -1,
1588                 .last_played = -1,
1589                 .lyrics_id = -1,
1590                 .image_id = -1
1591         };
1592         struct osl_object options = {.data = &cto, .size = sizeof(cto)};
1593         int i, ret;
1594
1595
1596         for (i = 1; i < argc; i++) {
1597                 const char *arg = argv[i];
1598                 if (arg[0] != '-')
1599                         break;
1600                 if (!strcmp(arg, "--")) {
1601                         i++;
1602                         break;
1603                 }
1604                 if (!strncmp(arg, "-n", 2)) {
1605                         ret = para_atol(arg + 2, &cto.num_played);
1606                         if (ret < 0)
1607                                 goto err;
1608                         continue;
1609                 }
1610                 if (!strncmp(arg, "-l", 2)) {
1611                         ret = para_atol(arg + 2, &cto.last_played);
1612                         if (ret < 0)
1613                                 goto err;
1614                         continue;
1615                 }
1616                 if (!strncmp(arg, "-y", 2)) {
1617                         ret = para_atol(arg + 2, &cto.lyrics_id);
1618                         if (ret < 0)
1619                                 goto err;
1620                         continue;
1621                 }
1622                 if (!strncmp(arg, "-i", 2)) {
1623                         ret = para_atol(arg + 2, &cto.image_id);
1624                         if (ret < 0)
1625                                 goto err;
1626                         continue;
1627                 }
1628         }
1629         ret = -E_AFT_SYNTAX;
1630         if (i >= argc)
1631                 goto err;
1632         return send_option_arg_callback_request(&options, argc - i,
1633                 argv + i, com_touch_callback, NULL);
1634 err:
1635         return ret;
1636 }
1637
1638 struct com_rm_options {
1639         uint32_t flags;
1640 };
1641
1642 static int com_rm_callback(const struct osl_object *query,
1643                 __a_unused struct osl_object *result)
1644 {
1645         struct com_rm_options *cro = query->data;
1646         char *p = (char *)query->data + sizeof(*cro);
1647         size_t len;
1648         int ret;
1649
1650         for (;p < (char *)query->data + query->size; p += len + 1) {
1651                 struct osl_row *row;
1652
1653                 len = strlen(p);
1654                 ret = aft_get_row_of_path(p, &row);
1655                 if (ret < 0)
1656                         return ret;
1657                 ret = mood_delete_audio_file(row);
1658                 if (ret < 0)
1659                         return ret;
1660                 ret = osl_del_row(audio_file_table, row);
1661                 if (ret < 0)
1662                         return ret;
1663         }
1664         return 1;
1665 }
1666
1667 /*
1668  * TODO options: -v verbose, -f dont stop if file not found
1669  * -h remove by hash, use fnmatch
1670  *
1671  * */
1672
1673 int com_afs_rm(__a_unused int fd, int argc,  char * const * const argv)
1674 {
1675         struct com_rm_options cro = {.flags = 0};
1676         struct osl_object options = {.data = &cro, .size = sizeof(cro)};
1677         int i, ret;
1678
1679         for (i = 1; i < argc; i++) {
1680                 const char *arg = argv[i];
1681                 if (arg[0] != '-')
1682                         break;
1683                 if (!strcmp(arg, "--")) {
1684                         i++;
1685                         break;
1686                 }
1687         }
1688         ret = -E_AFT_SYNTAX;
1689         if (i >= argc)
1690                 goto err;
1691         return send_option_arg_callback_request(&options, argc - i,
1692                 argv + i, com_rm_callback, NULL);
1693 err:
1694         return ret;
1695 }
1696
1697 /**
1698  * Close the audio file table.
1699  *
1700  * \param flags Ususal flags that are passed to osl_close_table().
1701  *
1702  * \sa osl_close_table().
1703  */
1704 void aft_shutdown(enum osl_close_flags flags)
1705 {
1706         osl_close_table(audio_file_table, flags);
1707 }
1708
1709 /**
1710  * Open the audio file table.
1711  *
1712  * \param ti Gets initialized by this function
1713  *
1714  * \return Positive on success, negative on errors.
1715  *
1716  * \sa osl_open_table().
1717  */
1718 int aft_init(struct table_info *ti)
1719 {
1720         int ret;
1721
1722         ti->desc = &audio_file_table_desc;
1723         ret = osl_open_table(ti->desc, &ti->table);
1724         if (ret >= 0) {
1725                 unsigned num;
1726                 audio_file_table = ti->table;
1727                 osl_get_num_rows(audio_file_table, &num);
1728                 PARA_INFO_LOG("audio file table contains %d files\n", num);
1729                 return ret;
1730         }
1731         PARA_INFO_LOG("failed to open audio file table\n");
1732         audio_file_table = NULL;
1733         return ret == -E_NOENT? 1 : ret;
1734 }