Fix a few comments.
[Rockbox.git] / firmware / pcm_record.c
blob1437b438baf32122e24796203cec010110a49629
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2005 by Linus Nielsen Feltzing
12 * All files in this archive are subject to the GNU General Public License.
13 * See the file COPYING in the source tree root for full license agreement.
15 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
16 * KIND, either express or implied.
18 ****************************************************************************/
19 #include "system.h"
20 #include "kernel.h"
21 #include "logf.h"
22 #include "thread.h"
23 #include <string.h>
24 #include "ata.h"
25 #include "usb.h"
26 #include "buffer.h"
27 #include "general.h"
28 #include "audio.h"
29 #include "sound.h"
30 #include "id3.h"
31 #ifdef HAVE_SPDIF_IN
32 #include "spdif.h"
33 #endif
35 /***************************************************************************/
37 extern struct thread_entry *codec_thread_p;
39 /** General recording state **/
40 static bool is_recording; /* We are recording */
41 static bool is_paused; /* We have paused */
42 static unsigned long errors; /* An error has occured */
43 static unsigned long warnings; /* Warning */
44 static int flush_interrupts = 0; /* Number of messages queued that
45 should interrupt a flush in
46 progress -
47 for a safety net and a prompt
48 response to stop, split and pause
49 requests -
50 only interrupts a flush initiated
51 by pcmrec_flush(0) */
53 /* Utility functions for setting/clearing flushing interrupt flag */
54 static inline void flush_interrupt(void)
56 flush_interrupts++;
57 logf("flush int: %d", flush_interrupts);
60 static inline void clear_flush_interrupt(void)
62 if (--flush_interrupts < 0)
63 flush_interrupts = 0;
66 /** Stats on encoded data for current file **/
67 static size_t num_rec_bytes; /* Num bytes recorded */
68 static unsigned long num_rec_samples; /* Number of PCM samples recorded */
70 /** Stats on encoded data for all files from start to stop **/
71 #if 0
72 static unsigned long long accum_rec_bytes; /* total size written to chunks */
73 static unsigned long long accum_pcm_samples; /* total pcm count processed */
74 #endif
76 /* Keeps data about current file and is sent as event data for codec */
77 static struct enc_file_event_data rec_fdata IDATA_ATTR =
79 .chunk = NULL,
80 .new_enc_size = 0,
81 .new_num_pcm = 0,
82 .rec_file = -1,
83 .num_pcm_samples = 0
86 /** These apply to current settings **/
87 static int rec_source; /* current rec_source setting */
88 static int rec_frequency; /* current frequency setting */
89 static unsigned long sample_rate; /* Sample rate in HZ */
90 static int num_channels; /* Current number of channels */
91 static struct encoder_config enc_config; /* Current encoder configuration */
92 static unsigned long pre_record_ticks; /* pre-record time in ticks */
94 /****************************************************************************
95 use 2 circular buffers:
96 pcm_buffer=DMA output buffer: chunks (8192 Bytes) of raw pcm audio data
97 enc_buffer=encoded audio buffer: storage for encoder output data
99 Flow:
100 1. when entering recording_screen DMA feeds the ringbuffer pcm_buffer
101 2. if enough pcm data are available the encoder codec does encoding of pcm
102 chunks (4-8192 Bytes) into ringbuffer enc_buffer in codec_thread
103 3. pcmrec_callback detects enc_buffer 'near full' and writes data to disk
105 Functions calls (basic encoder steps):
106 1.main: audio_load_encoder(); start the encoder
107 2.encoder: enc_get_inputs(); get encoder recording settings
108 3.encoder: enc_set_parameters(); set the encoder parameters
109 4.encoder: enc_get_pcm_data(); get n bytes of unprocessed pcm data
110 5.encoder: enc_unget_pcm_data(); put n bytes of data back (optional)
111 6.encoder: enc_get_chunk(); get a ptr to next enc chunk
112 7.encoder: <process enc chunk> compress and store data to enc chunk
113 8.encoder: enc_finish_chunk(); inform main about chunk processed and
114 is available to be written to a file.
115 Encoder can place any number of chunks
116 of PCM data in a single output chunk
117 but must stay within its output chunk
118 size
119 9.encoder: repeat 4. to 8.
120 A.pcmrec: enc_events_callback(); called for certain events
122 (*) Optional step
123 ****************************************************************************/
125 /** buffer parameters where incoming PCM data is placed **/
126 #define PCM_NUM_CHUNKS 256 /* Power of 2 */
127 #define PCM_CHUNK_SIZE 8192 /* Power of 2 */
128 #define PCM_CHUNK_MASK (PCM_NUM_CHUNKS*PCM_CHUNK_SIZE - 1)
130 #define GET_PCM_CHUNK(offset) ((long *)(pcm_buffer + (offset)))
131 #define GET_ENC_CHUNK(index) ENC_CHUNK_HDR(enc_buffer + enc_chunk_size*(index))
132 #define INC_ENC_INDEX(index) \
133 { if (++index >= enc_num_chunks) index = 0; }
134 #define DEC_ENC_INDEX(index) \
135 { if (--index < 0) index = enc_num_chunks - 1; }
137 static size_t rec_buffer_size; /* size of available buffer */
138 static unsigned char *pcm_buffer; /* circular recording buffer */
139 static unsigned char *enc_buffer; /* circular encoding buffer */
140 #ifdef DEBUG
141 static unsigned long *wrap_id_p; /* magic at wrap position - a debugging
142 aid to check if the encoder data
143 spilled out of its chunk */
144 #endif /* DEBUG */
145 static volatile int dma_wr_pos; /* current DMA write pos */
146 static int pcm_rd_pos; /* current PCM read pos */
147 static int pcm_enc_pos; /* position encoder is processing */
148 static volatile bool dma_lock; /* lock DMA write position */
149 static int enc_wr_index; /* encoder chunk write index */
150 static int enc_rd_index; /* encoder chunk read index */
151 static int enc_num_chunks; /* number of chunks in ringbuffer */
152 static size_t enc_chunk_size; /* maximum encoder chunk size */
153 static unsigned long enc_sample_rate; /* sample rate used by encoder */
154 static bool pcmrec_context = false; /* called by pcmrec thread? */
155 static bool pcm_buffer_empty; /* all pcm chunks processed? */
157 /** file flushing **/
158 static int low_watermark; /* Low watermark to stop flush */
159 static int high_watermark; /* max chunk limit for data flush */
160 static unsigned long spinup_time = 35*HZ/10; /* Fudged spinup time */
161 static int last_ata_spinup_time = -1;/* previous spin time used */
162 #ifdef HAVE_PRIORITY_SCHEDULING
163 static int flood_watermark; /* boost thread priority when here */
164 #endif
166 /* Constants that control watermarks */
167 #define LOW_SECONDS 1 /* low watermark time till empty */
168 #define MINI_CHUNKS 10 /* chunk count for mini flush */
169 #ifdef HAVE_PRIORITY_SCHEDULING
170 #define PRIO_SECONDS 10 /* max flush time before priority boost */
171 #endif
172 #if MEM <= 16
173 #define PANIC_SECONDS 5 /* flood watermark time until full */
174 #define FLUSH_SECONDS 7 /* flush watermark time until full */
175 #else
176 #define PANIC_SECONDS 8
177 #define FLUSH_SECONDS 10
178 #endif /* MEM */
180 /** encoder events **/
181 static void (*enc_events_callback)(enum enc_events event, void *data);
183 /** Path queue for files to write **/
184 #define FNQ_MIN_NUM_PATHS 16 /* minimum number of paths to hold */
185 #define FNQ_MAX_NUM_PATHS 64 /* maximum number of paths to hold */
186 static unsigned char *fn_queue; /* pointer to first filename */
187 static ssize_t fnq_size; /* capacity of queue in bytes */
188 static int fnq_rd_pos; /* current read position */
189 static int fnq_wr_pos; /* current write position */
190 #define FNQ_NEXT(pos) \
191 ({ int p = (pos) + MAX_PATH; \
192 if (p >= fnq_size) \
193 p = 0; \
194 p; })
195 #define FNQ_PREV(pos) \
196 ({ int p = (pos) - MAX_PATH; \
197 if (p < 0) \
198 p = fnq_size - MAX_PATH; \
199 p; })
201 enum
203 PCMREC_FLUSH_INTERRUPTABLE = 0x8000000, /* Flush can be interrupted by
204 incoming messages - combine
205 with other constants */
206 PCMREC_FLUSH_ALL = 0x7ffffff, /* Flush all files */
207 PCMREC_FLUSH_MINI = 0x7fffffe, /* Flush a small number of
208 chunks */
209 PCMREC_FLUSH_IF_HIGH = 0x0000000, /* Flush if high watermark
210 reached */
213 /***************************************************************************/
215 static struct event_queue pcmrec_queue NOCACHEBSS_ATTR;
216 static struct queue_sender_list pcmrec_queue_send NOCACHEBSS_ATTR;
217 static long pcmrec_stack[3*DEFAULT_STACK_SIZE/sizeof(long)];
218 static const char pcmrec_thread_name[] = "pcmrec";
219 static struct thread_entry *pcmrec_thread_p;
221 static void pcmrec_thread(void);
223 enum
225 PCMREC_NULL = 0,
226 PCMREC_INIT, /* enable recording */
227 PCMREC_CLOSE, /* close recording */
228 PCMREC_OPTIONS, /* set recording options */
229 PCMREC_RECORD, /* record a new file */
230 PCMREC_STOP, /* stop the current recording */
231 PCMREC_PAUSE, /* pause the current recording */
232 PCMREC_RESUME, /* resume the current recording */
233 #if 0
234 PCMREC_FLUSH_NUM, /* flush a number of files out */
235 #endif
238 /*******************************************************************/
239 /* Functions that are not executing in the pcmrec_thread first */
240 /*******************************************************************/
242 /* Callback for when more data is ready - called in interrupt context */
243 static int pcm_rec_have_more(int status)
245 if (status < 0)
247 /* some error condition */
248 if (status == DMA_REC_ERROR_DMA)
250 /* Flush recorded data to disk and stop recording */
251 queue_post(&pcmrec_queue, PCMREC_STOP, 0);
252 return -1;
254 /* else try again next transmission */
256 else if (!dma_lock)
258 /* advance write position */
259 int next_pos = (dma_wr_pos + PCM_CHUNK_SIZE) & PCM_CHUNK_MASK;
261 /* set pcm ovf if processing start position is inside current
262 write chunk */
263 if ((unsigned)(pcm_enc_pos - next_pos) < PCM_CHUNK_SIZE)
264 warnings |= PCMREC_W_PCM_BUFFER_OVF;
266 dma_wr_pos = next_pos;
269 pcm_record_more(GET_PCM_CHUNK(dma_wr_pos), PCM_CHUNK_SIZE);
270 return 0;
271 } /* pcm_rec_have_more */
273 static void reset_hardware(void)
275 /* reset pcm to defaults (playback only) */
276 pcm_set_frequency(HW_SAMPR_DEFAULT);
277 audio_set_output_source(AUDIO_SRC_PLAYBACK);
278 pcm_apply_settings();
281 /** pcm_rec_* group **/
284 * Clear all errors and warnings
286 void pcm_rec_error_clear(void)
288 errors = warnings = 0;
289 } /* pcm_rec_error_clear */
292 * Check mode, errors and warnings
294 unsigned long pcm_rec_status(void)
296 unsigned long ret = 0;
298 if (is_recording)
299 ret |= AUDIO_STATUS_RECORD;
300 else if (pre_record_ticks)
301 ret |= AUDIO_STATUS_PRERECORD;
303 if (is_paused)
304 ret |= AUDIO_STATUS_PAUSE;
306 if (errors)
307 ret |= AUDIO_STATUS_ERROR;
309 if (warnings)
310 ret |= AUDIO_STATUS_WARNING;
312 return ret;
313 } /* pcm_rec_status */
316 * Return warnings that have occured since recording started
318 unsigned long pcm_rec_get_warnings(void)
320 return warnings;
323 #if 0
324 int pcm_rec_current_bitrate(void)
326 if (accum_pcm_samples == 0)
327 return 0;
329 return (int)(8*accum_rec_bytes*enc_sample_rate / (1000*accum_pcm_samples));
330 } /* pcm_rec_current_bitrate */
331 #endif
333 #if 0
334 int pcm_rec_encoder_afmt(void)
336 return enc_config.afmt;
337 } /* pcm_rec_encoder_afmt */
338 #endif
340 #if 0
341 int pcm_rec_rec_format(void)
343 return afmt_rec_format[enc_config.afmt];
344 } /* pcm_rec_rec_format */
345 #endif
347 #ifdef HAVE_SPDIF_IN
348 unsigned long pcm_rec_sample_rate(void)
350 /* Which is better ?? */
351 #if 0
352 return enc_sample_rate;
353 #endif
354 return sample_rate;
355 } /* audio_get_sample_rate */
356 #endif
359 * Creates pcmrec_thread
361 void pcm_rec_init(void)
363 queue_init(&pcmrec_queue, true);
364 queue_enable_queue_send(&pcmrec_queue, &pcmrec_queue_send);
365 pcmrec_thread_p =
366 create_thread(pcmrec_thread, pcmrec_stack, sizeof(pcmrec_stack),
367 0, pcmrec_thread_name IF_PRIO(, PRIORITY_RECORDING)
368 IF_COP(, CPU));
369 } /* pcm_rec_init */
371 /** audio_* group **/
374 * Initializes recording - call before calling any other recording function
376 void audio_init_recording(unsigned int buffer_offset)
378 logf("audio_init_recording");
379 queue_send(&pcmrec_queue, PCMREC_INIT, 0);
380 logf("audio_init_recording done");
381 (void)buffer_offset;
382 } /* audio_init_recording */
385 * Closes recording - call audio_stop_recording first
387 void audio_close_recording(void)
389 logf("audio_close_recording");
390 queue_send(&pcmrec_queue, PCMREC_CLOSE, 0);
391 logf("audio_close_recording done");
392 } /* audio_close_recording */
395 * Sets recording parameters
397 void audio_set_recording_options(struct audio_recording_options *options)
399 logf("audio_set_recording_options");
400 queue_send(&pcmrec_queue, PCMREC_OPTIONS, (intptr_t)options);
401 logf("audio_set_recording_options done");
402 } /* audio_set_recording_options */
405 * Start recording if not recording or else split
407 void audio_record(const char *filename)
409 logf("audio_record: %s", filename);
410 flush_interrupt();
411 queue_send(&pcmrec_queue, PCMREC_RECORD, (intptr_t)filename);
412 logf("audio_record_done");
413 } /* audio_record */
416 * audio_record wrapper for API compatibility with HW codec
418 void audio_new_file(const char *filename)
420 audio_record(filename);
421 } /* audio_new_file */
424 * Stop current recording if recording
426 void audio_stop_recording(void)
428 logf("audio_stop_recording");
429 flush_interrupt();
430 queue_post(&pcmrec_queue, PCMREC_STOP, 0);
431 logf("audio_stop_recording done");
432 } /* audio_stop_recording */
435 * Pause current recording
437 void audio_pause_recording(void)
439 logf("audio_pause_recording");
440 flush_interrupt();
441 queue_post(&pcmrec_queue, PCMREC_PAUSE, 0);
442 logf("audio_pause_recording done");
443 } /* audio_pause_recording */
446 * Resume current recording if paused
448 void audio_resume_recording(void)
450 logf("audio_resume_recording");
451 queue_post(&pcmrec_queue, PCMREC_RESUME, 0);
452 logf("audio_resume_recording done");
453 } /* audio_resume_recording */
456 * Note that microphone is mono, only left value is used
457 * See audiohw_set_recvol() for exact ranges.
459 * @param type AUDIO_GAIN_MIC, AUDIO_GAIN_LINEIN
462 void audio_set_recording_gain(int left, int right, int type)
464 //logf("rcmrec: t=%d l=%d r=%d", type, left, right);
465 audiohw_set_recvol(left, right, type);
466 } /* audio_set_recording_gain */
468 /** Information about current state **/
471 * Return current recorded time in ticks (playback eqivalent time)
473 unsigned long audio_recorded_time(void)
475 if (!is_recording || enc_sample_rate == 0)
476 return 0;
478 /* return actual recorded time a la encoded data even if encoder rate
479 doesn't match the pcm rate */
480 return (long)(HZ*(unsigned long long)num_rec_samples / enc_sample_rate);
481 } /* audio_recorded_time */
484 * Return number of bytes encoded to output
486 unsigned long audio_num_recorded_bytes(void)
488 if (!is_recording)
489 return 0;
491 return num_rec_bytes;
492 } /* audio_num_recorded_bytes */
494 /***************************************************************************/
495 /* */
496 /* Functions that execute in the context of pcmrec_thread */
497 /* */
498 /***************************************************************************/
500 /** Filename Queue **/
502 /* returns true if the queue is empty */
503 static inline bool pcmrec_fnq_is_empty(void)
505 return fnq_rd_pos == fnq_wr_pos;
506 } /* pcmrec_fnq_is_empty */
508 /* empties the filename queue */
509 static inline void pcmrec_fnq_set_empty(void)
511 fnq_rd_pos = fnq_wr_pos;
512 } /* pcmrec_fnq_set_empty */
514 /* returns true if the queue is full */
515 static bool pcmrec_fnq_is_full(void)
517 ssize_t size = fnq_wr_pos - fnq_rd_pos;
518 if (size < 0)
519 size += fnq_size;
521 return size >= fnq_size - MAX_PATH;
522 } /* pcmrec_fnq_is_full */
524 /* queue another filename - will overwrite oldest one if full */
525 static bool pcmrec_fnq_add_filename(const char *filename)
527 strncpy(fn_queue + fnq_wr_pos, filename, MAX_PATH);
528 fnq_wr_pos = FNQ_NEXT(fnq_wr_pos);
530 if (fnq_rd_pos != fnq_wr_pos)
531 return true;
533 /* queue full */
534 fnq_rd_pos = FNQ_NEXT(fnq_rd_pos);
535 return true;
536 } /* pcmrec_fnq_add_filename */
538 /* replace the last filename added */
539 static bool pcmrec_fnq_replace_tail(const char *filename)
541 int pos;
543 if (pcmrec_fnq_is_empty())
544 return false;
546 pos = FNQ_PREV(fnq_wr_pos);
548 strncpy(fn_queue + pos, filename, MAX_PATH);
550 return true;
551 } /* pcmrec_fnq_replace_tail */
553 /* pulls the next filename from the queue */
554 static bool pcmrec_fnq_get_filename(char *filename)
556 if (pcmrec_fnq_is_empty())
557 return false;
559 if (filename)
560 strncpy(filename, fn_queue + fnq_rd_pos, MAX_PATH);
562 fnq_rd_pos = FNQ_NEXT(fnq_rd_pos);
563 return true;
564 } /* pcmrec_fnq_get_filename */
566 /* close the file number pointed to by fd_p */
567 static void pcmrec_close_file(int *fd_p)
569 if (*fd_p < 0)
570 return; /* preserve error */
572 if (close(*fd_p) != 0)
573 errors |= PCMREC_E_IO;
575 *fd_p = -1;
576 } /* pcmrec_close_file */
578 /** Data Flushing **/
581 * called after callback to update sizes if codec changed the amount of data
582 * a chunk represents
584 static inline void pcmrec_update_sizes_inl(size_t prev_enc_size,
585 unsigned long prev_num_pcm)
587 if (rec_fdata.new_enc_size != prev_enc_size)
589 ssize_t size_diff = rec_fdata.new_enc_size - prev_enc_size;
590 num_rec_bytes += size_diff;
591 #if 0
592 accum_rec_bytes += size_diff;
593 #endif
596 if (rec_fdata.new_num_pcm != prev_num_pcm)
598 unsigned long pcm_diff = rec_fdata.new_num_pcm - prev_num_pcm;
599 num_rec_samples += pcm_diff;
600 #if 0
601 accum_pcm_samples += pcm_diff;
602 #endif
604 } /* pcmrec_update_sizes_inl */
606 /* don't need to inline every instance */
607 static void pcmrec_update_sizes(size_t prev_enc_size,
608 unsigned long prev_num_pcm)
610 pcmrec_update_sizes_inl(prev_enc_size, prev_num_pcm);
611 } /* pcmrec_update_sizes */
613 static void pcmrec_start_file(void)
615 size_t enc_size = rec_fdata.new_enc_size;
616 unsigned long num_pcm = rec_fdata.new_num_pcm;
617 int curr_rec_file = rec_fdata.rec_file;
618 char filename[MAX_PATH];
620 /* must always pull the filename that matches with this queue */
621 if (!pcmrec_fnq_get_filename(filename))
623 logf("start file: fnq empty");
624 *filename = '\0';
625 errors |= PCMREC_E_FNQ_DESYNC;
627 else if (errors != 0)
629 logf("start file: error already");
631 else if (curr_rec_file >= 0)
633 /* Any previous file should have been closed */
634 logf("start file: file already open");
635 errors |= PCMREC_E_FNQ_DESYNC;
638 if (errors != 0)
639 rec_fdata.chunk->flags |= CHUNKF_ERROR;
641 /* encoder can set error flag here and should increase
642 enc_new_size and pcm_new_size to reflect additional
643 data written if any */
644 rec_fdata.filename = filename;
645 enc_events_callback(ENC_START_FILE, &rec_fdata);
647 if (errors == 0 && (rec_fdata.chunk->flags & CHUNKF_ERROR))
649 logf("start file: enc error");
650 errors |= PCMREC_E_ENCODER;
653 if (errors != 0)
655 pcmrec_close_file(&curr_rec_file);
656 /* Write no more to this file */
657 rec_fdata.chunk->flags |= CHUNKF_END_FILE;
659 else
661 pcmrec_update_sizes(enc_size, num_pcm);
664 rec_fdata.chunk->flags &= ~CHUNKF_START_FILE;
665 } /* pcmrec_start_file */
667 static inline void pcmrec_write_chunk(void)
669 size_t enc_size = rec_fdata.new_enc_size;
670 unsigned long num_pcm = rec_fdata.new_num_pcm;
672 if (errors != 0)
673 rec_fdata.chunk->flags |= CHUNKF_ERROR;
675 enc_events_callback(ENC_WRITE_CHUNK, &rec_fdata);
677 if ((long)rec_fdata.chunk->flags >= 0)
679 pcmrec_update_sizes_inl(enc_size, num_pcm);
681 else if (errors == 0)
683 logf("wr chk enc error %lu %lu",
684 rec_fdata.chunk->enc_size, rec_fdata.chunk->num_pcm);
685 errors |= PCMREC_E_ENCODER;
687 } /* pcmrec_write_chunk */
689 static void pcmrec_end_file(void)
691 /* all data in output buffer for current file will have been
692 written and encoder can now do any nescessary steps to
693 finalize the written file */
694 size_t enc_size = rec_fdata.new_enc_size;
695 unsigned long num_pcm = rec_fdata.new_num_pcm;
697 enc_events_callback(ENC_END_FILE, &rec_fdata);
699 if (errors == 0)
701 if (rec_fdata.chunk->flags & CHUNKF_ERROR)
703 logf("end file: enc error");
704 errors |= PCMREC_E_ENCODER;
706 else
708 pcmrec_update_sizes(enc_size, num_pcm);
712 /* Force file close if error */
713 if (errors != 0)
714 pcmrec_close_file(&rec_fdata.rec_file);
716 rec_fdata.chunk->flags &= ~CHUNKF_END_FILE;
717 } /* pcmrec_end_file */
720 * Update buffer watermarks with spinup time compensation
722 * All this assumes reasonable data rates, chunk sizes and sufficient
723 * memory for the most part. Some dumb checks are included but perhaps
724 * are pointless since this all will break down at extreme limits that
725 * are currently not applicable to any supported device.
727 static void pcmrec_refresh_watermarks(void)
729 logf("ata spinup: %d", ata_spinup_time);
731 /* set the low mark for when flushing stops if automatic */
732 low_watermark = (LOW_SECONDS*4*sample_rate + (enc_chunk_size-1))
733 / enc_chunk_size;
734 logf("low wmk: %d", low_watermark);
736 #ifdef HAVE_PRIORITY_SCHEDULING
737 /* panic boost thread priority if 2 seconds of ground is lost -
738 this allows encoder to boost with just under a second of
739 pcm data (if not yet full enough to boost itself)
740 and not falsely trip the alarm. */
741 flood_watermark = enc_num_chunks -
742 (PANIC_SECONDS*4*sample_rate + (enc_chunk_size-1))
743 / enc_chunk_size;
745 if (flood_watermark < low_watermark)
747 logf("warning: panic < low");
748 flood_watermark = low_watermark;
751 logf("flood at: %d", flood_watermark);
752 #endif
753 spinup_time = last_ata_spinup_time = ata_spinup_time;
755 /* write at 8s + st remaining in enc_buffer - range 12s to
756 20s total - default to 3.5s spinup. */
757 if (spinup_time == 0)
758 spinup_time = 35*HZ/10; /* default - cozy */
759 else if (spinup_time < 2*HZ)
760 spinup_time = 2*HZ; /* ludicrous - ramdisk? */
761 else if (spinup_time > 10*HZ)
762 spinup_time = 10*HZ; /* do you have a functioning HD? */
764 /* try to start writing with 10s remaining after disk spinup */
765 high_watermark = enc_num_chunks -
766 ((FLUSH_SECONDS*HZ + spinup_time)*4*sample_rate +
767 (enc_chunk_size-1)*HZ) / (enc_chunk_size*HZ);
769 if (high_watermark < low_watermark)
771 high_watermark = low_watermark;
772 low_watermark /= 2;
773 logf("warning: low 'write at'");
776 logf("write at: %d", high_watermark);
777 } /* pcmrec_refresh_watermarks */
780 * Process the chunks
782 * This function is called when queue_get_w_tmo times out.
784 * Set flush_num to the number of files to flush to disk or to
785 * a PCMREC_FLUSH_* constant.
787 static void pcmrec_flush(unsigned flush_num)
789 #ifdef HAVE_PRIORITY_SCHEDULING
790 static unsigned long last_flush_tick; /* tick when function returned */
791 unsigned long start_tick; /* When flush started */
792 unsigned long prio_tick; /* Timeout for auto boost */
793 int prio_pcmrec; /* Current thread priority for pcmrec */
794 int prio_codec; /* Current thread priority for codec */
795 #endif
796 int num_ready; /* Number of chunks ready at start */
797 unsigned remaining; /* Number of file starts remaining */
798 unsigned chunks_flushed; /* Chunks flushed (for mini flush only) */
799 bool interruptable; /* Flush can be interupted */
801 num_ready = enc_wr_index - enc_rd_index;
802 if (num_ready < 0)
803 num_ready += enc_num_chunks;
805 /* save interruptable flag and remove it to get the actual count */
806 interruptable = (flush_num & PCMREC_FLUSH_INTERRUPTABLE) != 0;
807 flush_num &= ~PCMREC_FLUSH_INTERRUPTABLE;
809 if (flush_num == 0)
811 if (!is_recording)
812 return;
814 if (ata_spinup_time != last_ata_spinup_time)
815 pcmrec_refresh_watermarks();
817 /* enough available? no? then leave */
818 if (num_ready < high_watermark)
819 return;
820 } /* endif (flush_num == 0) */
822 #ifdef HAVE_PRIORITY_SCHEDULING
823 start_tick = current_tick;
824 prio_tick = start_tick + PRIO_SECONDS*HZ + spinup_time;
826 if (flush_num == 0 && TIME_BEFORE(current_tick, last_flush_tick + HZ/2))
828 /* if we're getting called too much and this isn't forced,
829 boost stat by expiring timeout in advance */
830 logf("too frequent flush");
831 prio_tick = current_tick - 1;
834 prio_pcmrec = -1;
835 prio_codec = -1; /* GCC is too stoopid to figure out it doesn't
836 need init */
837 #endif
839 logf("writing:%d(%d):%s%s", num_ready, flush_num,
840 interruptable ? "i" : "",
841 flush_num == PCMREC_FLUSH_MINI ? "m" : "");
843 cpu_boost(true);
845 remaining = flush_num;
846 chunks_flushed = 0;
848 while (num_ready > 0)
850 /* check current number of encoder chunks */
851 int num = enc_wr_index - enc_rd_index;
852 if (num < 0)
853 num += enc_num_chunks;
855 if (num <= low_watermark &&
856 (flush_num == PCMREC_FLUSH_IF_HIGH || num <= 0))
858 logf("low data: %d", num);
859 break; /* data remaining is below threshold */
862 if (interruptable && flush_interrupts > 0)
864 logf("int at: %d", num);
865 break; /* interrupted */
868 #ifdef HAVE_PRIORITY_SCHEDULING
869 if (prio_pcmrec == -1 && (num >= flood_watermark ||
870 TIME_AFTER(current_tick, prio_tick)))
872 /* losing ground or holding without progress - boost
873 priority until finished */
874 logf("pcmrec: boost (%s)",
875 num >= flood_watermark ? "num" : "time");
876 prio_pcmrec = thread_set_priority(NULL,
877 thread_get_priority(NULL) - 1);
878 prio_codec = thread_set_priority(codec_thread_p,
879 thread_get_priority(codec_thread_p) - 1);
881 #endif
883 rec_fdata.chunk = GET_ENC_CHUNK(enc_rd_index);
884 rec_fdata.new_enc_size = rec_fdata.chunk->enc_size;
885 rec_fdata.new_num_pcm = rec_fdata.chunk->num_pcm;
887 if (rec_fdata.chunk->flags & CHUNKF_START_FILE)
889 pcmrec_start_file();
890 if (--remaining == 0)
891 num_ready = 0; /* stop on next loop - must write this
892 chunk if it has data */
895 pcmrec_write_chunk();
897 if (rec_fdata.chunk->flags & CHUNKF_END_FILE)
898 pcmrec_end_file();
900 INC_ENC_INDEX(enc_rd_index);
902 if (errors != 0)
904 pcmrec_end_file();
905 break;
908 if (flush_num == PCMREC_FLUSH_MINI &&
909 ++chunks_flushed >= MINI_CHUNKS)
911 logf("mini flush break");
912 break;
914 /* no yielding; the file apis called in the codecs do that
915 sufficiently */
916 } /* end while */
918 /* sync file */
919 if (rec_fdata.rec_file >= 0 && fsync(rec_fdata.rec_file) != 0)
920 errors |= PCMREC_E_IO;
922 cpu_boost(false);
924 #ifdef HAVE_PRIORITY_SCHEDULING
925 if (prio_pcmrec != -1)
927 /* return to original priorities */
928 logf("pcmrec: unboost priority");
929 thread_set_priority(NULL, prio_pcmrec);
930 thread_set_priority(codec_thread_p, prio_codec);
933 last_flush_tick = current_tick; /* save tick when we left */
934 #endif
936 logf("done");
937 } /* pcmrec_flush */
940 * Marks a new stream in the buffer and gives the encoder a chance for special
941 * handling of transition from one to the next. The encoder may change the
942 * chunk that ends the old stream by requesting more chunks and similiarly for
943 * the new but must always advance the position though the interface. It can
944 * later reject any data it cares to when writing the file but should mark the
945 * chunk so it can recognize this. ENC_WRITE_CHUNK event must be able to accept
946 * a NULL data pointer without error as well.
948 static int pcmrec_get_chunk_index(struct enc_chunk_hdr *chunk)
950 return ((char *)chunk - (char *)enc_buffer) / enc_chunk_size;
951 } /* pcmrec_get_chunk_index */
953 static struct enc_chunk_hdr * pcmrec_get_prev_chunk(int index)
955 DEC_ENC_INDEX(index);
956 return GET_ENC_CHUNK(index);
957 } /* pcmrec_get_prev_chunk */
959 static void pcmrec_new_stream(const char *filename, /* next file name */
960 unsigned long flags, /* CHUNKF_* flags */
961 int pre_index) /* index for prerecorded data */
963 logf("pcmrec_new_stream");
964 char path[MAX_PATH]; /* place to copy filename so sender can be released */
966 struct enc_buffer_event_data data;
967 bool (*fnq_add_fn)(const char *) = NULL; /* function to use to add
968 new filename */
969 struct enc_chunk_hdr *start = NULL; /* pointer to starting chunk of
970 stream */
971 bool did_flush = false; /* did a flush occurr? */
973 if (filename)
974 strncpy(path, filename, MAX_PATH);
975 queue_reply(&pcmrec_queue, 0); /* We have all we need */
977 data.pre_chunk = NULL;
978 data.chunk = GET_ENC_CHUNK(enc_wr_index);
980 /* end chunk */
981 if (flags & CHUNKF_END_FILE)
983 data.chunk->flags &= CHUNKF_START_FILE | CHUNKF_END_FILE;
985 if (data.chunk->flags & CHUNKF_START_FILE)
987 /* cannot start and end on same unprocessed chunk */
988 logf("file end on start");
989 flags &= ~CHUNKF_END_FILE;
991 else if (enc_rd_index == enc_wr_index)
993 /* all data flushed but file not ended - chunk will be left
994 empty */
995 logf("end on dead end");
996 data.chunk->flags = 0;
997 data.chunk->enc_size = 0;
998 data.chunk->num_pcm = 0;
999 data.chunk->enc_data = NULL;
1000 INC_ENC_INDEX(enc_wr_index);
1001 data.chunk = GET_ENC_CHUNK(enc_wr_index);
1003 else
1005 struct enc_chunk_hdr *last = pcmrec_get_prev_chunk(enc_wr_index);
1007 if (last->flags & CHUNKF_END_FILE)
1009 /* end already processed and marked - can't end twice */
1010 logf("file end again");
1011 flags &= ~CHUNKF_END_FILE;
1016 /* start chunk */
1017 if (flags & CHUNKF_START_FILE)
1019 bool pre = flags & CHUNKF_PRERECORD;
1021 if (pre)
1023 logf("stream prerecord start");
1024 start = data.pre_chunk = GET_ENC_CHUNK(pre_index);
1025 start->flags &= CHUNKF_START_FILE | CHUNKF_PRERECORD;
1027 else
1029 logf("stream normal start");
1030 start = data.chunk;
1031 start->flags &= CHUNKF_START_FILE;
1034 /* if encoder hasn't yet processed the last start - abort the start
1035 of the previous file queued or else it will be empty and invalid */
1036 if (start->flags & CHUNKF_START_FILE)
1038 logf("replacing fnq tail: %s", filename);
1039 fnq_add_fn = pcmrec_fnq_replace_tail;
1041 else
1043 logf("adding filename: %s", filename);
1044 fnq_add_fn = pcmrec_fnq_add_filename;
1048 data.flags = flags;
1049 pcmrec_context = true; /* switch encoder context */
1050 enc_events_callback(ENC_REC_NEW_STREAM, &data);
1051 pcmrec_context = false; /* switch back */
1053 if (flags & CHUNKF_END_FILE)
1055 int i = pcmrec_get_chunk_index(data.chunk);
1056 pcmrec_get_prev_chunk(i)->flags |= CHUNKF_END_FILE;
1059 if (start)
1061 if (!(flags & CHUNKF_PRERECORD))
1063 /* get stats on data added to start - sort of a prerecord
1064 operation */
1065 int i = pcmrec_get_chunk_index(data.chunk);
1066 struct enc_chunk_hdr *chunk = data.chunk;
1068 logf("start data: %d %d", i, enc_wr_index);
1070 num_rec_bytes = 0;
1071 num_rec_samples = 0;
1073 while (i != enc_wr_index)
1075 num_rec_bytes += chunk->enc_size;
1076 num_rec_samples += chunk->num_pcm;
1077 INC_ENC_INDEX(i);
1078 chunk = GET_ENC_CHUNK(i);
1081 start->flags &= ~CHUNKF_START_FILE;
1082 start = data.chunk;
1085 start->flags |= CHUNKF_START_FILE;
1087 /* flush all pending files out if full and adding */
1088 if (fnq_add_fn == pcmrec_fnq_add_filename && pcmrec_fnq_is_full())
1090 logf("fnq full");
1091 pcmrec_flush(PCMREC_FLUSH_ALL);
1092 did_flush = true;
1095 fnq_add_fn(path);
1098 /* Make sure to complete any interrupted high watermark */
1099 if (!did_flush)
1100 pcmrec_flush(PCMREC_FLUSH_IF_HIGH);
1101 } /* pcmrec_new_stream */
1103 /** event handlers for pcmrec thread */
1105 /* PCMREC_INIT */
1106 static void pcmrec_init(void)
1108 unsigned char *buffer;
1110 /* warings and errors */
1111 warnings =
1112 errors = 0;
1114 pcmrec_close_file(&rec_fdata.rec_file);
1115 rec_fdata.rec_file = -1;
1117 /* pcm FIFO */
1118 dma_lock = true;
1119 pcm_rd_pos = 0;
1120 dma_wr_pos = 0;
1121 pcm_enc_pos = 0;
1123 /* encoder FIFO */
1124 enc_wr_index = 0;
1125 enc_rd_index = 0;
1127 /* filename queue */
1128 fnq_rd_pos = 0;
1129 fnq_wr_pos = 0;
1131 /* stats */
1132 num_rec_bytes = 0;
1133 num_rec_samples = 0;
1134 #if 0
1135 accum_rec_bytes = 0;
1136 accum_pcm_samples = 0;
1137 #endif
1139 pre_record_ticks = 0;
1141 is_recording = false;
1142 is_paused = false;
1144 buffer = audio_get_recording_buffer(&rec_buffer_size);
1146 /* Line align pcm_buffer 2^4=16 bytes */
1147 pcm_buffer = (unsigned char *)ALIGN_UP_P2((uintptr_t)buffer, 4);
1148 enc_buffer = pcm_buffer + ALIGN_UP_P2(PCM_NUM_CHUNKS*PCM_CHUNK_SIZE +
1149 PCM_MAX_FEED_SIZE, 2);
1150 /* Adjust available buffer for possible align advancement */
1151 rec_buffer_size -= pcm_buffer - buffer;
1153 pcm_init_recording();
1154 } /* pcmrec_init */
1156 /* PCMREC_CLOSE */
1157 static void pcmrec_close(void)
1159 dma_lock = true;
1160 pre_record_ticks = 0; /* Can't be prerecording any more */
1161 warnings = 0;
1162 pcm_close_recording();
1163 reset_hardware();
1164 audio_remove_encoder();
1165 } /* pcmrec_close */
1167 /* PCMREC_OPTIONS */
1168 static void pcmrec_set_recording_options(
1169 struct audio_recording_options *options)
1171 /* stop DMA transfer */
1172 dma_lock = true;
1173 pcm_stop_recording();
1175 rec_frequency = options->rec_frequency;
1176 rec_source = options->rec_source;
1177 num_channels = options->rec_channels == 1 ? 1 : 2;
1178 pre_record_ticks = options->rec_prerecord_time * HZ;
1179 enc_config = options->enc_config;
1180 enc_config.afmt = rec_format_afmt[enc_config.rec_format];
1182 #ifdef HAVE_SPDIF_IN
1183 if (rec_source == AUDIO_SRC_SPDIF)
1185 /* must measure SPDIF sample rate before configuring codecs */
1186 unsigned long sr = spdif_measure_frequency();
1187 /* round to master list for SPDIF rate */
1188 int index = round_value_to_list32(sr, audio_master_sampr_list,
1189 SAMPR_NUM_FREQ, false);
1190 sample_rate = audio_master_sampr_list[index];
1191 /* round to HW playback rates for monitoring */
1192 index = round_value_to_list32(sr, hw_freq_sampr,
1193 HW_NUM_FREQ, false);
1194 pcm_set_frequency(hw_freq_sampr[index]);
1195 /* encoders with a limited number of rates do their own rounding */
1197 else
1198 #endif
1200 /* set sample rate from frequency selection */
1201 sample_rate = rec_freq_sampr[rec_frequency];
1202 pcm_set_frequency(sample_rate);
1205 /* set monitoring */
1206 audio_set_output_source(rec_source);
1208 /* apply hardware setting to start monitoring now */
1209 pcm_apply_settings();
1211 queue_reply(&pcmrec_queue, 0); /* Release sender */
1213 if (audio_load_encoder(enc_config.afmt))
1215 /* start DMA transfer */
1216 dma_lock = pre_record_ticks == 0;
1217 pcm_record_data(pcm_rec_have_more, GET_PCM_CHUNK(dma_wr_pos),
1218 PCM_CHUNK_SIZE);
1220 else
1222 logf("set rec opt: enc load failed");
1223 errors |= PCMREC_E_LOAD_ENCODER;
1225 } /* pcmrec_set_recording_options */
1227 /* PCMREC_RECORD - start recording (not gapless)
1228 or split stream (gapless) */
1229 static void pcmrec_record(const char *filename)
1231 unsigned long pre_sample_ticks;
1232 int rd_start;
1233 unsigned long flags;
1234 int pre_index;
1236 logf("pcmrec_record: %s", filename);
1238 /* reset stats */
1239 num_rec_bytes = 0;
1240 num_rec_samples = 0;
1242 if (!is_recording)
1244 #if 0
1245 accum_rec_bytes = 0;
1246 accum_pcm_samples = 0;
1247 #endif
1248 warnings = 0; /* reset warnings */
1250 rd_start = enc_wr_index;
1251 pre_sample_ticks = 0;
1253 pcmrec_refresh_watermarks();
1255 if (pre_record_ticks)
1257 int i = rd_start;
1258 /* calculate number of available chunks */
1259 unsigned long avail_pre_chunks = (enc_wr_index - enc_rd_index +
1260 enc_num_chunks) % enc_num_chunks;
1261 /* overflow at 974 seconds of prerecording at 44.1kHz */
1262 unsigned long pre_record_sample_ticks =
1263 enc_sample_rate*pre_record_ticks;
1264 int pre_chunks = 0; /* Counter to limit prerecorded time to
1265 prevent flood state at outset */
1267 logf("pre-st: %ld", pre_record_sample_ticks);
1269 /* Get exact measure of recorded data as number of samples aren't
1270 nescessarily going to be the max for each chunk */
1271 for (; avail_pre_chunks-- > 0;)
1273 struct enc_chunk_hdr *chunk;
1274 unsigned long chunk_sample_ticks;
1276 DEC_ENC_INDEX(i);
1278 chunk = GET_ENC_CHUNK(i);
1280 /* must have data to be counted */
1281 if (chunk->enc_data == NULL)
1282 continue;
1284 chunk_sample_ticks = chunk->num_pcm*HZ;
1286 rd_start = i;
1287 pre_sample_ticks += chunk_sample_ticks;
1288 num_rec_bytes += chunk->enc_size;
1289 num_rec_samples += chunk->num_pcm;
1290 pre_chunks++;
1292 /* stop here if enough already */
1293 if (pre_chunks >= high_watermark ||
1294 pre_sample_ticks >= pre_record_sample_ticks)
1296 logf("pre-chks: %d", pre_chunks);
1297 break;
1301 #if 0
1302 accum_rec_bytes = num_rec_bytes;
1303 accum_pcm_samples = num_rec_samples;
1304 #endif
1307 enc_rd_index = rd_start;
1309 /* filename queue should be empty */
1310 if (!pcmrec_fnq_is_empty())
1312 logf("fnq: not empty!");
1313 pcmrec_fnq_set_empty();
1316 flags = CHUNKF_START_FILE;
1317 if (pre_sample_ticks > 0)
1318 flags |= CHUNKF_PRERECORD;
1320 pre_index = enc_rd_index;
1322 dma_lock = false;
1323 is_paused = false;
1324 is_recording = true;
1326 else
1328 /* already recording, just split the stream */
1329 logf("inserting split");
1330 flags = CHUNKF_START_FILE | CHUNKF_END_FILE;
1331 pre_index = 0;
1334 pcmrec_new_stream(filename, flags, pre_index);
1335 logf("pcmrec_record done");
1336 } /* pcmrec_record */
1338 /* PCMREC_STOP */
1339 static void pcmrec_stop(void)
1341 logf("pcmrec_stop");
1343 if (is_recording)
1345 dma_lock = true; /* lock dma write position */
1347 /* flush all available data first to avoid overflow while waiting
1348 for encoding to finish */
1349 pcmrec_flush(PCMREC_FLUSH_ALL);
1351 /* wait for encoder to finish remaining data */
1352 while (errors == 0 && !pcm_buffer_empty)
1353 yield();
1355 /* end stream at last data */
1356 pcmrec_new_stream(NULL, CHUNKF_END_FILE, 0);
1358 /* flush anything else encoder added */
1359 pcmrec_flush(PCMREC_FLUSH_ALL);
1361 /* remove any pending file start not yet processed - should be at
1362 most one at enc_wr_index */
1363 pcmrec_fnq_get_filename(NULL);
1364 /* encoder should abort any chunk it was in midst of processing */
1365 GET_ENC_CHUNK(enc_wr_index)->flags = CHUNKF_ABORT;
1367 /* filename queue should be empty */
1368 if (!pcmrec_fnq_is_empty())
1370 logf("fnq: not empty!");
1371 pcmrec_fnq_set_empty();
1374 /* be absolutely sure the file is closed */
1375 if (errors != 0)
1376 pcmrec_close_file(&rec_fdata.rec_file);
1377 rec_fdata.rec_file = -1;
1379 is_recording = false;
1380 is_paused = false;
1381 dma_lock = pre_record_ticks == 0;
1383 else
1385 logf("not recording");
1388 logf("pcmrec_stop done");
1389 } /* pcmrec_stop */
1391 /* PCMREC_PAUSE */
1392 static void pcmrec_pause(void)
1394 logf("pcmrec_pause");
1396 if (!is_recording)
1398 logf("not recording");
1400 else if (is_paused)
1402 logf("already paused");
1404 else
1406 dma_lock = true;
1407 is_paused = true;
1410 logf("pcmrec_pause done");
1411 } /* pcmrec_pause */
1413 /* PCMREC_RESUME */
1414 static void pcmrec_resume(void)
1416 logf("pcmrec_resume");
1418 if (!is_recording)
1420 logf("not recording");
1422 else if (!is_paused)
1424 logf("not paused");
1426 else
1428 is_paused = false;
1429 is_recording = true;
1430 dma_lock = false;
1433 logf("pcmrec_resume done");
1434 } /* pcmrec_resume */
1436 static void pcmrec_thread(void) __attribute__((noreturn));
1437 static void pcmrec_thread(void)
1439 struct queue_event ev;
1441 logf("thread pcmrec start");
1443 while(1)
1445 if (is_recording)
1447 /* Poll periodically to flush data */
1448 queue_wait_w_tmo(&pcmrec_queue, &ev, HZ/5);
1450 if (ev.id == SYS_TIMEOUT)
1452 /* Messages that interrupt this will complete it */
1453 pcmrec_flush(PCMREC_FLUSH_IF_HIGH |
1454 PCMREC_FLUSH_INTERRUPTABLE);
1455 continue;
1458 else
1460 /* Not doing anything - sit and wait for commands */
1461 queue_wait(&pcmrec_queue, &ev);
1464 switch (ev.id)
1466 case PCMREC_INIT:
1467 pcmrec_init();
1468 break;
1470 case PCMREC_CLOSE:
1471 pcmrec_close();
1472 break;
1474 case PCMREC_OPTIONS:
1475 pcmrec_set_recording_options(
1476 (struct audio_recording_options *)ev.data);
1477 break;
1479 case PCMREC_RECORD:
1480 clear_flush_interrupt();
1481 pcmrec_record((const char *)ev.data);
1482 break;
1484 case PCMREC_STOP:
1485 clear_flush_interrupt();
1486 pcmrec_stop();
1487 break;
1489 case PCMREC_PAUSE:
1490 clear_flush_interrupt();
1491 pcmrec_pause();
1492 break;
1494 case PCMREC_RESUME:
1495 pcmrec_resume();
1496 break;
1497 #if 0
1498 case PCMREC_FLUSH_NUM:
1499 pcmrec_flush((unsigned)ev.data);
1500 break;
1501 #endif
1502 case SYS_USB_CONNECTED:
1503 if (is_recording)
1504 break;
1505 pcmrec_close();
1506 usb_acknowledge(SYS_USB_CONNECTED_ACK);
1507 usb_wait_for_disconnect(&pcmrec_queue);
1508 flush_interrupts = 0;
1509 break;
1510 } /* end switch */
1511 } /* end while */
1512 } /* pcmrec_thread */
1514 /****************************************************************************/
1515 /* */
1516 /* following functions will be called by the encoder codec */
1517 /* in a free-threaded manner */
1518 /* */
1519 /****************************************************************************/
1521 /* pass the encoder settings to the encoder */
1522 void enc_get_inputs(struct enc_inputs *inputs)
1524 inputs->sample_rate = sample_rate;
1525 inputs->num_channels = num_channels;
1526 inputs->config = &enc_config;
1527 } /* enc_get_inputs */
1529 /* set the encoder dimensions (called by encoder codec at initialization and
1530 termination) */
1531 void enc_set_parameters(struct enc_parameters *params)
1533 size_t bufsize, resbytes;
1535 logf("enc_set_parameters");
1537 if (!params)
1539 logf("reset");
1540 /* Encoder is terminating */
1541 memset(&enc_config, 0, sizeof (enc_config));
1542 enc_sample_rate = 0;
1543 cancel_cpu_boost(); /* Make sure no boost remains */
1544 return;
1547 enc_sample_rate = params->enc_sample_rate;
1548 logf("enc sampr:%lu", enc_sample_rate);
1550 pcm_rd_pos = dma_wr_pos;
1551 pcm_enc_pos = pcm_rd_pos;
1553 enc_config.afmt = params->afmt;
1554 /* addition of the header is always implied - chunk size 4-byte aligned */
1555 enc_chunk_size =
1556 ALIGN_UP_P2(ENC_CHUNK_HDR_SIZE + params->chunk_size, 2);
1557 enc_events_callback = params->events_callback;
1559 logf("chunk size:%lu", enc_chunk_size);
1561 /*** Configure the buffers ***/
1563 /* Layout of recording buffer:
1564 * [ax] = possible alignment x multiple
1565 * [sx] = possible size alignment of x multiple
1566 * |[a16]|[s4]:PCM Buffer+PCM Guard|[s4 each]:Encoder Chunks|->
1567 * |[[s4]:Reserved Bytes]|Filename Queue->|[space]|
1569 resbytes = ALIGN_UP_P2(params->reserve_bytes, 2);
1570 logf("resbytes:%lu", resbytes);
1572 bufsize = rec_buffer_size - (enc_buffer - pcm_buffer) -
1573 resbytes - FNQ_MIN_NUM_PATHS*MAX_PATH
1574 #ifdef DEBUG
1575 - sizeof (*wrap_id_p)
1576 #endif
1579 enc_num_chunks = bufsize / enc_chunk_size;
1580 logf("num chunks:%d", enc_num_chunks);
1582 /* get real amount used by encoder chunks */
1583 bufsize = enc_num_chunks*enc_chunk_size;
1584 logf("enc size:%lu", bufsize);
1586 #ifdef DEBUG
1587 /* add magic at wraparound for spillover checks */
1588 wrap_id_p = SKIPBYTES((unsigned long *)enc_buffer, bufsize);
1589 bufsize += sizeof (*wrap_id_p);
1590 *wrap_id_p = ENC_CHUNK_MAGIC;
1591 #endif
1593 /** set OUT parameters **/
1594 params->enc_buffer = enc_buffer;
1595 params->buf_chunk_size = enc_chunk_size;
1596 params->num_chunks = enc_num_chunks;
1598 /* calculate reserve buffer start and return pointer to encoder */
1599 params->reserve_buffer = NULL;
1600 if (resbytes > 0)
1602 params->reserve_buffer = enc_buffer + bufsize;
1603 bufsize += resbytes;
1606 /* place filename queue at end of buffer using up whatever remains */
1607 fnq_rd_pos = 0; /* reset */
1608 fnq_wr_pos = 0; /* reset */
1609 fn_queue = enc_buffer + bufsize;
1610 fnq_size = pcm_buffer + rec_buffer_size - fn_queue;
1611 fnq_size /= MAX_PATH;
1612 if (fnq_size > FNQ_MAX_NUM_PATHS)
1613 fnq_size = FNQ_MAX_NUM_PATHS;
1614 fnq_size *= MAX_PATH;
1615 logf("fnq files:%ld", fnq_size / MAX_PATH);
1617 #if defined(DEBUG)
1618 logf("ab :%08lX", (uintptr_t)audiobuf);
1619 logf("pcm:%08lX", (uintptr_t)pcm_buffer);
1620 logf("enc:%08lX", (uintptr_t)enc_buffer);
1621 logf("res:%08lX", (uintptr_t)params->reserve_buffer);
1622 logf("wip:%08lX", (uintptr_t)wrap_id_p);
1623 logf("fnq:%08lX", (uintptr_t)fn_queue);
1624 logf("end:%08lX", (uintptr_t)fn_queue + fnq_size);
1625 logf("abe:%08lX", (uintptr_t)audiobufend);
1626 #endif
1628 /* init all chunk headers and reset indexes */
1629 enc_rd_index = 0;
1630 for (enc_wr_index = enc_num_chunks; enc_wr_index > 0; )
1632 struct enc_chunk_hdr *chunk = GET_ENC_CHUNK(--enc_wr_index);
1633 #ifdef DEBUG
1634 chunk->id = ENC_CHUNK_MAGIC;
1635 #endif
1636 chunk->flags = 0;
1639 logf("enc_set_parameters done");
1640 } /* enc_set_parameters */
1642 /* return encoder chunk at current write position -
1643 NOTE: can be called by pcmrec thread when splitting streams */
1644 struct enc_chunk_hdr * enc_get_chunk(void)
1646 struct enc_chunk_hdr *chunk = GET_ENC_CHUNK(enc_wr_index);
1648 #ifdef DEBUG
1649 if (chunk->id != ENC_CHUNK_MAGIC || *wrap_id_p != ENC_CHUNK_MAGIC)
1651 errors |= PCMREC_E_CHUNK_OVF;
1652 logf("finish chk ovf: %d", enc_wr_index);
1654 #endif
1656 chunk->flags &= CHUNKF_START_FILE;
1658 if (!is_recording)
1659 chunk->flags |= CHUNKF_PRERECORD;
1661 return chunk;
1662 } /* enc_get_chunk */
1664 /* releases the current chunk into the available chunks -
1665 NOTE: can be called by pcmrec thread when splitting streams */
1666 void enc_finish_chunk(void)
1668 struct enc_chunk_hdr *chunk = GET_ENC_CHUNK(enc_wr_index);
1670 if ((long)chunk->flags < 0)
1672 /* encoder set error flag */
1673 errors |= PCMREC_E_ENCODER;
1674 logf("finish chk enc error");
1677 /* advance enc_wr_index to the next encoder chunk */
1678 INC_ENC_INDEX(enc_wr_index);
1680 if (enc_rd_index != enc_wr_index)
1682 num_rec_bytes += chunk->enc_size;
1683 num_rec_samples += chunk->num_pcm;
1684 #if 0
1685 accum_rec_bytes += chunk->enc_size;
1686 accum_pcm_samples += chunk->num_pcm;
1687 #endif
1689 else if (is_recording) /* buffer full */
1691 /* keep current position and put up warning flag */
1692 warnings |= PCMREC_W_ENC_BUFFER_OVF;
1693 logf("enc_buffer ovf");
1694 DEC_ENC_INDEX(enc_wr_index);
1695 if (pcmrec_context)
1697 /* if stream splitting, keep this out of circulation and
1698 flush a small number, then readd - cannot risk losing
1699 stream markers */
1700 logf("mini flush");
1701 pcmrec_flush(PCMREC_FLUSH_MINI);
1702 INC_ENC_INDEX(enc_wr_index);
1705 else
1707 /* advance enc_rd_index for prerecording */
1708 INC_ENC_INDEX(enc_rd_index);
1710 } /* enc_finish_chunk */
1712 /* passes a pointer to next chunk of unprocessed wav data */
1713 /* TODO: this really should give the actual size returned */
1714 unsigned char * enc_get_pcm_data(size_t size)
1716 int wp = dma_wr_pos;
1717 size_t avail = (wp - pcm_rd_pos) & PCM_CHUNK_MASK;
1719 /* limit the requested pcm data size */
1720 if (size > PCM_MAX_FEED_SIZE)
1721 size = PCM_MAX_FEED_SIZE;
1723 if (avail >= size)
1725 unsigned char *ptr = pcm_buffer + pcm_rd_pos;
1726 int next_pos = (pcm_rd_pos + size) & PCM_CHUNK_MASK;
1728 pcm_enc_pos = pcm_rd_pos;
1729 pcm_rd_pos = next_pos;
1731 /* ptr must point to continous data at wraparound position */
1732 if ((size_t)pcm_rd_pos < size)
1734 memcpy(pcm_buffer + PCM_NUM_CHUNKS*PCM_CHUNK_SIZE,
1735 pcm_buffer, pcm_rd_pos);
1738 if (avail >= (sample_rate << 2))
1740 /* Filling up - boost codec */
1741 trigger_cpu_boost();
1744 pcm_buffer_empty = false;
1745 return ptr;
1748 /* not enough data available - encoder should idle */
1749 pcm_buffer_empty = true;
1751 cancel_cpu_boost();
1753 /* Sleep long enough to allow one frame on average */
1754 sleep(0);
1756 return NULL;
1757 } /* enc_get_pcm_data */
1759 /* puts some pcm data back in the queue */
1760 size_t enc_unget_pcm_data(size_t size)
1762 int wp = dma_wr_pos;
1763 size_t old_avail = ((pcm_rd_pos - wp) & PCM_CHUNK_MASK) -
1764 2*PCM_CHUNK_SIZE;
1766 /* allow one interrupt to occur during this call and not have the
1767 new read position inside the DMA destination chunk */
1768 if ((ssize_t)old_avail > 0)
1770 /* limit size to amount of old data remaining */
1771 if (size > old_avail)
1772 size = old_avail;
1774 pcm_enc_pos = (pcm_rd_pos - size) & PCM_CHUNK_MASK;
1775 pcm_rd_pos = pcm_enc_pos;
1777 return size;
1780 return 0;
1781 } /* enc_unget_pcm_data */