Fix errors and warnings.
[kugel-rb.git] / apps / recorder / pcm_record.c
blob3b069b6dc87a20e1275cdd989f116778d3c6c2f8
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2005 by Linus Nielsen Feltzing
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
20 ****************************************************************************/
22 #include "config.h"
23 #include "gcc_extensions.h"
24 #include "pcm_record.h"
25 #include "system.h"
26 #include "kernel.h"
27 #include "logf.h"
28 #include "thread.h"
29 #include "string-extra.h"
30 #include "storage.h"
31 #include "usb.h"
32 #include "buffer.h"
33 #include "general.h"
34 #include "codec_thread.h"
35 #include "audio.h"
36 #include "sound.h"
37 #include "metadata.h"
38 #include "appevents.h"
39 #ifdef HAVE_SPDIF_IN
40 #include "spdif.h"
41 #endif
43 /***************************************************************************/
45 /** General recording state **/
46 static bool is_recording; /* We are recording */
47 static bool is_paused; /* We have paused */
48 static unsigned long errors; /* An error has occured */
49 static unsigned long warnings; /* Warning */
50 static int flush_interrupts = 0; /* Number of messages queued that
51 should interrupt a flush in
52 progress -
53 for a safety net and a prompt
54 response to stop, split and pause
55 requests -
56 only interrupts a flush initiated
57 by pcmrec_flush(0) */
59 /* Utility functions for setting/clearing flushing interrupt flag */
60 static inline void flush_interrupt(void)
62 flush_interrupts++;
63 logf("flush int: %d", flush_interrupts);
66 static inline void clear_flush_interrupt(void)
68 if (--flush_interrupts < 0)
69 flush_interrupts = 0;
72 /** Stats on encoded data for current file **/
73 static size_t num_rec_bytes; /* Num bytes recorded */
74 static unsigned long num_rec_samples; /* Number of PCM samples recorded */
76 /** Stats on encoded data for all files from start to stop **/
77 #if 0
78 static unsigned long long accum_rec_bytes; /* total size written to chunks */
79 static unsigned long long accum_pcm_samples; /* total pcm count processed */
80 #endif
82 /* Keeps data about current file and is sent as event data for codec */
83 static struct enc_file_event_data rec_fdata IDATA_ATTR =
85 .chunk = NULL,
86 .new_enc_size = 0,
87 .new_num_pcm = 0,
88 .rec_file = -1,
89 .num_pcm_samples = 0
92 /** These apply to current settings **/
93 static int rec_source; /* current rec_source setting */
94 static int rec_frequency; /* current frequency setting */
95 static unsigned long sample_rate; /* Sample rate in HZ */
96 static int num_channels; /* Current number of channels */
97 static int rec_mono_mode; /* how mono is created */
98 static struct encoder_config enc_config; /* Current encoder configuration */
99 static unsigned long pre_record_ticks; /* pre-record time in ticks */
101 /****************************************************************************
102 use 2 circular buffers:
103 pcm_buffer=DMA output buffer: chunks (8192 Bytes) of raw pcm audio data
104 enc_buffer=encoded audio buffer: storage for encoder output data
106 Flow:
107 1. when entering recording_screen DMA feeds the ringbuffer pcm_buffer
108 2. if enough pcm data are available the encoder codec does encoding of pcm
109 chunks (4-8192 Bytes) into ringbuffer enc_buffer in codec_thread
110 3. pcmrec_callback detects enc_buffer 'near full' and writes data to disk
112 Functions calls (basic encoder steps):
113 1.main: audio_load_encoder(); start the encoder
114 2.encoder: enc_get_inputs(); get encoder recording settings
115 3.encoder: enc_set_parameters(); set the encoder parameters
116 4.encoder: enc_get_pcm_data(); get n bytes of unprocessed pcm data
117 5.encoder: enc_unget_pcm_data(); put n bytes of data back (optional)
118 6.encoder: enc_get_chunk(); get a ptr to next enc chunk
119 7.encoder: <process enc chunk> compress and store data to enc chunk
120 8.encoder: enc_finish_chunk(); inform main about chunk processed and
121 is available to be written to a file.
122 Encoder can place any number of chunks
123 of PCM data in a single output chunk
124 but must stay within its output chunk
125 size
126 9.encoder: repeat 4. to 8.
127 A.pcmrec: enc_events_callback(); called for certain events
129 (*) Optional step
130 ****************************************************************************/
132 /** buffer parameters where incoming PCM data is placed **/
133 #if MEMORYSIZE <= 2
134 #define PCM_NUM_CHUNKS 16 /* Power of 2 */
135 #else
136 #define PCM_NUM_CHUNKS 256 /* Power of 2 */
137 #endif
138 #define PCM_CHUNK_SIZE 8192 /* Power of 2 */
139 #define PCM_CHUNK_MASK (PCM_NUM_CHUNKS*PCM_CHUNK_SIZE - 1)
141 #define GET_PCM_CHUNK(offset) ((long *)(pcm_buffer + (offset)))
142 #define GET_ENC_CHUNK(index) ENC_CHUNK_HDR(enc_buffer + enc_chunk_size*(index))
143 #define INC_ENC_INDEX(index) \
144 { if (++index >= enc_num_chunks) index = 0; }
145 #define DEC_ENC_INDEX(index) \
146 { if (--index < 0) index = enc_num_chunks - 1; }
148 static size_t rec_buffer_size; /* size of available buffer */
149 static unsigned char *pcm_buffer; /* circular recording buffer */
150 static unsigned char *enc_buffer; /* circular encoding buffer */
151 #ifdef DEBUG
152 static unsigned long *wrap_id_p; /* magic at wrap position - a debugging
153 aid to check if the encoder data
154 spilled out of its chunk */
155 #endif /* DEBUG */
156 static volatile int dma_wr_pos; /* current DMA write pos */
157 static int pcm_rd_pos; /* current PCM read pos */
158 static int pcm_enc_pos; /* position encoder is processing */
159 static volatile bool dma_lock; /* lock DMA write position */
160 static int enc_wr_index; /* encoder chunk write index */
161 static int enc_rd_index; /* encoder chunk read index */
162 static int enc_num_chunks; /* number of chunks in ringbuffer */
163 static size_t enc_chunk_size; /* maximum encoder chunk size */
164 static unsigned long enc_sample_rate; /* sample rate used by encoder */
165 static bool pcmrec_context = false; /* called by pcmrec thread? */
166 static bool pcm_buffer_empty; /* all pcm chunks processed? */
168 /** file flushing **/
169 static int low_watermark; /* Low watermark to stop flush */
170 static int high_watermark; /* max chunk limit for data flush */
171 static unsigned long spinup_time = 35*HZ/10; /* Fudged spinup time */
172 static int last_storage_spinup_time = -1;/* previous spin time used */
173 #ifdef HAVE_PRIORITY_SCHEDULING
174 static int flood_watermark; /* boost thread priority when here */
175 #endif
177 /* Constants that control watermarks */
178 #define MINI_CHUNKS 10 /* chunk count for mini flush */
179 #ifdef HAVE_PRIORITY_SCHEDULING
180 #define PRIO_SECONDS 10 /* max flush time before priority boost */
181 #endif
182 #if MEMORYSIZE <= 2
183 /* fractions must be integer fractions of 4 because they are evaluated with
184 * X*4*XXX_SECONDS, that way we avoid float calculation */
185 #define LOW_SECONDS 1/4 /* low watermark time till empty */
186 #define PANIC_SECONDS 1/2 /* flood watermark time until full */
187 #define FLUSH_SECONDS 1 /* flush watermark time until full */
188 #elif MEMORYSIZE <= 16
189 #define LOW_SECONDS 1 /* low watermark time till empty */
190 #define PANIC_SECONDS 5 /* flood watermark time until full */
191 #define FLUSH_SECONDS 7 /* flush watermark time until full */
192 #else
193 #define LOW_SECONDS 1 /* low watermark time till empty */
194 #define PANIC_SECONDS 8
195 #define FLUSH_SECONDS 10
196 #endif /* MEMORYSIZE */
198 /** encoder events **/
199 static void (*enc_events_callback)(enum enc_events event, void *data);
201 /** Path queue for files to write **/
202 #define FNQ_MIN_NUM_PATHS 16 /* minimum number of paths to hold */
203 #define FNQ_MAX_NUM_PATHS 64 /* maximum number of paths to hold */
204 static unsigned char *fn_queue; /* pointer to first filename */
205 static ssize_t fnq_size; /* capacity of queue in bytes */
206 static int fnq_rd_pos; /* current read position */
207 static int fnq_wr_pos; /* current write position */
208 #define FNQ_NEXT(pos) \
209 ({ int p = (pos) + MAX_PATH; \
210 if (p >= fnq_size) \
211 p = 0; \
212 p; })
213 #define FNQ_PREV(pos) \
214 ({ int p = (pos) - MAX_PATH; \
215 if (p < 0) \
216 p = fnq_size - MAX_PATH; \
217 p; })
219 enum
221 PCMREC_FLUSH_INTERRUPTABLE = 0x8000000, /* Flush can be interrupted by
222 incoming messages - combine
223 with other constants */
224 PCMREC_FLUSH_ALL = 0x7ffffff, /* Flush all files */
225 PCMREC_FLUSH_MINI = 0x7fffffe, /* Flush a small number of
226 chunks */
227 PCMREC_FLUSH_IF_HIGH = 0x0000000, /* Flush if high watermark
228 reached */
231 /***************************************************************************/
233 static struct event_queue pcmrec_queue SHAREDBSS_ATTR;
234 static struct queue_sender_list pcmrec_queue_send SHAREDBSS_ATTR;
235 static long pcmrec_stack[3*DEFAULT_STACK_SIZE/sizeof(long)];
236 static const char pcmrec_thread_name[] = "pcmrec";
237 static unsigned int pcmrec_thread_id = 0;
239 static void pcmrec_thread(void);
241 enum
243 PCMREC_NULL = 0,
244 PCMREC_INIT, /* enable recording */
245 PCMREC_CLOSE, /* close recording */
246 PCMREC_OPTIONS, /* set recording options */
247 PCMREC_RECORD, /* record a new file */
248 PCMREC_STOP, /* stop the current recording */
249 PCMREC_PAUSE, /* pause the current recording */
250 PCMREC_RESUME, /* resume the current recording */
251 #if 0
252 PCMREC_FLUSH_NUM, /* flush a number of files out */
253 #endif
256 /*******************************************************************/
257 /* Functions that are not executing in the pcmrec_thread first */
258 /*******************************************************************/
260 /* Callback for when more data is ready - called in interrupt context */
261 static void pcm_rec_have_more(int status, void **start, size_t *size)
263 if (status < 0)
265 /* some error condition */
266 if (status == DMA_REC_ERROR_DMA)
268 /* Flush recorded data to disk and stop recording */
269 queue_post(&pcmrec_queue, PCMREC_STOP, 0);
270 return;
272 /* else try again next transmission - frame is invalid */
274 else if (!dma_lock)
276 /* advance write position */
277 int next_pos = (dma_wr_pos + PCM_CHUNK_SIZE) & PCM_CHUNK_MASK;
279 /* set pcm ovf if processing start position is inside current
280 write chunk */
281 if ((unsigned)(pcm_enc_pos - next_pos) < PCM_CHUNK_SIZE)
282 warnings |= PCMREC_W_PCM_BUFFER_OVF;
284 dma_wr_pos = next_pos;
287 *start = GET_PCM_CHUNK(dma_wr_pos);
288 *size = PCM_CHUNK_SIZE;
289 } /* pcm_rec_have_more */
291 static void reset_hardware(void)
293 /* reset pcm to defaults */
294 pcm_set_frequency(REC_SAMPR_DEFAULT | SAMPR_TYPE_REC);
295 audio_set_output_source(AUDIO_SRC_PLAYBACK);
296 pcm_apply_settings();
299 /** pcm_rec_* group **/
302 * Clear all errors and warnings
304 void pcm_rec_error_clear(void)
306 errors = warnings = 0;
307 } /* pcm_rec_error_clear */
310 * Check mode, errors and warnings
312 unsigned long pcm_rec_status(void)
314 unsigned long ret = 0;
316 if (is_recording)
317 ret |= AUDIO_STATUS_RECORD;
318 else if (pre_record_ticks)
319 ret |= AUDIO_STATUS_PRERECORD;
321 if (is_paused)
322 ret |= AUDIO_STATUS_PAUSE;
324 if (errors)
325 ret |= AUDIO_STATUS_ERROR;
327 if (warnings)
328 ret |= AUDIO_STATUS_WARNING;
330 return ret;
331 } /* pcm_rec_status */
334 * Return warnings that have occured since recording started
336 unsigned long pcm_rec_get_warnings(void)
338 return warnings;
341 #if 0
342 int pcm_rec_current_bitrate(void)
344 if (accum_pcm_samples == 0)
345 return 0;
347 return (int)(8*accum_rec_bytes*enc_sample_rate / (1000*accum_pcm_samples));
348 } /* pcm_rec_current_bitrate */
349 #endif
351 #if 0
352 int pcm_rec_encoder_afmt(void)
354 return enc_config.afmt;
355 } /* pcm_rec_encoder_afmt */
356 #endif
358 #if 0
359 int pcm_rec_rec_format(void)
361 return afmt_rec_format[enc_config.afmt];
362 } /* pcm_rec_rec_format */
363 #endif
365 #ifdef HAVE_SPDIF_IN
366 unsigned long pcm_rec_sample_rate(void)
368 /* Which is better ?? */
369 #if 0
370 return enc_sample_rate;
371 #endif
372 return sample_rate;
373 } /* audio_get_sample_rate */
374 #endif
377 * Creates pcmrec_thread
379 void pcm_rec_init(void)
381 queue_init(&pcmrec_queue, true);
382 pcmrec_thread_id =
383 create_thread(pcmrec_thread, pcmrec_stack, sizeof(pcmrec_stack),
384 0, pcmrec_thread_name IF_PRIO(, PRIORITY_RECORDING)
385 IF_COP(, CPU));
386 queue_enable_queue_send(&pcmrec_queue, &pcmrec_queue_send,
387 pcmrec_thread_id);
388 } /* pcm_rec_init */
390 /** audio_* group **/
393 * Initializes recording - call before calling any other recording function
395 void audio_init_recording(void)
397 logf("audio_init_recording");
398 queue_send(&pcmrec_queue, PCMREC_INIT, 0);
399 logf("audio_init_recording done");
400 } /* audio_init_recording */
403 * Closes recording - call audio_stop_recording first
405 void audio_close_recording(void)
407 logf("audio_close_recording");
408 queue_send(&pcmrec_queue, PCMREC_CLOSE, 0);
409 logf("audio_close_recording done");
410 } /* audio_close_recording */
413 * Sets recording parameters
415 void audio_set_recording_options(struct audio_recording_options *options)
417 logf("audio_set_recording_options");
418 queue_send(&pcmrec_queue, PCMREC_OPTIONS, (intptr_t)options);
419 logf("audio_set_recording_options done");
420 } /* audio_set_recording_options */
423 * Start recording if not recording or else split
425 void audio_record(const char *filename)
427 logf("audio_record: %s", filename);
428 flush_interrupt();
429 queue_send(&pcmrec_queue, PCMREC_RECORD, (intptr_t)filename);
430 logf("audio_record_done");
431 } /* audio_record */
434 * audio_record wrapper for API compatibility with HW codec
436 void audio_new_file(const char *filename)
438 audio_record(filename);
439 } /* audio_new_file */
442 * Stop current recording if recording
444 void audio_stop_recording(void)
446 logf("audio_stop_recording");
447 flush_interrupt();
448 queue_post(&pcmrec_queue, PCMREC_STOP, 0);
449 logf("audio_stop_recording done");
450 } /* audio_stop_recording */
453 * Pause current recording
455 void audio_pause_recording(void)
457 logf("audio_pause_recording");
458 flush_interrupt();
459 queue_post(&pcmrec_queue, PCMREC_PAUSE, 0);
460 logf("audio_pause_recording done");
461 } /* audio_pause_recording */
464 * Resume current recording if paused
466 void audio_resume_recording(void)
468 logf("audio_resume_recording");
469 queue_post(&pcmrec_queue, PCMREC_RESUME, 0);
470 logf("audio_resume_recording done");
471 } /* audio_resume_recording */
474 * Note that microphone is mono, only left value is used
475 * See audiohw_set_recvol() for exact ranges.
477 * @param type AUDIO_GAIN_MIC, AUDIO_GAIN_LINEIN
480 void audio_set_recording_gain(int left, int right, int type)
482 //logf("rcmrec: t=%d l=%d r=%d", type, left, right);
483 audiohw_set_recvol(left, right, type);
484 } /* audio_set_recording_gain */
486 /** Information about current state **/
489 * Return current recorded time in ticks (playback eqivalent time)
491 unsigned long audio_recorded_time(void)
493 if (!is_recording || enc_sample_rate == 0)
494 return 0;
496 /* return actual recorded time a la encoded data even if encoder rate
497 doesn't match the pcm rate */
498 return (long)(HZ*(unsigned long long)num_rec_samples / enc_sample_rate);
499 } /* audio_recorded_time */
502 * Return number of bytes encoded to output
504 unsigned long audio_num_recorded_bytes(void)
506 if (!is_recording)
507 return 0;
509 return num_rec_bytes;
510 } /* audio_num_recorded_bytes */
512 /***************************************************************************/
513 /* */
514 /* Functions that execute in the context of pcmrec_thread */
515 /* */
516 /***************************************************************************/
518 /** Filename Queue **/
520 /* returns true if the queue is empty */
521 static inline bool pcmrec_fnq_is_empty(void)
523 return fnq_rd_pos == fnq_wr_pos;
524 } /* pcmrec_fnq_is_empty */
526 /* empties the filename queue */
527 static inline void pcmrec_fnq_set_empty(void)
529 fnq_rd_pos = fnq_wr_pos;
530 } /* pcmrec_fnq_set_empty */
532 /* returns true if the queue is full */
533 static bool pcmrec_fnq_is_full(void)
535 ssize_t size = fnq_wr_pos - fnq_rd_pos;
536 if (size < 0)
537 size += fnq_size;
539 return size >= fnq_size - MAX_PATH;
540 } /* pcmrec_fnq_is_full */
542 /* queue another filename - will overwrite oldest one if full */
543 static bool pcmrec_fnq_add_filename(const char *filename)
545 strlcpy(fn_queue + fnq_wr_pos, filename, MAX_PATH);
546 fnq_wr_pos = FNQ_NEXT(fnq_wr_pos);
548 if (fnq_rd_pos != fnq_wr_pos)
549 return true;
551 /* queue full */
552 fnq_rd_pos = FNQ_NEXT(fnq_rd_pos);
553 return true;
554 } /* pcmrec_fnq_add_filename */
556 /* replace the last filename added */
557 static bool pcmrec_fnq_replace_tail(const char *filename)
559 int pos;
561 if (pcmrec_fnq_is_empty())
562 return false;
564 pos = FNQ_PREV(fnq_wr_pos);
566 strlcpy(fn_queue + pos, filename, MAX_PATH);
568 return true;
569 } /* pcmrec_fnq_replace_tail */
571 /* pulls the next filename from the queue */
572 static bool pcmrec_fnq_get_filename(char *filename)
574 if (pcmrec_fnq_is_empty())
575 return false;
577 if (filename)
578 strlcpy(filename, fn_queue + fnq_rd_pos, MAX_PATH);
580 fnq_rd_pos = FNQ_NEXT(fnq_rd_pos);
581 return true;
582 } /* pcmrec_fnq_get_filename */
584 /* close the file number pointed to by fd_p */
585 static void pcmrec_close_file(int *fd_p)
587 if (*fd_p < 0)
588 return; /* preserve error */
590 if (close(*fd_p) != 0)
591 errors |= PCMREC_E_IO;
593 *fd_p = -1;
594 } /* pcmrec_close_file */
596 /** Data Flushing **/
599 * called after callback to update sizes if codec changed the amount of data
600 * a chunk represents
602 static inline void pcmrec_update_sizes_inl(size_t prev_enc_size,
603 unsigned long prev_num_pcm)
605 if (rec_fdata.new_enc_size != prev_enc_size)
607 ssize_t size_diff = rec_fdata.new_enc_size - prev_enc_size;
608 num_rec_bytes += size_diff;
609 #if 0
610 accum_rec_bytes += size_diff;
611 #endif
614 if (rec_fdata.new_num_pcm != prev_num_pcm)
616 unsigned long pcm_diff = rec_fdata.new_num_pcm - prev_num_pcm;
617 num_rec_samples += pcm_diff;
618 #if 0
619 accum_pcm_samples += pcm_diff;
620 #endif
622 } /* pcmrec_update_sizes_inl */
624 /* don't need to inline every instance */
625 static void pcmrec_update_sizes(size_t prev_enc_size,
626 unsigned long prev_num_pcm)
628 pcmrec_update_sizes_inl(prev_enc_size, prev_num_pcm);
629 } /* pcmrec_update_sizes */
631 static void pcmrec_start_file(void)
633 size_t enc_size = rec_fdata.new_enc_size;
634 unsigned long num_pcm = rec_fdata.new_num_pcm;
635 int curr_rec_file = rec_fdata.rec_file;
636 char filename[MAX_PATH];
638 /* must always pull the filename that matches with this queue */
639 if (!pcmrec_fnq_get_filename(filename))
641 logf("start file: fnq empty");
642 *filename = '\0';
643 errors |= PCMREC_E_FNQ_DESYNC;
645 else if (errors != 0)
647 logf("start file: error already");
649 else if (curr_rec_file >= 0)
651 /* Any previous file should have been closed */
652 logf("start file: file already open");
653 errors |= PCMREC_E_FNQ_DESYNC;
656 if (errors != 0)
657 rec_fdata.chunk->flags |= CHUNKF_ERROR;
659 /* encoder can set error flag here and should increase
660 enc_new_size and pcm_new_size to reflect additional
661 data written if any */
662 rec_fdata.filename = filename;
663 enc_events_callback(ENC_START_FILE, &rec_fdata);
665 if (errors == 0 && (rec_fdata.chunk->flags & CHUNKF_ERROR))
667 logf("start file: enc error");
668 errors |= PCMREC_E_ENCODER;
671 if (errors != 0)
673 pcmrec_close_file(&curr_rec_file);
674 /* Write no more to this file */
675 rec_fdata.chunk->flags |= CHUNKF_END_FILE;
677 else
679 pcmrec_update_sizes(enc_size, num_pcm);
682 rec_fdata.chunk->flags &= ~CHUNKF_START_FILE;
683 } /* pcmrec_start_file */
685 static inline void pcmrec_write_chunk(void)
687 size_t enc_size = rec_fdata.new_enc_size;
688 unsigned long num_pcm = rec_fdata.new_num_pcm;
690 if (errors != 0)
691 rec_fdata.chunk->flags |= CHUNKF_ERROR;
693 enc_events_callback(ENC_WRITE_CHUNK, &rec_fdata);
695 if ((long)rec_fdata.chunk->flags >= 0)
697 pcmrec_update_sizes_inl(enc_size, num_pcm);
699 else if (errors == 0)
701 logf("wr chk enc error %lu %lu",
702 rec_fdata.chunk->enc_size, rec_fdata.chunk->num_pcm);
703 errors |= PCMREC_E_ENCODER;
705 } /* pcmrec_write_chunk */
707 static void pcmrec_end_file(void)
709 /* all data in output buffer for current file will have been
710 written and encoder can now do any nescessary steps to
711 finalize the written file */
712 size_t enc_size = rec_fdata.new_enc_size;
713 unsigned long num_pcm = rec_fdata.new_num_pcm;
715 enc_events_callback(ENC_END_FILE, &rec_fdata);
717 if (errors == 0)
719 if (rec_fdata.chunk->flags & CHUNKF_ERROR)
721 logf("end file: enc error");
722 errors |= PCMREC_E_ENCODER;
724 else
726 pcmrec_update_sizes(enc_size, num_pcm);
730 /* Force file close if error */
731 if (errors != 0)
732 pcmrec_close_file(&rec_fdata.rec_file);
734 rec_fdata.chunk->flags &= ~CHUNKF_END_FILE;
735 } /* pcmrec_end_file */
738 * Update buffer watermarks with spinup time compensation
740 * All this assumes reasonable data rates, chunk sizes and sufficient
741 * memory for the most part. Some dumb checks are included but perhaps
742 * are pointless since this all will break down at extreme limits that
743 * are currently not applicable to any supported device.
745 static void pcmrec_refresh_watermarks(void)
747 logf("ata spinup: %d", storage_spinup_time());
749 /* set the low mark for when flushing stops if automatic */
750 /* don't change the order in this expression, LOW_SECONDS can be an
751 * integer fraction of 4 */
752 low_watermark = (sample_rate*4*LOW_SECONDS + (enc_chunk_size-1))
753 / enc_chunk_size;
754 logf("low wmk: %d", low_watermark);
756 #ifdef HAVE_PRIORITY_SCHEDULING
757 /* panic boost thread priority if 2 seconds of ground is lost -
758 this allows encoder to boost with just under a second of
759 pcm data (if not yet full enough to boost itself)
760 and not falsely trip the alarm. */
761 /* don't change the order in this expression, PANIC_SECONDS can be an
762 * integer fraction of 4 */
763 flood_watermark = enc_num_chunks -
764 (sample_rate*4*PANIC_SECONDS + (enc_chunk_size-1))
765 / enc_chunk_size;
767 if (flood_watermark < low_watermark)
769 logf("warning: panic < low");
770 flood_watermark = low_watermark;
773 logf("flood at: %d", flood_watermark);
774 #endif
775 spinup_time = last_storage_spinup_time = storage_spinup_time();
776 #if (CONFIG_STORAGE & STORAGE_ATA)
777 /* write at 8s + st remaining in enc_buffer - range 12s to
778 20s total - default to 3.5s spinup. */
779 if (spinup_time == 0)
780 spinup_time = 35*HZ/10; /* default - cozy */
781 else if (spinup_time < 2*HZ)
782 spinup_time = 2*HZ; /* ludicrous - ramdisk? */
783 else if (spinup_time > 10*HZ)
784 spinup_time = 10*HZ; /* do you have a functioning HD? */
785 #endif
787 /* try to start writing with 10s remaining after disk spinup */
788 high_watermark = enc_num_chunks -
789 ((FLUSH_SECONDS*HZ + spinup_time)*4*sample_rate +
790 (enc_chunk_size-1)*HZ) / (enc_chunk_size*HZ);
792 if (high_watermark < low_watermark)
794 logf("warning: low 'write at' (%d)", high_watermark);
795 high_watermark = low_watermark;
796 low_watermark /= 2;
799 logf("write at: %d", high_watermark);
800 } /* pcmrec_refresh_watermarks */
803 * Process the chunks
805 * This function is called when queue_get_w_tmo times out.
807 * Set flush_num to the number of files to flush to disk or to
808 * a PCMREC_FLUSH_* constant.
810 static void pcmrec_flush(unsigned flush_num)
812 #ifdef HAVE_PRIORITY_SCHEDULING
813 static unsigned long last_flush_tick; /* tick when function returned */
814 unsigned long start_tick; /* When flush started */
815 unsigned long prio_tick; /* Timeout for auto boost */
816 int prio_pcmrec; /* Current thread priority for pcmrec */
817 int prio_codec; /* Current thread priority for codec */
818 #endif
819 int num_ready; /* Number of chunks ready at start */
820 unsigned remaining; /* Number of file starts remaining */
821 unsigned chunks_flushed; /* Chunks flushed (for mini flush only) */
822 bool interruptable; /* Flush can be interupted */
824 num_ready = enc_wr_index - enc_rd_index;
825 if (num_ready < 0)
826 num_ready += enc_num_chunks;
828 /* save interruptable flag and remove it to get the actual count */
829 interruptable = (flush_num & PCMREC_FLUSH_INTERRUPTABLE) != 0;
830 flush_num &= ~PCMREC_FLUSH_INTERRUPTABLE;
832 if (flush_num == 0)
834 if (!is_recording)
835 return;
837 if (storage_spinup_time() != last_storage_spinup_time)
838 pcmrec_refresh_watermarks();
840 /* enough available? no? then leave */
841 if (num_ready < high_watermark)
842 return;
843 } /* endif (flush_num == 0) */
845 #ifdef HAVE_PRIORITY_SCHEDULING
846 start_tick = current_tick;
847 prio_tick = start_tick + PRIO_SECONDS*HZ + spinup_time;
849 if (flush_num == 0 && TIME_BEFORE(current_tick, last_flush_tick + HZ/2))
851 /* if we're getting called too much and this isn't forced,
852 boost stat by expiring timeout in advance */
853 logf("too frequent flush");
854 prio_tick = current_tick - 1;
857 prio_pcmrec = -1;
858 prio_codec = -1; /* GCC is too stoopid to figure out it doesn't
859 need init */
860 #endif
862 logf("writing:%d(%d):%s%s", num_ready, flush_num,
863 interruptable ? "i" : "",
864 flush_num == PCMREC_FLUSH_MINI ? "m" : "");
866 cpu_boost(true);
868 remaining = flush_num;
869 chunks_flushed = 0;
871 while (num_ready > 0)
873 /* check current number of encoder chunks */
874 int num = enc_wr_index - enc_rd_index;
875 if (num < 0)
876 num += enc_num_chunks;
878 if (num <= low_watermark &&
879 (flush_num == PCMREC_FLUSH_IF_HIGH || num <= 0))
881 logf("low data: %d", num);
882 break; /* data remaining is below threshold */
885 if (interruptable && flush_interrupts > 0)
887 logf("int at: %d", num);
888 break; /* interrupted */
891 #ifdef HAVE_PRIORITY_SCHEDULING
892 if (prio_pcmrec == -1 && (num >= flood_watermark ||
893 TIME_AFTER(current_tick, prio_tick)))
895 /* losing ground or holding without progress - boost
896 priority until finished */
897 logf("pcmrec: boost (%s)",
898 num >= flood_watermark ? "num" : "time");
899 prio_pcmrec = thread_set_priority(thread_self(),
900 thread_get_priority(thread_self()) - 4);
901 prio_codec = codec_thread_set_priority(
902 codec_thread_get_priority() - 4);
904 #endif
906 rec_fdata.chunk = GET_ENC_CHUNK(enc_rd_index);
907 rec_fdata.new_enc_size = rec_fdata.chunk->enc_size;
908 rec_fdata.new_num_pcm = rec_fdata.chunk->num_pcm;
910 if (rec_fdata.chunk->flags & CHUNKF_START_FILE)
912 pcmrec_start_file();
913 if (--remaining == 0)
914 num_ready = 0; /* stop on next loop - must write this
915 chunk if it has data */
918 pcmrec_write_chunk();
920 if (rec_fdata.chunk->flags & CHUNKF_END_FILE)
921 pcmrec_end_file();
923 INC_ENC_INDEX(enc_rd_index);
925 if (errors != 0)
927 pcmrec_end_file();
928 break;
931 if (flush_num == PCMREC_FLUSH_MINI &&
932 ++chunks_flushed >= MINI_CHUNKS)
934 logf("mini flush break");
935 break;
937 /* no yielding; the file apis called in the codecs do that
938 sufficiently */
939 } /* end while */
941 /* sync file */
942 if (rec_fdata.rec_file >= 0 && fsync(rec_fdata.rec_file) != 0)
943 errors |= PCMREC_E_IO;
945 cpu_boost(false);
947 #ifdef HAVE_PRIORITY_SCHEDULING
948 if (prio_pcmrec != -1)
950 /* return to original priorities */
951 logf("pcmrec: unboost priority");
952 thread_set_priority(thread_self(), prio_pcmrec);
953 codec_thread_set_priority(prio_codec);
956 last_flush_tick = current_tick; /* save tick when we left */
957 #endif
959 logf("done");
960 } /* pcmrec_flush */
963 * Marks a new stream in the buffer and gives the encoder a chance for special
964 * handling of transition from one to the next. The encoder may change the
965 * chunk that ends the old stream by requesting more chunks and similiarly for
966 * the new but must always advance the position though the interface. It can
967 * later reject any data it cares to when writing the file but should mark the
968 * chunk so it can recognize this. ENC_WRITE_CHUNK event must be able to accept
969 * a NULL data pointer without error as well.
971 static int pcmrec_get_chunk_index(struct enc_chunk_hdr *chunk)
973 return ((char *)chunk - (char *)enc_buffer) / enc_chunk_size;
974 } /* pcmrec_get_chunk_index */
976 static struct enc_chunk_hdr * pcmrec_get_prev_chunk(int index)
978 DEC_ENC_INDEX(index);
979 return GET_ENC_CHUNK(index);
980 } /* pcmrec_get_prev_chunk */
982 static void pcmrec_new_stream(const char *filename, /* next file name */
983 unsigned long flags, /* CHUNKF_* flags */
984 int pre_index) /* index for prerecorded data */
986 logf("pcmrec_new_stream");
987 char path[MAX_PATH]; /* place to copy filename so sender can be released */
989 struct enc_buffer_event_data data;
990 bool (*fnq_add_fn)(const char *) = NULL; /* function to use to add
991 new filename */
992 struct enc_chunk_hdr *start = NULL; /* pointer to starting chunk of
993 stream */
994 bool did_flush = false; /* did a flush occurr? */
996 if (filename)
997 strlcpy(path, filename, MAX_PATH);
998 queue_reply(&pcmrec_queue, 0); /* We have all we need */
1000 data.pre_chunk = NULL;
1001 data.chunk = GET_ENC_CHUNK(enc_wr_index);
1003 /* end chunk */
1004 if (flags & CHUNKF_END_FILE)
1006 data.chunk->flags &= CHUNKF_START_FILE | CHUNKF_END_FILE;
1008 if (data.chunk->flags & CHUNKF_START_FILE)
1010 /* cannot start and end on same unprocessed chunk */
1011 logf("file end on start");
1012 flags &= ~CHUNKF_END_FILE;
1014 else if (enc_rd_index == enc_wr_index)
1016 /* all data flushed but file not ended - chunk will be left
1017 empty */
1018 logf("end on dead end");
1019 data.chunk->flags = 0;
1020 data.chunk->enc_size = 0;
1021 data.chunk->num_pcm = 0;
1022 data.chunk->enc_data = NULL;
1023 INC_ENC_INDEX(enc_wr_index);
1024 data.chunk = GET_ENC_CHUNK(enc_wr_index);
1026 else
1028 struct enc_chunk_hdr *last = pcmrec_get_prev_chunk(enc_wr_index);
1030 if (last->flags & CHUNKF_END_FILE)
1032 /* end already processed and marked - can't end twice */
1033 logf("file end again");
1034 flags &= ~CHUNKF_END_FILE;
1039 /* start chunk */
1040 if (flags & CHUNKF_START_FILE)
1042 bool pre = flags & CHUNKF_PRERECORD;
1044 if (pre)
1046 logf("stream prerecord start");
1047 start = data.pre_chunk = GET_ENC_CHUNK(pre_index);
1048 start->flags &= CHUNKF_START_FILE | CHUNKF_PRERECORD;
1050 else
1052 logf("stream normal start");
1053 start = data.chunk;
1054 start->flags &= CHUNKF_START_FILE;
1057 /* if encoder hasn't yet processed the last start - abort the start
1058 of the previous file queued or else it will be empty and invalid */
1059 if (start->flags & CHUNKF_START_FILE)
1061 logf("replacing fnq tail: %s", filename);
1062 fnq_add_fn = pcmrec_fnq_replace_tail;
1064 else
1066 logf("adding filename: %s", filename);
1067 fnq_add_fn = pcmrec_fnq_add_filename;
1071 data.flags = flags;
1072 pcmrec_context = true; /* switch encoder context */
1073 enc_events_callback(ENC_REC_NEW_STREAM, &data);
1074 pcmrec_context = false; /* switch back */
1076 if (flags & CHUNKF_END_FILE)
1078 int i = pcmrec_get_chunk_index(data.chunk);
1079 pcmrec_get_prev_chunk(i)->flags |= CHUNKF_END_FILE;
1082 if (start)
1084 if (!(flags & CHUNKF_PRERECORD))
1086 /* get stats on data added to start - sort of a prerecord
1087 operation */
1088 int i = pcmrec_get_chunk_index(data.chunk);
1089 struct enc_chunk_hdr *chunk = data.chunk;
1091 logf("start data: %d %d", i, enc_wr_index);
1093 num_rec_bytes = 0;
1094 num_rec_samples = 0;
1096 while (i != enc_wr_index)
1098 num_rec_bytes += chunk->enc_size;
1099 num_rec_samples += chunk->num_pcm;
1100 INC_ENC_INDEX(i);
1101 chunk = GET_ENC_CHUNK(i);
1104 start->flags &= ~CHUNKF_START_FILE;
1105 start = data.chunk;
1108 start->flags |= CHUNKF_START_FILE;
1110 /* flush all pending files out if full and adding */
1111 if (fnq_add_fn == pcmrec_fnq_add_filename && pcmrec_fnq_is_full())
1113 logf("fnq full");
1114 pcmrec_flush(PCMREC_FLUSH_ALL);
1115 did_flush = true;
1118 fnq_add_fn(path);
1121 /* Make sure to complete any interrupted high watermark */
1122 if (!did_flush)
1123 pcmrec_flush(PCMREC_FLUSH_IF_HIGH);
1124 } /* pcmrec_new_stream */
1126 /** event handlers for pcmrec thread */
1128 /* PCMREC_INIT */
1129 static void pcmrec_init(void)
1131 unsigned char *buffer;
1132 send_event(RECORDING_EVENT_START, NULL);
1134 /* warings and errors */
1135 warnings =
1136 errors = 0;
1138 pcmrec_close_file(&rec_fdata.rec_file);
1139 rec_fdata.rec_file = -1;
1141 /* pcm FIFO */
1142 dma_lock = true;
1143 pcm_rd_pos = 0;
1144 dma_wr_pos = 0;
1145 pcm_enc_pos = 0;
1147 /* encoder FIFO */
1148 enc_wr_index = 0;
1149 enc_rd_index = 0;
1151 /* filename queue */
1152 fnq_rd_pos = 0;
1153 fnq_wr_pos = 0;
1155 /* stats */
1156 num_rec_bytes = 0;
1157 num_rec_samples = 0;
1158 #if 0
1159 accum_rec_bytes = 0;
1160 accum_pcm_samples = 0;
1161 #endif
1163 pre_record_ticks = 0;
1165 is_recording = false;
1166 is_paused = false;
1168 buffer = audio_get_recording_buffer(&rec_buffer_size);
1170 /* Line align pcm_buffer 2^5=32 bytes */
1171 pcm_buffer = (unsigned char *)ALIGN_UP_P2((uintptr_t)buffer, 5);
1172 enc_buffer = pcm_buffer + ALIGN_UP_P2(PCM_NUM_CHUNKS*PCM_CHUNK_SIZE +
1173 PCM_MAX_FEED_SIZE, 2);
1174 /* Adjust available buffer for possible align advancement */
1175 rec_buffer_size -= pcm_buffer - buffer;
1177 pcm_init_recording();
1178 } /* pcmrec_init */
1180 /* PCMREC_CLOSE */
1181 static void pcmrec_close(void)
1183 dma_lock = true;
1184 pre_record_ticks = 0; /* Can't be prerecording any more */
1185 warnings = 0;
1186 pcm_close_recording();
1187 reset_hardware();
1188 audio_remove_encoder();
1189 send_event(RECORDING_EVENT_STOP, NULL);
1190 } /* pcmrec_close */
1192 /* PCMREC_OPTIONS */
1193 static void pcmrec_set_recording_options(
1194 struct audio_recording_options *options)
1196 /* stop DMA transfer */
1197 dma_lock = true;
1198 pcm_stop_recording();
1200 rec_frequency = options->rec_frequency;
1201 rec_source = options->rec_source;
1202 num_channels = options->rec_channels == 1 ? 1 : 2;
1203 rec_mono_mode = options->rec_mono_mode;
1204 pre_record_ticks = options->rec_prerecord_time * HZ;
1205 enc_config = options->enc_config;
1206 enc_config.afmt = rec_format_afmt[enc_config.rec_format];
1208 #ifdef HAVE_SPDIF_IN
1209 if (rec_source == AUDIO_SRC_SPDIF)
1211 /* must measure SPDIF sample rate before configuring codecs */
1212 unsigned long sr = spdif_measure_frequency();
1213 /* round to master list for SPDIF rate */
1214 int index = round_value_to_list32(sr, audio_master_sampr_list,
1215 SAMPR_NUM_FREQ, false);
1216 sample_rate = audio_master_sampr_list[index];
1217 /* round to HW playback rates for monitoring */
1218 index = round_value_to_list32(sr, hw_freq_sampr,
1219 HW_NUM_FREQ, false);
1220 pcm_set_frequency(hw_freq_sampr[index] | SAMPR_TYPE_REC);
1221 /* encoders with a limited number of rates do their own rounding */
1223 else
1224 #endif
1226 /* set sample rate from frequency selection */
1227 sample_rate = rec_freq_sampr[rec_frequency];
1228 pcm_set_frequency(sample_rate | SAMPR_TYPE_REC);
1231 /* set monitoring */
1232 audio_set_output_source(rec_source);
1234 /* apply hardware setting to start monitoring now */
1235 pcm_apply_settings();
1237 queue_reply(&pcmrec_queue, 0); /* Release sender */
1239 if (audio_load_encoder(enc_config.afmt))
1241 /* start DMA transfer */
1242 dma_lock = pre_record_ticks == 0;
1243 pcm_record_data(pcm_rec_have_more, GET_PCM_CHUNK(dma_wr_pos),
1244 PCM_CHUNK_SIZE);
1246 else
1248 logf("set rec opt: enc load failed");
1249 errors |= PCMREC_E_LOAD_ENCODER;
1251 } /* pcmrec_set_recording_options */
1253 /* PCMREC_RECORD - start recording (not gapless)
1254 or split stream (gapless) */
1255 static void pcmrec_record(const char *filename)
1257 unsigned long pre_sample_ticks;
1258 int rd_start;
1259 unsigned long flags;
1260 int pre_index;
1262 logf("pcmrec_record: %s", filename);
1264 /* reset stats */
1265 num_rec_bytes = 0;
1266 num_rec_samples = 0;
1268 if (!is_recording)
1270 #if 0
1271 accum_rec_bytes = 0;
1272 accum_pcm_samples = 0;
1273 #endif
1274 warnings = 0; /* reset warnings */
1276 rd_start = enc_wr_index;
1277 pre_sample_ticks = 0;
1279 pcmrec_refresh_watermarks();
1281 if (pre_record_ticks)
1283 int i = rd_start;
1284 /* calculate number of available chunks */
1285 unsigned long avail_pre_chunks = (enc_wr_index - enc_rd_index +
1286 enc_num_chunks) % enc_num_chunks;
1287 /* overflow at 974 seconds of prerecording at 44.1kHz */
1288 unsigned long pre_record_sample_ticks =
1289 enc_sample_rate*pre_record_ticks;
1290 int pre_chunks = 0; /* Counter to limit prerecorded time to
1291 prevent flood state at outset */
1293 logf("pre-st: %ld", pre_record_sample_ticks);
1295 /* Get exact measure of recorded data as number of samples aren't
1296 nescessarily going to be the max for each chunk */
1297 for (; avail_pre_chunks-- > 0;)
1299 struct enc_chunk_hdr *chunk;
1300 unsigned long chunk_sample_ticks;
1302 DEC_ENC_INDEX(i);
1304 chunk = GET_ENC_CHUNK(i);
1306 /* must have data to be counted */
1307 if (chunk->enc_data == NULL)
1308 continue;
1310 chunk_sample_ticks = chunk->num_pcm*HZ;
1312 rd_start = i;
1313 pre_sample_ticks += chunk_sample_ticks;
1314 num_rec_bytes += chunk->enc_size;
1315 num_rec_samples += chunk->num_pcm;
1316 pre_chunks++;
1318 /* stop here if enough already */
1319 if (pre_chunks >= high_watermark ||
1320 pre_sample_ticks >= pre_record_sample_ticks)
1322 logf("pre-chks: %d", pre_chunks);
1323 break;
1327 #if 0
1328 accum_rec_bytes = num_rec_bytes;
1329 accum_pcm_samples = num_rec_samples;
1330 #endif
1333 enc_rd_index = rd_start;
1335 /* filename queue should be empty */
1336 if (!pcmrec_fnq_is_empty())
1338 logf("fnq: not empty!");
1339 pcmrec_fnq_set_empty();
1342 flags = CHUNKF_START_FILE;
1343 if (pre_sample_ticks > 0)
1344 flags |= CHUNKF_PRERECORD;
1346 pre_index = enc_rd_index;
1348 dma_lock = false;
1349 is_paused = false;
1350 is_recording = true;
1352 else
1354 /* already recording, just split the stream */
1355 logf("inserting split");
1356 flags = CHUNKF_START_FILE | CHUNKF_END_FILE;
1357 pre_index = 0;
1360 pcmrec_new_stream(filename, flags, pre_index);
1361 logf("pcmrec_record done");
1362 } /* pcmrec_record */
1364 /* PCMREC_STOP */
1365 static void pcmrec_stop(void)
1367 logf("pcmrec_stop");
1369 if (is_recording)
1371 dma_lock = true; /* lock dma write position */
1373 /* flush all available data first to avoid overflow while waiting
1374 for encoding to finish */
1375 pcmrec_flush(PCMREC_FLUSH_ALL);
1377 /* wait for encoder to finish remaining data */
1378 while (errors == 0 && !pcm_buffer_empty)
1379 yield();
1381 /* end stream at last data */
1382 pcmrec_new_stream(NULL, CHUNKF_END_FILE, 0);
1384 /* flush anything else encoder added */
1385 pcmrec_flush(PCMREC_FLUSH_ALL);
1387 /* remove any pending file start not yet processed - should be at
1388 most one at enc_wr_index */
1389 pcmrec_fnq_get_filename(NULL);
1390 /* encoder should abort any chunk it was in midst of processing */
1391 GET_ENC_CHUNK(enc_wr_index)->flags = CHUNKF_ABORT;
1393 /* filename queue should be empty */
1394 if (!pcmrec_fnq_is_empty())
1396 logf("fnq: not empty!");
1397 pcmrec_fnq_set_empty();
1400 /* be absolutely sure the file is closed */
1401 if (errors != 0)
1402 pcmrec_close_file(&rec_fdata.rec_file);
1403 rec_fdata.rec_file = -1;
1405 is_recording = false;
1406 is_paused = false;
1407 dma_lock = pre_record_ticks == 0;
1409 else
1411 logf("not recording");
1414 logf("pcmrec_stop done");
1415 } /* pcmrec_stop */
1417 /* PCMREC_PAUSE */
1418 static void pcmrec_pause(void)
1420 logf("pcmrec_pause");
1422 if (!is_recording)
1424 logf("not recording");
1426 else if (is_paused)
1428 logf("already paused");
1430 else
1432 dma_lock = true;
1433 is_paused = true;
1436 logf("pcmrec_pause done");
1437 } /* pcmrec_pause */
1439 /* PCMREC_RESUME */
1440 static void pcmrec_resume(void)
1442 logf("pcmrec_resume");
1444 if (!is_recording)
1446 logf("not recording");
1448 else if (!is_paused)
1450 logf("not paused");
1452 else
1454 is_paused = false;
1455 is_recording = true;
1456 dma_lock = false;
1459 logf("pcmrec_resume done");
1460 } /* pcmrec_resume */
1462 static void pcmrec_thread(void) NORETURN_ATTR;
1463 static void pcmrec_thread(void)
1465 struct queue_event ev;
1467 logf("thread pcmrec start");
1469 while(1)
1471 if (is_recording)
1473 /* Poll periodically to flush data */
1474 queue_wait_w_tmo(&pcmrec_queue, &ev, HZ/5);
1476 if (ev.id == SYS_TIMEOUT)
1478 /* Messages that interrupt this will complete it */
1479 pcmrec_flush(PCMREC_FLUSH_IF_HIGH |
1480 PCMREC_FLUSH_INTERRUPTABLE);
1481 continue;
1484 else
1486 /* Not doing anything - sit and wait for commands */
1487 queue_wait(&pcmrec_queue, &ev);
1490 switch (ev.id)
1492 case PCMREC_INIT:
1493 pcmrec_init();
1494 break;
1496 case PCMREC_CLOSE:
1497 pcmrec_close();
1498 break;
1500 case PCMREC_OPTIONS:
1501 pcmrec_set_recording_options(
1502 (struct audio_recording_options *)ev.data);
1503 break;
1505 case PCMREC_RECORD:
1506 clear_flush_interrupt();
1507 pcmrec_record((const char *)ev.data);
1508 break;
1510 case PCMREC_STOP:
1511 clear_flush_interrupt();
1512 pcmrec_stop();
1513 break;
1515 case PCMREC_PAUSE:
1516 clear_flush_interrupt();
1517 pcmrec_pause();
1518 break;
1520 case PCMREC_RESUME:
1521 pcmrec_resume();
1522 break;
1523 #if 0
1524 case PCMREC_FLUSH_NUM:
1525 pcmrec_flush((unsigned)ev.data);
1526 break;
1527 #endif
1528 case SYS_USB_CONNECTED:
1529 if (is_recording)
1530 break;
1531 pcmrec_close();
1532 usb_acknowledge(SYS_USB_CONNECTED_ACK);
1533 usb_wait_for_disconnect(&pcmrec_queue);
1534 flush_interrupts = 0;
1535 break;
1536 } /* end switch */
1537 } /* end while */
1538 } /* pcmrec_thread */
1540 /****************************************************************************/
1541 /* */
1542 /* following functions will be called by the encoder codec */
1543 /* in a free-threaded manner */
1544 /* */
1545 /****************************************************************************/
1547 /* pass the encoder settings to the encoder */
1548 void enc_get_inputs(struct enc_inputs *inputs)
1550 inputs->sample_rate = sample_rate;
1551 inputs->num_channels = num_channels;
1552 inputs->rec_mono_mode = rec_mono_mode;
1553 inputs->config = &enc_config;
1554 } /* enc_get_inputs */
1556 /* set the encoder dimensions (called by encoder codec at initialization and
1557 termination) */
1558 void enc_set_parameters(struct enc_parameters *params)
1560 size_t bufsize, resbytes;
1562 logf("enc_set_parameters");
1564 if (!params)
1566 logf("reset");
1567 /* Encoder is terminating */
1568 memset(&enc_config, 0, sizeof (enc_config));
1569 enc_sample_rate = 0;
1570 cancel_cpu_boost(); /* Make sure no boost remains */
1571 return;
1574 enc_sample_rate = params->enc_sample_rate;
1575 logf("enc sampr:%lu", enc_sample_rate);
1577 pcm_rd_pos = dma_wr_pos;
1578 pcm_enc_pos = pcm_rd_pos;
1580 enc_config.afmt = params->afmt;
1581 /* addition of the header is always implied - chunk size 4-byte aligned */
1582 enc_chunk_size =
1583 ALIGN_UP_P2(ENC_CHUNK_HDR_SIZE + params->chunk_size, 2);
1584 enc_events_callback = params->events_callback;
1586 logf("chunk size:%lu", enc_chunk_size);
1588 /*** Configure the buffers ***/
1590 /* Layout of recording buffer:
1591 * [ax] = possible alignment x multiple
1592 * [sx] = possible size alignment of x multiple
1593 * |[a16]|[s4]:PCM Buffer+PCM Guard|[s4 each]:Encoder Chunks|->
1594 * |[[s4]:Reserved Bytes]|Filename Queue->|[space]|
1596 resbytes = ALIGN_UP_P2(params->reserve_bytes, 2);
1597 logf("resbytes:%lu", resbytes);
1599 bufsize = rec_buffer_size - (enc_buffer - pcm_buffer) -
1600 resbytes - FNQ_MIN_NUM_PATHS*MAX_PATH
1601 #ifdef DEBUG
1602 - sizeof (*wrap_id_p)
1603 #endif
1606 enc_num_chunks = bufsize / enc_chunk_size;
1607 logf("num chunks:%d", enc_num_chunks);
1609 /* get real amount used by encoder chunks */
1610 bufsize = enc_num_chunks*enc_chunk_size;
1611 logf("enc size:%lu", bufsize);
1613 #ifdef DEBUG
1614 /* add magic at wraparound for spillover checks */
1615 wrap_id_p = SKIPBYTES((unsigned long *)enc_buffer, bufsize);
1616 bufsize += sizeof (*wrap_id_p);
1617 *wrap_id_p = ENC_CHUNK_MAGIC;
1618 #endif
1620 /** set OUT parameters **/
1621 params->enc_buffer = enc_buffer;
1622 params->buf_chunk_size = enc_chunk_size;
1623 params->num_chunks = enc_num_chunks;
1625 /* calculate reserve buffer start and return pointer to encoder */
1626 params->reserve_buffer = NULL;
1627 if (resbytes > 0)
1629 params->reserve_buffer = enc_buffer + bufsize;
1630 bufsize += resbytes;
1633 /* place filename queue at end of buffer using up whatever remains */
1634 fnq_rd_pos = 0; /* reset */
1635 fnq_wr_pos = 0; /* reset */
1636 fn_queue = enc_buffer + bufsize;
1637 fnq_size = pcm_buffer + rec_buffer_size - fn_queue;
1638 fnq_size /= MAX_PATH;
1639 if (fnq_size > FNQ_MAX_NUM_PATHS)
1640 fnq_size = FNQ_MAX_NUM_PATHS;
1641 fnq_size *= MAX_PATH;
1642 logf("fnq files:%ld", fnq_size / MAX_PATH);
1644 #if defined(DEBUG)
1645 logf("pcm:%08lX", (uintptr_t)pcm_buffer);
1646 logf("enc:%08lX", (uintptr_t)enc_buffer);
1647 logf("res:%08lX", (uintptr_t)params->reserve_buffer);
1648 logf("wip:%08lX", (uintptr_t)wrap_id_p);
1649 logf("fnq:%08lX", (uintptr_t)fn_queue);
1650 logf("end:%08lX", (uintptr_t)fn_queue + fnq_size);
1651 #endif
1653 /* init all chunk headers and reset indexes */
1654 enc_rd_index = 0;
1655 for (enc_wr_index = enc_num_chunks; enc_wr_index > 0; )
1657 struct enc_chunk_hdr *chunk = GET_ENC_CHUNK(--enc_wr_index);
1658 #ifdef DEBUG
1659 chunk->id = ENC_CHUNK_MAGIC;
1660 #endif
1661 chunk->flags = 0;
1664 logf("enc_set_parameters done");
1665 } /* enc_set_parameters */
1667 /* return encoder chunk at current write position -
1668 NOTE: can be called by pcmrec thread when splitting streams */
1669 struct enc_chunk_hdr * enc_get_chunk(void)
1671 struct enc_chunk_hdr *chunk = GET_ENC_CHUNK(enc_wr_index);
1673 #ifdef DEBUG
1674 if (chunk->id != ENC_CHUNK_MAGIC || *wrap_id_p != ENC_CHUNK_MAGIC)
1676 errors |= PCMREC_E_CHUNK_OVF;
1677 logf("finish chk ovf: %d", enc_wr_index);
1679 #endif
1681 chunk->flags &= CHUNKF_START_FILE;
1683 if (!is_recording)
1684 chunk->flags |= CHUNKF_PRERECORD;
1686 return chunk;
1687 } /* enc_get_chunk */
1689 /* releases the current chunk into the available chunks -
1690 NOTE: can be called by pcmrec thread when splitting streams */
1691 void enc_finish_chunk(void)
1693 struct enc_chunk_hdr *chunk = GET_ENC_CHUNK(enc_wr_index);
1695 if ((long)chunk->flags < 0)
1697 /* encoder set error flag */
1698 errors |= PCMREC_E_ENCODER;
1699 logf("finish chk enc error");
1702 /* advance enc_wr_index to the next encoder chunk */
1703 INC_ENC_INDEX(enc_wr_index);
1705 if (enc_rd_index != enc_wr_index)
1707 num_rec_bytes += chunk->enc_size;
1708 num_rec_samples += chunk->num_pcm;
1709 #if 0
1710 accum_rec_bytes += chunk->enc_size;
1711 accum_pcm_samples += chunk->num_pcm;
1712 #endif
1714 else if (is_recording) /* buffer full */
1716 /* keep current position and put up warning flag */
1717 warnings |= PCMREC_W_ENC_BUFFER_OVF;
1718 logf("enc_buffer ovf");
1719 DEC_ENC_INDEX(enc_wr_index);
1720 if (pcmrec_context)
1722 /* if stream splitting, keep this out of circulation and
1723 flush a small number, then readd - cannot risk losing
1724 stream markers */
1725 logf("mini flush");
1726 pcmrec_flush(PCMREC_FLUSH_MINI);
1727 INC_ENC_INDEX(enc_wr_index);
1730 else
1732 /* advance enc_rd_index for prerecording */
1733 INC_ENC_INDEX(enc_rd_index);
1735 } /* enc_finish_chunk */
1737 /* passes a pointer to next chunk of unprocessed wav data */
1738 /* TODO: this really should give the actual size returned */
1739 unsigned char * enc_get_pcm_data(size_t size)
1741 int wp = dma_wr_pos;
1742 size_t avail = (wp - pcm_rd_pos) & PCM_CHUNK_MASK;
1744 /* limit the requested pcm data size */
1745 if (size > PCM_MAX_FEED_SIZE)
1746 size = PCM_MAX_FEED_SIZE;
1748 if (avail >= size)
1750 unsigned char *ptr = pcm_buffer + pcm_rd_pos;
1751 int next_pos = (pcm_rd_pos + size) & PCM_CHUNK_MASK;
1753 pcm_enc_pos = pcm_rd_pos;
1754 pcm_rd_pos = next_pos;
1756 /* ptr must point to continous data at wraparound position */
1757 if ((size_t)pcm_rd_pos < size)
1759 memcpy(pcm_buffer + PCM_NUM_CHUNKS*PCM_CHUNK_SIZE,
1760 pcm_buffer, pcm_rd_pos);
1763 if (avail >= (sample_rate << 2))
1765 /* Filling up - boost codec */
1766 trigger_cpu_boost();
1769 pcm_buffer_empty = false;
1770 return ptr;
1773 /* not enough data available - encoder should idle */
1774 pcm_buffer_empty = true;
1776 cancel_cpu_boost();
1778 /* Sleep long enough to allow one frame on average */
1779 sleep(0);
1781 return NULL;
1782 } /* enc_get_pcm_data */
1784 /* puts some pcm data back in the queue */
1785 size_t enc_unget_pcm_data(size_t size)
1787 int wp = dma_wr_pos;
1788 size_t old_avail = ((pcm_rd_pos - wp) & PCM_CHUNK_MASK) -
1789 2*PCM_CHUNK_SIZE;
1791 /* allow one interrupt to occur during this call and not have the
1792 new read position inside the DMA destination chunk */
1793 if ((ssize_t)old_avail > 0)
1795 /* limit size to amount of old data remaining */
1796 if (size > old_avail)
1797 size = old_avail;
1799 pcm_enc_pos = (pcm_rd_pos - size) & PCM_CHUNK_MASK;
1800 pcm_rd_pos = pcm_enc_pos;
1802 return size;
1805 return 0;
1806 } /* enc_unget_pcm_data */