@@ -543,16 +543,6 @@ void Application::Start() {
543543
544544 audio_processor_->Initialize (codec);
545545 audio_processor_->OnOutput ([this ](std::vector<int16_t >&& data) {
546- {
547- std::lock_guard<std::mutex> lock (mutex_);
548- // We do not have a send queue yet, but all packets are sent by the main task
549- // so we use the main task queue to limit the number of packets
550- if (main_tasks_.size () > MAX_AUDIO_PACKETS_IN_QUEUE) {
551- ESP_LOGW (TAG, " Too many main tasks = %u, skip sending audio..." , main_tasks_.size ());
552- return ;
553- }
554- }
555-
556546 background_task_->Schedule ([this , data = std::move (data)]() mutable {
557547 opus_encoder_->Encode (std::move (data), [this ](std::vector<uint8_t >&& opus) {
558548 AudioStreamPacket packet;
@@ -573,9 +563,13 @@ void Application::Start() {
573563 }
574564 }
575565#endif
576- Schedule ([this , packet = std::move (packet)]() {
577- protocol_->SendAudio (packet);
578- });
566+ std::lock_guard<std::mutex> lock (mutex_);
567+ if (audio_send_queue_.size () >= MAX_AUDIO_PACKETS_IN_QUEUE) {
568+ ESP_LOGW (TAG, " Too many audio packets in queue, drop the oldest packet" );
569+ audio_send_queue_.pop_front ();
570+ }
571+ audio_send_queue_.emplace_back (std::move (packet));
572+ xEventGroupSetBits (event_group_, SEND_AUDIO_EVENT);
579573 });
580574 });
581575 });
@@ -686,11 +680,22 @@ void Application::Schedule(std::function<void()> callback) {
686680// they should use Schedule to call this function
687681void Application::MainEventLoop () {
688682 while (true ) {
689- auto bits = xEventGroupWaitBits (event_group_, SCHEDULE_EVENT, pdTRUE, pdFALSE, portMAX_DELAY);
683+ auto bits = xEventGroupWaitBits (event_group_, SCHEDULE_EVENT | SEND_AUDIO_EVENT, pdTRUE, pdFALSE, portMAX_DELAY);
684+
685+ if (bits & SEND_AUDIO_EVENT) {
686+ std::unique_lock<std::mutex> lock (mutex_);
687+ auto packets = std::move (audio_send_queue_);
688+ lock.unlock ();
689+ for (auto & packet : packets) {
690+ if (!protocol_->SendAudio (packet)) {
691+ break ;
692+ }
693+ }
694+ }
690695
691696 if (bits & SCHEDULE_EVENT) {
692697 std::unique_lock<std::mutex> lock (mutex_);
693- std::list<std::function< void ()>> tasks = std::move (main_tasks_);
698+ auto tasks = std::move (main_tasks_);
694699 lock.unlock ();
695700 for (auto & task : tasks) {
696701 task ();
@@ -792,7 +797,7 @@ void Application::OnAudioInput() {
792797 }
793798 }
794799
795- vTaskDelay (pdMS_TO_TICKS (30 ));
800+ vTaskDelay (pdMS_TO_TICKS (OPUS_FRAME_DURATION_MS / 2 ));
796801}
797802
798803void Application::ReadAudio (std::vector<int16_t >& data, int sample_rate, int samples) {
0 commit comments