Merge branch 'maint'
[paraslash.git] / fecdec_filter.c
1 /*
2  * Copyright (C) 2009 Andre Noll <maan@systemlinux.org>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file fecdec_filter.c A filter that fec-decodes an audio stream. */
8
9 #include <regex.h>
10
11 #include <dirent.h>
12 #include "para.h"
13 #include "error.h"
14 #include "list.h"
15 #include "sched.h"
16 #include "ggo.h"
17 #include "filter.h"
18 #include "string.h"
19 #include "portable_io.h"
20 #include "fec.h"
21 #include "fd.h"
22
23 /**
24  * How many FEC groups to store in memory.
25  *
26  * Packet reordering requires to keep more than one FEC group in memory because
27  * slices belonging to the next FEC group may arrive before the current FEC group
28  * is complete.
29  */
30 #define NUM_FEC_GROUPS 3
31
32 /** Default size of the output buffer of the fecdec filter. */
33 #define FECDEC_DEFAULT_OUTBUF_SIZE (3 * 1024)
34 /** Maximal size of the output buffer of the fecdec filter. */
35 #define FECDEC_MAX_OUTBUF_SIZE (1024 * 1024)
36
37 /** Data read from the header of a slice. */
38 struct fec_header {
39         /** Total number of slices in this group. */
40         uint8_t slices_per_group;
41         /** Number of slices needed to start decoding. */
42         uint8_t data_slices_per_group;
43         /** Size of the ogg vorbis header (zero for mp3, aac). */
44         uint32_t audio_header_size;
45         /** Number of the FEC group this slice belongs to. */
46         uint32_t group_num;
47         /** Size of the data in this FEC group. */
48         uint32_t group_bytes;
49         /** Number of this slice in the group. */
50         uint8_t slice_num;
51         /** Used data bytes of this slice. */
52         uint16_t slice_bytes;
53         /** Non-zero if this group is the beginning of the stream. */
54         uint8_t bos;
55         /** Non-zero if this stream embedds audio headers into fec groups. */
56         uint8_t header_stream;
57 };
58
59 /**
60  * The status of one partially received FEC group.
61  */
62 struct fecdec_group {
63         /** The header read from the last slice. */
64         struct fec_header h;
65         /** How many slices received so far. */
66         int num_received_slices;
67         /** The size of the \a idx and the \a data arrays below. */
68         int num_slices;
69         /** Array of indices of the received slices. */
70         int *idx;
71         /** Content of the received slices. */
72         unsigned char **data;
73 };
74
75 /**
76  * Data private to the fecdec filter.
77  */
78 struct private_fecdec_data {
79         /** Used by the fec core code. */
80         struct fec_parms *fec;
81         /** Keeps track of what was received so far. */
82         struct fecdec_group groups[NUM_FEC_GROUPS];
83         /** Whether an audio file header was already received. */
84         int have_header;
85         /** Points to the first received group. */
86         struct fecdec_group *first_complete_group;
87 };
88
89 /** Iterate over all fecdec groups. */
90 #define FOR_EACH_FECDEC_GROUP(g, d) for (g = (d)->groups; \
91         (g) < (d)->groups + NUM_FEC_GROUPS; (g)++)
92
93 static int group_complete(struct fecdec_group *fg)
94 {
95         return fg->num_received_slices >= fg->h.data_slices_per_group;
96 }
97
98 static int group_empty(struct fecdec_group *fg)
99 {
100         return fg->num_received_slices == 0;
101 }
102
103 static void clear_group(struct fecdec_group *fg)
104 {
105         int i;
106
107         for (i = 0; i < fg->num_slices; i++) {
108                 free(fg->data[i]);
109                 fg->data[i] = NULL;
110                 fg->idx[i] = -1;
111         }
112         free(fg->data);
113         fg->data = NULL;
114         free(fg->idx);
115         fg->idx = NULL;
116         fg->num_slices = 0;
117         memset(&fg->h, 0, sizeof(struct fec_header));
118         fg->num_received_slices = 0;
119 }
120
121 static int find_group(struct fec_header *h,
122                 struct private_fecdec_data *pfd, struct fecdec_group **result)
123 {
124         struct fecdec_group *fg;
125
126         FOR_EACH_FECDEC_GROUP(fg, pfd) {
127                 if (fg->h.group_num != h->group_num)
128                         continue;
129                 if (fg->num_received_slices == 0)
130                         goto success;
131                 if (fg->h.slices_per_group != h->slices_per_group)
132                         return -E_BAD_FEC_HEADER;
133                 if (fg->h.data_slices_per_group != h->data_slices_per_group)
134                         return -E_BAD_FEC_HEADER;
135                 if (fg->h.group_bytes != h->group_bytes)
136                         return -E_BAD_FEC_HEADER;
137 success:
138                 *result = fg;
139                 return 1;
140         }
141         return 0;
142 }
143
144 static struct fecdec_group *find_unused_group(struct private_fecdec_data *pfd)
145 {
146         struct fecdec_group *fg;
147
148         FOR_EACH_FECDEC_GROUP(fg, pfd) {
149                 if (fg->num_received_slices == 0)
150                         return fg;
151         }
152         return NULL;
153 }
154
155 static struct fecdec_group *try_to_free_group(struct private_fecdec_data *pfd)
156 {
157         struct fecdec_group *fg;
158
159         FOR_EACH_FECDEC_GROUP(fg, pfd) {
160                 if (!group_complete(fg))
161                         continue;
162                 /*
163                  * Don't clear the first complete group if it has not yet been
164                  * decoded.
165                  */
166                 if (fg == pfd->first_complete_group)
167                         continue;
168                 clear_group(fg);
169                 return fg;
170         }
171         return NULL;
172 }
173
174 static struct fecdec_group *free_oldest_group(struct private_fecdec_data *pfd)
175 {
176         struct fecdec_group *fg, *oldest = NULL;
177
178         FOR_EACH_FECDEC_GROUP(fg, pfd) {
179                 if (!oldest || oldest->h.group_num > fg->h.group_num)
180                         oldest = fg;
181         }
182         if (!group_complete(oldest) && !group_empty(oldest))
183                 PARA_WARNING_LOG("Clearing incomplete group %d "
184                         "(contains %d slices)\n", oldest->h.group_num,
185                         oldest->num_received_slices);
186         if (oldest == pfd->first_complete_group)
187                 pfd->first_complete_group = NULL;
188         clear_group(oldest);
189         return oldest;
190 }
191
192 /* returns 1 if the group was found, 0 if not, negative on errors */
193 static int get_group(struct fec_header *h, struct private_fecdec_data *pfd,
194                 struct fecdec_group **result)
195 {
196         struct fecdec_group *fg;
197         int ret = find_group(h, pfd, &fg);
198
199         if (ret < 0)
200                 return ret;
201         if (ret > 0) /* found group */
202                 goto success;
203         /* group not found */
204         fg = find_unused_group(pfd);
205         if (fg)
206                 goto success;
207         fg = try_to_free_group(pfd);
208         if (fg)
209                 goto success;
210         fg = free_oldest_group(pfd);
211         ret = 0;
212 success:
213         fg->h = *h;
214         *result = fg;
215         return ret;
216 }
217
218 /*
219  * returns 1 if slice was added, zero otherwise (because the group was already
220  * complete). In any case the number of received slices is being increased by
221  * one.
222  */
223 static int add_slice(char *buf, struct fecdec_group *fg)
224 {
225         int r, slice_num;
226
227         if (group_complete(fg)) {
228                 PARA_DEBUG_LOG("group %d complete, ignoring slice %d\n",
229                         fg->h.group_num, fg->h.slice_num);
230                 fg->num_received_slices++;
231                 return 0;
232         }
233         slice_num = fg->h.slice_num;
234         if (fg->num_slices == 0) {
235                 fg->num_slices = fg->h.slices_per_group;
236                 fg->idx = para_malloc(fg->num_slices * sizeof(int));
237                 fg->data = para_malloc(fg->num_slices * sizeof(unsigned char *));
238                 memset(fg->data, 0, fg->num_slices * sizeof(unsigned char *));
239         }
240         r = fg->num_received_slices;
241         fg->idx[r] = slice_num;
242         fg->data[r] = para_malloc(fg->h.slice_bytes);
243         memcpy(fg->data[r], buf, fg->h.slice_bytes);
244         fg->num_received_slices++;
245         return 1;
246 }
247
248 enum fec_group_usability {
249         FEC_GROUP_UNUSABLE,
250         FEC_GROUP_USABLE,
251         FEC_GROUP_USABLE_SKIP_HEADER,
252         FEC_GROUP_USABLE_WITH_HEADER
253 };
254
255 static enum fec_group_usability group_is_usable(struct fecdec_group *fg,
256                 struct private_fecdec_data *pfd)
257 {
258         struct fec_header *h = &fg->h;
259
260         if (!h->header_stream)
261                 return FEC_GROUP_USABLE;
262         if (pfd->have_header) {
263                 if (h->audio_header_size)
264                         return FEC_GROUP_USABLE_SKIP_HEADER;
265                 return FEC_GROUP_USABLE;
266         }
267         if (fg->h.bos)
268                 return FEC_GROUP_USABLE;
269         if (fg->h.audio_header_size)
270                 return FEC_GROUP_USABLE_WITH_HEADER;
271         return FEC_GROUP_UNUSABLE;
272 }
273
274 static int decode_group(struct fecdec_group *fg, struct filter_node *fn)
275 {
276         int i, ret, sb = fg->h.slice_bytes;
277         size_t written, need;
278         struct private_fecdec_data *pfd = fn->private_data;
279         enum fec_group_usability u = group_is_usable(fg, pfd);
280
281         if (u == FEC_GROUP_UNUSABLE) {
282                 PARA_INFO_LOG("dropping unusable group %d\n", fg->h.group_num);
283                 return 0;
284         }
285         PARA_DEBUG_LOG("decoding group %d (%d slices)\n", fg->h.group_num,
286                 fg->h.data_slices_per_group);
287         ret = fec_decode(pfd->fec, fg->data, fg->idx, sb);
288         if (ret < 0)
289                 return ret;
290         pfd->have_header = 1;
291         i = 0;
292         if (u == FEC_GROUP_USABLE_SKIP_HEADER) {
293                 i = ROUND_UP(fg->h.audio_header_size, fg->h.slice_bytes)
294                         / fg->h.slice_bytes;
295                 PARA_DEBUG_LOG("skipping %d header slices\n", i);
296         }
297         PARA_DEBUG_LOG("writing group %d (%d/%d decoded data bytes)\n",
298                 fg->h.group_num, fg->h.group_bytes,
299                 fg->h.data_slices_per_group * sb);
300         need = fn->loaded + (fg->h.data_slices_per_group - i)* sb;
301         if (need > fn->bufsize) {
302                 fn->bufsize = PARA_MAX(fn->bufsize * 2, need);
303                 if (fn->bufsize > FECDEC_MAX_OUTBUF_SIZE)
304                         return -E_FECDEC_OVERRUN;
305                 PARA_INFO_LOG("increasing fec buf to %zu\n", fn->bufsize);
306                 fn->buf = para_realloc(fn->buf, fn->bufsize);
307         }
308         if (u == FEC_GROUP_USABLE_WITH_HEADER) {
309                 PARA_INFO_LOG("writing audio file header\n");
310                 written = 0;
311                 for (i = 0; i < fg->h.data_slices_per_group; i++) {
312                         size_t n = sb;
313                         if (written >= fg->h.audio_header_size)
314                                 break;
315                         if (sb + written > fg->h.audio_header_size)
316                                 n = fg->h.audio_header_size - written;
317                         memcpy(fn->buf + fn->loaded, fg->data[i], n);
318                         fn->loaded += n;
319                         written += n;
320                 }
321         }
322         written = 0;
323         for (; i < fg->h.data_slices_per_group; i++) {
324                 size_t n = sb;
325                 if (n + written > fg->h.group_bytes)
326                         n = fg->h.group_bytes - written;
327                 memcpy(fn->buf + fn->loaded, fg->data[i], n);
328                 fn->loaded += n;
329                 written += n;
330         }
331         return 0;
332 }
333
334 /**
335  * Read a fec header from a buffer.
336  *
337  * \param buf The buffer to write to.
338  * \param h The fec header to write.
339  */
340 static int read_fec_header(char *buf, size_t len, struct fec_header *h)
341 {
342         uint32_t magic;
343
344         if (len < FEC_HEADER_SIZE)
345                 return 0;
346         magic = read_u32(buf);
347         if (magic != FEC_MAGIC)
348                 return -E_BAD_FEC_HEADER;
349         h->slices_per_group = read_u8(buf + 4);
350         h->data_slices_per_group = read_u8(buf + 5);
351         h->audio_header_size = read_u32(buf + 6);
352
353         h->group_num = read_u32(buf + 10);
354         h->group_bytes = read_u32(buf + 14);
355
356         h->slice_num = read_u8(buf + 18);
357         h->slice_bytes = read_u16(buf + 20);
358         h->bos = read_u8(buf + 22);
359         h->header_stream = read_u8(buf + 23);
360         if (!memcmp(buf, FEC_EOF_PACKET, FEC_EOF_PACKET_LEN))
361                 return -E_FECDEC_EOF;
362 //      PARA_DEBUG_LOG("group %u, slize %u, slices per group: %u\n",
363 //              h->group_num, h->slice_num, h->slices_per_group);
364         return 1;
365 }
366
367 /* returns 1 if we used the buffer, 0 if we didn't, negative on errors */
368 static int dispatch_slice(char *buf, size_t len, struct fec_header *h,
369                 struct filter_node *fn)
370 {
371         struct fecdec_group *fg;
372         int ret, k, n;
373         struct private_fecdec_data *pfd = fn->private_data;
374
375         if (h->slice_bytes > len) /* can not use the thing, try to read more */
376                 return 0;
377         ret = get_group(h, pfd, &fg);
378         if (ret < 0)
379                 return ret;
380         if (!add_slice(buf, fg)) /* group already complete */
381                 return 1;
382         if (!group_complete(fg))
383                 return 1;
384         /* this slice completed the group */
385         if (pfd->fec)
386                 goto decode;
387         /* it's either the first or the second complete group */
388         if (!pfd->first_complete_group) { /* it's the first group */
389                 enum fec_group_usability u = group_is_usable(fg, pfd);
390                 assert(u != FEC_GROUP_USABLE_SKIP_HEADER);
391                 if (u == FEC_GROUP_UNUSABLE) /* forget it */
392                         return 1;
393                 pfd->first_complete_group = fg; /* remember it */
394                 return 1;
395         }
396         /* we have two complete groups, let's go */
397         k = h->data_slices_per_group;
398         n = h->slices_per_group;
399         PARA_NOTICE_LOG("init fec (%d, %d)\n", k, n);
400         ret = fec_new(k, n, &pfd->fec);
401         if (ret < 0)
402                 return ret;
403         /* decode and clear the first group */
404         ret = decode_group(pfd->first_complete_group, fn);
405         if (ret < 0)
406                 return ret;
407         clear_group(pfd->first_complete_group);
408         pfd->first_complete_group = NULL;
409 decode:
410         ret = decode_group(fg, fn);
411         if (ret < 0)
412                 return ret;
413         return 1;
414 }
415
416 static ssize_t fecdec(char *buf, size_t len, struct filter_node *fn)
417 {
418         int ret;
419         struct fec_header h;
420
421         ret = read_fec_header(buf, len, &h);
422         if (ret <= 0)
423                 return ret;
424         if (!h.slice_bytes)
425                 return -E_BAD_SLICE_SIZE;
426         if (h.slice_num > h.slices_per_group)
427                 return -E_BAD_SLICE_NUM;
428         ret = dispatch_slice(buf + FEC_HEADER_SIZE, len - FEC_HEADER_SIZE,
429                 &h, fn);
430         //PARA_INFO_LOG("ret: %d, len: %d, slice_bytes: %d\n", ret, len, h.slice_bytes);
431         if (ret <= 0)
432                 return ret;
433         return FEC_HEADER_SIZE + h.slice_bytes;
434 }
435
436 static void fecdec_close(struct filter_node *fn)
437 {
438         struct private_fecdec_data *pfd = fn->private_data;
439         struct fecdec_group *fg;
440
441         FOR_EACH_FECDEC_GROUP(fg, pfd)
442                 clear_group(fg);
443         free(fn->buf);
444         fn->buf = NULL;
445         fec_free(pfd->fec);
446         free(fn->private_data);
447         fn->private_data = NULL;
448 }
449
450 static void fecdec_open(struct filter_node *fn)
451 {
452         struct private_fecdec_data *pfd;
453         fn->bufsize = FECDEC_DEFAULT_OUTBUF_SIZE;
454         fn->buf = para_malloc(fn->bufsize);
455         pfd = para_calloc(sizeof(*pfd));
456         fn->private_data = pfd;
457         fn->loaded = 0;
458 }
459
460 /**
461  * The init function of the fecdec filter.
462  *
463  * \param f struct to initialize.
464  */
465 void fecdec_filter_init(struct filter *f)
466 {
467         f->convert = fecdec;
468         f->close = fecdec_close;
469         f->open = fecdec_open;
470 }