1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
From 2f9af718161c726eedebefb2b721eba26bffcc69 Mon Sep 17 00:00:00 2001
From: Thomas Martitz <[email protected]>
Date: Tue, 16 Aug 2011 19:51:57 +0200
Subject: [PATCH] Current state

---
 apps/buffering.c              |   63 +++++++++++++++++++++++++++++++++++++++--
 apps/playback.c               |   58 +++++++++++++++++++++++--------------
 apps/talk.c                   |    4 +-
 firmware/buflib.c             |   62 ++++++++++++++++++++++++++++++++++++++--
 firmware/include/buflib.h     |    2 +
 firmware/include/core_alloc.h |    5 +++
 6 files changed, 164 insertions(+), 30 deletions(-)

diff --git a/apps/buffering.c b/apps/buffering.c
index c47564b..22631e0 100644
--- a/apps/buffering.c
+++ b/apps/buffering.c
@@ -138,6 +138,8 @@ static int base_handle_id;
 
 /* Main lock for adding / removing handles */
 static struct mutex llist_mutex SHAREDBSS_ATTR;
+/* Lock for reading from the buffer */
+static struct mutex bufrd_mutex SHAREDBSS_ATTR;
 
 /* Handle cache (makes find_handle faster).
    This is global so that move_handle and rm_handle can invalidate it. */
@@ -1356,6 +1358,7 @@ static struct memory_handle *prep_bufdata(int handle_id, size_t *size,
     }
 
     *size = MIN(realsize, avail);
+
     return h;
 }
 
@@ -1377,19 +1380,26 @@ ssize_t bufread(int handle_id, size_t size, void *dest)
     const struct memory_handle *h;
     size_t adjusted_size = size;
 
+    mutex_lock(&bufrd_mutex);
+
     h = prep_bufdata(handle_id, &adjusted_size, false);
-    if (!h)
+    if (!h) {
+        mutex_unlock(&bufrd_mutex);
         return ERR_HANDLE_NOT_FOUND;
+    }
 
     if (h->ridx + adjusted_size > buffer_len) {
         /* the data wraps around the end of the buffer */
         size_t read = buffer_len - h->ridx;
+        printf("%s(): (%p, %p, %zu); (%p, %p, %zu);\n", __func__, dest, &buffer[h->ridx], read, dest+read, buffer, adjusted_size - read);
+        printf("%s(): %zu, %zu\n", __func__, buffer_len, h->ridx);
         memcpy(dest, &buffer[h->ridx], read);
         memcpy(dest+read, buffer, adjusted_size - read);
     } else {
         memcpy(dest, &buffer[h->ridx], adjusted_size);
     }
 
+    mutex_unlock(&bufrd_mutex);
     return adjusted_size;
 }
 
@@ -1407,9 +1417,13 @@ ssize_t bufgetdata(int handle_id, size_t size, void **data)
     const struct memory_handle *h;
     size_t adjusted_size = size;
 
+    mutex_lock(&bufrd_mutex);
+
     h = prep_bufdata(handle_id, &adjusted_size, true);
-    if (!h)
+    if (!h) {
+        mutex_unlock(&bufrd_mutex);
         return ERR_HANDLE_NOT_FOUND;
+    }
 
     if (h->ridx + adjusted_size > buffer_len) {
         /* the data wraps around the end of the buffer :
@@ -1424,6 +1438,7 @@ ssize_t bufgetdata(int handle_id, size_t size, void **data)
     if (data)
         *data = &buffer[h->ridx];
 
+    mutex_unlock(&bufrd_mutex);
     return adjusted_size;
 }
 
@@ -1605,9 +1620,48 @@ static void shrink_buffer_inner(struct memory_handle *h)
     shrink_handle(h);
 }
 
+static void
+move_buffer_front(char* new_buffer, size_t new_size, struct memory_handle *h)
+{
+    mutex_lock(&bufrd_mutex);
+    ptrdiff_t diff = buffer - new_buffer;
+    do {
+        h->data += diff;
+        h->ridx += diff;
+        h->widx += diff;
+    } while ((h = h->next));
+    
+    buffer = new_buffer;
+    buffer_len = new_size;
+    guard_buffer = buffer + buffer_len;
+    high_watermark = 3*buffer_len / 4;
+    printf("%s(): %p, %zu, %d\n", __func__, new_buffer, new_size, diff);
+
+    buf_ridx += diff;
+    buf_widx += diff;
+    mutex_unlock(&bufrd_mutex);
+}
+
+/* cache these until the thread is ready to move the buffer */
+static char* new_buffer;        /* may be NULL */
+static size_t new_buffer_len;
+
+void buf_set_buffer(char *buf, size_t buflen)
+{
+    buflen -= GUARD_BUFSIZE;
+    STORAGE_ALIGN_BUFFER(buf, buflen);
+    new_buffer = buf;
+    new_buffer_len = buflen;
+}
+
 static void shrink_buffer(void)
 {
-    logf("shrink_buffer()");
+    printf("%s()\n", __func__);
+    if (new_buffer)
+    {
+        move_buffer_front(new_buffer, new_buffer_len, first_handle);
+        new_buffer = NULL;
+    }
     shrink_buffer_inner(first_handle);
 }
 
@@ -1723,6 +1777,7 @@ static void NORETURN_ATTR buffering_thread(void)
 void buffering_init(void)
 {
     mutex_init(&llist_mutex);
+    mutex_init(&bufrd_mutex);
 
     /* Thread should absolutely not respond to USB because if it waits first,
        then it cannot properly service the handles and leaks will happen -
@@ -1758,6 +1813,7 @@ bool buffering_reset(char *buf, size_t buflen)
     buffer = buf;
     buffer_len = buflen;
     guard_buffer = buf + buflen;
+    new_buffer = NULL;
 
     buf_widx = 0;
     buf_ridx = 0;
@@ -1765,6 +1821,7 @@ bool buffering_reset(char *buf, size_t buflen)
     first_handle = NULL;
     cur_handle = NULL;
     cached_handle = NULL;
+
     num_handles = 0;
     base_handle_id = -1;
 
diff --git a/apps/playback.c b/apps/playback.c
index bc56d72..3d8bed6 100644
--- a/apps/playback.c
+++ b/apps/playback.c
@@ -716,9 +716,10 @@ static size_t scratch_mem_size(void)
 
 /* Initialize the memory area where data is stored that is only used when
    playing audio and anything depending upon it */
-static void scratch_mem_init(void *mem)
+static size_t scratch_mem_init(void *mem)
 {
-    audio_scratch_memory = (struct audio_scratch_memory *)mem;
+    size_t alloc_size = scratch_mem_size();
+    audio_scratch_memory = (struct audio_scratch_memory *)(mem - alloc_size);
     id3_write_locked(UNBUFFERED_ID3, NULL);
     id3_write(CODEC_ID3, NULL);
     ci.id3 = id3_get(CODEC_ID3);
@@ -730,10 +731,11 @@ static void scratch_mem_init(void *mem)
             SKIPBYTES((struct cuesheet *)audio_scratch_memory,
                       sizeof (struct audio_scratch_memory));
     }
+    return alloc_size;
 }
 
 static int audiobuf_handle;
-static size_t filebuflen;
+static size_t filebuflen, alloclen;
 
 size_t audio_buffer_available(void)
 {
@@ -748,7 +750,7 @@ static void audio_reset_buffer_noalloc(void)
 {
     /*
      * Layout audio buffer as follows:
-     * [[|TALK]|SCRATCH|BUFFERING|PCM|[VOICE|]]
+     * [BUFFERING[|TALK]|SCRATCH|PCM|[VOICE|]]
      */
 
     /* see audio_get_recording_buffer if this is modified */
@@ -760,16 +762,7 @@ static void audio_reset_buffer_noalloc(void)
 
     /* Initially set up file buffer as all space available */
     size_t allocsize;
-
     void* filebuf = core_get_data(audiobuf_handle);
-    /* Subtract whatever voice needs */
-    allocsize = talkbuf_init(filebuf);
-    allocsize = ALIGN_UP(allocsize, sizeof (intptr_t));
-    if (allocsize > filebuflen)
-        goto bufpanic;
-
-    filebuf += allocsize;
-    filebuflen -= allocsize;
 
     if (talk_voice_required())
     {
@@ -794,12 +787,18 @@ static void audio_reset_buffer_noalloc(void)
     filebuflen -= allocsize;
 
     /* Scratch memory */
-    allocsize = scratch_mem_size();
+    allocsize = scratch_mem_init(filebuf + filebuflen);
+    if (allocsize > filebuflen)
+        goto bufpanic;
+
+    filebuflen -= allocsize;
+
+    /* Subtract whatever voice needs */
+    allocsize = talkbuf_init(filebuf + filebuflen);
+    allocsize = ALIGN_UP(allocsize, sizeof (intptr_t));
     if (allocsize > filebuflen)
         goto bufpanic;
 
-    scratch_mem_init(filebuf);
-    filebuf += allocsize;
     filebuflen -= allocsize;
 
     buffering_reset(filebuf, filebuflen);
@@ -843,7 +842,7 @@ static int shrink_callback(int handle, unsigned hints, void* start, size_t old_s
     }
     /* set final buffer size before calling audio_start_playback()
      * (which calls audio_reset_buffer_noalloc() which needs the new size) */
-    filebuflen = size;
+    alloclen = filebuflen = size;
     /* TODO: Do it without stopping playback, if possible */
     /* don't call audio_hard_stop() as it frees this handle */
     if (thread_self() == audio_thread_id)
@@ -869,7 +868,8 @@ static void audio_reset_buffer(void)
         core_free(audiobuf_handle);
         audiobuf_handle = 0;
     }
-    audiobuf_handle = core_alloc_maximum("audiobuf", &filebuflen, &ops);
+    audiobuf_handle = core_alloc_maximum("audiobuf", &alloclen, &ops);
+    filebuflen = alloclen;
 
     audio_reset_buffer_noalloc();
 }
@@ -3035,6 +3035,20 @@ static void audio_thread(void)
         case Q_AUDIO_BUFFERING:
             /* some buffering event */
             LOGFQUEUE("audio < Q_AUDIO_BUFFERING: %d", (int)ev.data);
+            if (ev.data == BUFFER_EVENT_BUFFER_LOW)
+            {
+                void* oldstart = core_get_data(audiobuf_handle);
+                /* remember what buffer sizes we gave to other buffers
+                 * (voice, pcm, scratchmem) */
+                size_t diff = alloclen - filebuflen;
+                void* newstart = core_merge(audiobuf_handle, &alloclen);
+                printf("%p\n%p\n", oldstart, newstart);
+                if (newstart < oldstart)
+                {
+                    filebuflen = alloclen - diff;
+                    buf_set_buffer(newstart, filebuflen);
+                }
+            }
             audio_on_buffering(ev.data);
             break;
 
@@ -3510,7 +3524,8 @@ unsigned char * audio_get_buffer(bool talk_buf, size_t *buffer_size)
     if (audiobuf_handle > 0)
         audiobuf_handle = core_free(audiobuf_handle);
 
-    audiobuf_handle = core_alloc_maximum("audiobuf", &filebuflen, &ops);
+    audiobuf_handle = core_alloc_maximum("audiobuf", &alloclen, &ops);
+    filebuflen = alloclen;
     buf = core_get_data(audiobuf_handle);
 
     if (talk_buf || buffer_state == AUDIOBUF_STATE_TRASHED
@@ -3539,9 +3554,8 @@ unsigned char * audio_get_buffer(bool talk_buf, size_t *buffer_size)
         /* Skip talk buffer and move pcm buffer to end to maximize available
            contiguous memory - no audio running means voice will not need the
            swap space */
-        size_t talkbuf_size;
-        buf += talkbuf_size = talkbuf_init(buf);
-        filebuflen -= talkbuf_size;
+        size_t talkbuf_size = talkbuf_init(buf + filebuflen);
+        filebuflen -= ALIGN_UP(talkbuf_size, sizeof(void*));
         filebuflen -= voicebuf_init(buf + filebuflen);
 
         buffer_state = AUDIOBUF_STATE_VOICED_ONLY;
diff --git a/apps/talk.c b/apps/talk.c
index 2965738..93d6082 100644
--- a/apps/talk.c
+++ b/apps/talk.c
@@ -747,12 +747,12 @@ int talk_get_buffer(void)
  * buffer we will use for the voicefile */
 size_t talkbuf_init(char *bufstart)
 {
-    bool changed = voicebuf != bufstart;
+    bool changed = voicebuf != (bufstart - voicefile_size);
 
     if (changed) /* must reload voice file */
         reset_state();
     if (bufstart)
-        voicebuf = bufstart;
+        voicebuf = bufstart - voicefile_size;
 
     return talk_get_buffer();
 }
diff --git a/firmware/buflib.c b/firmware/buflib.c
index 3b4f522..bc330c1 100644
--- a/firmware/buflib.c
+++ b/firmware/buflib.c
@@ -228,9 +228,10 @@ buflib_compact(struct buflib_context *ctx)
     BDEBUGF("%s(): Compacting!\n", __func__);
     union buflib_data *block,
                       *first_free = find_first_free(ctx);
-    int shift = 0, len;
+    int shift = 0, moved = 0, len;
     /* Store the results of attempting to shrink the handle table */
     bool ret = handle_table_shrink(ctx);
+    bool compact = true; /* assume we sucessfully compact */
     for(block = first_free; block < ctx->alloc_end; block += len)
     {
         len = block->val;
@@ -258,6 +259,7 @@ buflib_compact(struct buflib_context *ctx)
                     first_free += block->val;
                     first_free->val = block->val - size; /* negative */
                 }
+                moved++;
                 continue;
             }
         }
@@ -270,6 +272,7 @@ buflib_compact(struct buflib_context *ctx)
             if (!move_block(ctx, block, shift))
             {
                 target_block->val = shift; /* this is a hole */
+                compact = false;
                 shift = 0;
             }
             else
@@ -277,6 +280,7 @@ buflib_compact(struct buflib_context *ctx)
                  * handling might make shift 0 before alloc_end is reached */
                 union buflib_data* new_free = target_block + target_block->val;
                 new_free->val = shift;
+                moved++;
             }
         }
     }
@@ -284,8 +288,8 @@ buflib_compact(struct buflib_context *ctx)
      * been freed.
      */
     ctx->alloc_end += shift;
-    ctx->compact = true;
-    return ret || shift;
+    ctx->compact = compact; /* it's compact if no move occured */
+    return ret || moved; /* true if moved succeeded at least once */
 }
 
 /* Compact the buffer by trying both shrinking and moving.
@@ -546,6 +550,48 @@ find_block_before(struct buflib_context *ctx, union buflib_data* block,
     return NULL;
 }
 
+void*
+buflib_merge(struct buflib_context* ctx, int handle_num, size_t *new_size)
+{
+    union buflib_data *block_start = handle_to_block(ctx, handle_num),
+                      *alloc_start = buflib_get_data(ctx, handle_num),
+                      *prev, *next;
+    size_t metadata_size = (alloc_start - block_start);
+    size_t size = block_start->val - metadata_size;
+    size *= sizeof(union buflib_data); /* make it bytes */
+    if (!ctx->compact)
+        buflib_compact(ctx);
+
+    /* no point in trying if the buf is compact */
+    if (ctx->compact)
+    {
+        *new_size = size;
+        return alloc_start;
+    }
+    /* first merge with the end */
+    next = block_start + block_start->val;
+    /* consecutive free blocks don't exist, they're merged in buflib_free() */
+    if (next->val < 0 && next != ctx->alloc_end)
+        block_start->val += -next->val;
+
+    /* merge with the front */
+    prev = find_block_before(ctx, block_start, true);
+    printf("found prev: %p, %ld\n", prev, prev ? prev->val : 0);
+    if (prev)
+    {
+        intptr_t shift = -prev->val; /* merge */
+        memmove(prev, block_start, metadata_size*sizeof(union buflib_data));
+        block_start -= shift;
+        block_start->val += shift;
+        shift *= sizeof(union buflib_data);
+        /* update handle table */
+        block_start[1].handle->alloc -= shift;
+        
+    }
+    *new_size = (block_start->val - metadata_size)*sizeof(union buflib_data);
+    return buflib_get_data(ctx, handle_num);
+}
+
 /* Free the buffer associated with handle_num. */
 int
 buflib_free(struct buflib_context *ctx, int handle_num)
@@ -779,4 +825,14 @@ void buflib_print_block_at(struct buflib_context *ctx, int block_num,
                             this->val > 0? this[3].name:"<unallocated>");
 }
 
+void buflib_print_blocks_all(struct buflib_context *ctx)
+{
+    int max = buflib_get_num_blocks(ctx);
+    char buf[128];
+    for (int i = 0; i < max; i++)
+    {
+        buflib_print_block_at(ctx, i, buf, sizeof(buf));
+        printf("%s\n", buf);
+    }
+}
 #endif
diff --git a/firmware/include/buflib.h b/firmware/include/buflib.h
index 9cd7c0b..4c42253 100644
--- a/firmware/include/buflib.h
+++ b/firmware/include/buflib.h
@@ -267,6 +267,8 @@ void* buflib_buffer_out(struct buflib_context *ctx, size_t *size);
  */
 void buflib_buffer_in(struct buflib_context *ctx, int size);
 
+void* buflib_merge(struct buflib_context *ctx, int handle_num, size_t* size);
+
 /* debugging */
 
 /**
diff --git a/firmware/include/core_alloc.h b/firmware/include/core_alloc.h
index f5206c9..97da38e 100644
--- a/firmware/include/core_alloc.h
+++ b/firmware/include/core_alloc.h
@@ -28,6 +28,11 @@ int  core_get_num_blocks(void);
 void core_print_block_at(int block_num, char* buf, size_t bufsize);
 #endif
 
+static inline void* core_merge(int handle, size_t *newsize)
+{
+    extern struct buflib_context core_ctx;
+    return buflib_merge(&core_ctx, handle, newsize);
+}
 static inline void* core_get_data(int handle)
 {
     extern struct buflib_context core_ctx;
-- 
1.7.5.4