ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
analysis.h File Reference

Audio Analysis and Debugging Interface. More...

Go to the source code of this file.

Data Structures

struct  audio_analysis_stats_t
 Measurements used to diagnose sent or received audio quality. More...

Functions

int audio_analysis_init (void)
 Measurements used to diagnose sent or received audio quality.
void audio_analysis_track_sent_sample (float sample)
 Track sent audio sample.
void audio_analysis_track_sent_packet (size_t size)
 Track sent packet.
void audio_analysis_track_received_sample (float sample)
 Track received audio sample.
void audio_analysis_track_received_packet (size_t size)
 Track received packet.
const audio_analysis_stats_t * audio_analysis_get_sent_stats (void)
 Get sent audio statistics.
const audio_analysis_stats_t * audio_analysis_get_received_stats (void)
 Get received audio statistics.
void audio_analysis_print_report (void)
 Print audio analysis report.
void audio_analysis_set_aec3_metrics (double echo_return_loss, double echo_return_loss_enhancement, uint64_t delay_ns)
 Set AEC3 echo cancellation metrics.
void audio_analysis_destroy (void)
 Cleanup audio analysis.

Detailed Description

Audio Analysis and Debugging Interface.

Provides audio quality analysis for troubleshooting audio issues. Tracks sent and received audio characteristics for debugging.

Author
Zachary Fogg me@zf.nosp@m.o.gg
Date
2025

Definition in file analysis.h.

Function Documentation

◆ audio_analysis_destroy()

void audio_analysis_destroy ( void )

Cleanup audio analysis.

Definition at line 1056 of file analysis.c.

1056 {
1057 g_analysis_enabled = false;
1058
1059 // Close WAV files if they were open
1060 if (g_sent_wav) {
1061 wav_writer_close(g_sent_wav);
1062 g_sent_wav = NULL;
1063 log_info("Closed sent audio WAV file");
1064 }
1065 if (g_received_wav) {
1066 wav_writer_close(g_received_wav);
1067 g_received_wav = NULL;
1068 log_info("Closed received audio WAV file");
1069 }
1070}
#define log_info(...)
Log an INFO message.
Definition log/log.h:578
void wav_writer_close(wav_writer_t *writer)
Close WAV file and finalize header.
Definition wav_writer.c:127

References log_info, and wav_writer_close().

◆ audio_analysis_get_received_stats()

const audio_analysis_stats_t * audio_analysis_get_received_stats ( void )

Get received audio statistics.

Returns
Pointer to analysis stats (do not free)

Definition at line 544 of file analysis.c.

544 {
545 g_received_stats.dc_offset =
546 g_received_stats.total_samples
547 ? (float)(g_received_mean / g_received_stats.total_samples)
548 : 0.0f;
549 g_received_stats.rms_level = g_received_rms_sample_count
550 ? sqrtf(g_received_rms_accumulator /
551 (float)g_received_rms_sample_count)
552 : 0.0f;
553 return &g_received_stats;
554}

References audio_analysis_stats_t::dc_offset.

Referenced by audio_analysis_print_report().

◆ audio_analysis_get_sent_stats()

const audio_analysis_stats_t * audio_analysis_get_sent_stats ( void )

Get sent audio statistics.

Returns
Pointer to analysis stats (do not free)

Definition at line 532 of file analysis.c.

532 {
533 g_sent_stats.dc_offset =
534 g_sent_stats.total_samples
535 ? (float)(g_sent_mean / g_sent_stats.total_samples)
536 : 0.0f;
537 g_sent_stats.rms_level =
538 g_sent_rms_sample_count
539 ? sqrtf(g_sent_rms_accumulator / g_sent_rms_sample_count)
540 : 0.0f;
541 return &g_sent_stats;
542}

References audio_analysis_stats_t::dc_offset.

Referenced by audio_analysis_print_report().

◆ audio_analysis_init()

int audio_analysis_init ( void )

Measurements used to diagnose sent or received audio quality.

Initialize audio analysis

Returns
0 on success, negative on error

Definition at line 124 of file analysis.c.

124 {
125 SAFE_MEMSET(&g_sent_stats, sizeof(g_sent_stats), 0, sizeof(g_sent_stats));
126 SAFE_MEMSET(&g_received_stats, sizeof(g_received_stats), 0,
127 sizeof(g_received_stats));
128
129 g_sent_mean = g_received_mean = 0.0;
130 g_sent_rms_accumulator = g_received_rms_accumulator = 0.0f;
131 g_sent_rms_sample_count = g_received_rms_sample_count = 0;
132
133 // Reset stuttering/gap tracking
134 SAFE_MEMSET(g_received_gap_intervals_ms, sizeof(g_received_gap_intervals_ms),
135 0, sizeof(g_received_gap_intervals_ms));
136 g_received_gap_count = 0;
137 g_received_silence_start_sample = 0;
138 g_received_last_silence_end_sample = 0;
139 SAFE_MEMSET(g_received_packet_times_ns, sizeof(g_received_packet_times_ns), 0,
140 sizeof(g_received_packet_times_ns));
141 g_received_packet_times_count = 0;
142 SAFE_MEMSET(g_received_packet_sizes, sizeof(g_received_packet_sizes), 0,
143 sizeof(g_received_packet_sizes));
144
145 // Reset echo detection
146 SAFE_MEMSET(g_echo_buffer, sizeof(g_echo_buffer), 0, sizeof(g_echo_buffer));
147 g_echo_buffer_pos = 0;
148 g_echo_correlation_sample_count = 0;
149 for (int i = 0; i < ECHO_DELAY_COUNT; i++) {
150 g_echo_correlation_strength[i] = 0;
151 g_echo_match_count[i] = 0;
152 }
153 g_detected_echo_delay_ms = 0;
154
155 // Reset beep detection
156 SAFE_MEMSET(g_received_beep_window, sizeof(g_received_beep_window), 0,
157 sizeof(g_received_beep_window));
158 g_received_beep_window_idx = 0;
159 g_received_beep_events = 0;
160 g_received_tonal_samples = 0;
161 g_in_beep_burst = false;
162 g_beep_burst_samples = 0;
163
164 int64_t now_us = (int64_t)time_ns_to_us(time_get_ns());
165
166 g_sent_stats.timestamp_start_ns = now_us;
167 g_received_stats.timestamp_start_ns = now_us;
168
169 g_sent_last_sample = 0.0f;
170 g_received_last_sample = 0.0f;
171 g_sent_last_packet_time_us = now_us;
172 g_received_last_packet_time_us = now_us;
173
174 // Initialize WAV file dumping if enabled
175 if (wav_dump_enabled()) {
176 char tmp[PLATFORM_MAX_PATH_LENGTH];
177 if (platform_get_temp_dir(tmp, sizeof(tmp))) {
178 char path[PLATFORM_MAX_PATH_LENGTH];
179 safe_snprintf(path, sizeof(path), "%s/sent_audio.wav", tmp);
180 g_sent_wav = wav_writer_open(path, 48000, 1);
181 safe_snprintf(path, sizeof(path), "%s/received_audio.wav", tmp);
182 g_received_wav = wav_writer_open(path, 48000, 1);
183 }
184 if (g_sent_wav) {
185 log_info("Dumping sent audio to temp dir");
186 }
187 if (g_received_wav) {
188 log_info("Dumping received audio to temp dir");
189 }
190 }
191
192 g_analysis_enabled = true;
193 log_info("Audio analysis enabled");
194 return 0;
195}
#define ECHO_DELAY_COUNT
Definition analysis.c:96
#define SAFE_MEMSET(dest, dest_size, ch, count)
bool platform_get_temp_dir(char *temp_dir, size_t path_size)
Definition util.c:81
bool wav_dump_enabled(void)
Check if audio dumping is enabled via environment.
Definition wav_writer.c:153
wav_writer_t * wav_writer_open(const char *filepath, int sample_rate, int channels)
Open WAV file for writing.
Definition wav_writer.c:59

References ASCIICHAT_OK, ECHO_DELAY_COUNT, log_info, platform_get_temp_dir(), SAFE_MEMSET, wav_dump_enabled(), and wav_writer_open().

◆ audio_analysis_print_report()

void audio_analysis_print_report ( void )

Print audio analysis report.

Definition at line 567 of file analysis.c.

567 {
568 if (!g_analysis_enabled) {
569 return;
570 }
571
572 int64_t now_us = (int64_t)time_ns_to_us(time_get_ns());
573
574 g_sent_stats.timestamp_end_ns = now_us;
575 g_received_stats.timestamp_end_ns = now_us;
576
577 int64_t sent_duration_ms =
578 (g_sent_stats.timestamp_end_ns - g_sent_stats.timestamp_start_ns) /
580 int64_t recv_duration_ms = (g_received_stats.timestamp_end_ns -
581 g_received_stats.timestamp_start_ns) /
583
586 float sent_rms = sent->rms_level;
587 float recv_rms = received->rms_level;
588
589 log_plain("=================================================================="
590 "==============");
591 log_plain(" AUDIO ANALYSIS REPORT "
592 " ");
593 log_plain("=================================================================="
594 "==============");
595 log_plain("SENT AUDIO (Microphone Capture):");
596 log_plain(" Duration: %lld ms", (long long)sent_duration_ms);
597 log_plain(" Total Samples: %llu",
598 (unsigned long long)g_sent_stats.total_samples);
599 log_plain(" Peak Level: %.4f (should be < 1.0)",
600 g_sent_stats.peak_level);
601 log_plain(" RMS Level: %.4f (audio energy/loudness)",
602 sent_rms);
603 log_plain(" DC Offset: %.6f (signal mean)", sent->dc_offset);
604 log_plain(
605 " Clipping Events: %llu samples (%.2f%%)",
606 (unsigned long long)g_sent_stats.clipping_count,
607 g_sent_stats.total_samples > 0
608 ? (100.0 * g_sent_stats.clipping_count / g_sent_stats.total_samples)
609 : 0);
610 log_plain(
611 " Silent Samples: %llu samples (%.2f%%)",
612 (unsigned long long)g_sent_stats.silent_samples,
613 g_sent_stats.total_samples > 0
614 ? (100.0 * g_sent_stats.silent_samples / g_sent_stats.total_samples)
615 : 0);
616 if (g_sent_max_silence_burst > 0) {
617 log_plain(" Max Silence Burst: %llu samples",
618 (unsigned long long)g_sent_max_silence_burst);
619 }
620 log_plain(" Packets Sent: %u", g_sent_stats.packets_count);
621 log_plain(" Status: %s",
622 g_sent_stats.clipping_count > 0 ? "CLIPPING DETECTED!" : "OK");
623
624 log_plain("RECEIVED AUDIO (Playback):");
625 log_plain(" Duration: %lld ms", (long long)recv_duration_ms);
626 log_plain(" Total Samples: %llu",
627 (unsigned long long)g_received_stats.total_samples);
628 log_plain(" Peak Level: %.4f", g_received_stats.peak_level);
629 log_plain(" RMS Level: %.4f (audio energy/loudness)",
630 recv_rms);
631 log_plain(" DC Offset: %.6f (signal mean)",
632 received->dc_offset);
633 log_plain(" Clipping Events: %llu samples (%.2f%%)",
634 (unsigned long long)g_received_stats.clipping_count,
635 g_received_stats.total_samples > 0
636 ? (100.0 * g_received_stats.clipping_count /
637 g_received_stats.total_samples)
638 : 0);
639 log_plain(" Silent Samples: %llu samples (%.2f%%)",
640 (unsigned long long)g_received_stats.silent_samples,
641 g_received_stats.total_samples > 0
642 ? (100.0 * g_received_stats.silent_samples /
643 g_received_stats.total_samples)
644 : 0);
645 if (g_received_max_silence_burst > 0) {
646 log_plain(" Max Silence Burst: %llu samples",
647 (unsigned long long)g_received_max_silence_burst);
648 }
649 double low_energy_pct = g_received_stats.total_samples > 0
650 ? (100.0 * g_received_low_energy_samples /
651 g_received_stats.total_samples)
652 : 0;
653 log_plain(
654 " Very Quiet Samples: %llu samples (%.1f%%) [amplitude < 0.05]",
655 (unsigned long long)g_received_low_energy_samples, low_energy_pct);
656 log_plain(" Packets Received: %u", g_received_stats.packets_count);
657 log_plain(" Status: %s", g_received_stats.total_samples == 0
658 ? "NO AUDIO RECEIVED!"
659 : "Receiving");
660
661 log_plain("QUALITY METRICS (Scratchy/Distorted Audio Detection):");
662 log_plain("SENT:");
663 log_plain(" Jitter Events: %llu (rapid amplitude changes)",
664 (unsigned long long)g_sent_stats.jitter_count);
665 log_plain(" Discontinuities: %llu (packet arrival gaps > 100ms)",
666 (unsigned long long)g_sent_stats.discontinuity_count);
667 log_plain(" Max Gap Between Packets: %u ms (expected ~20ms per frame)",
668 g_sent_stats.max_gap_ns);
669
670 log_plain("RECEIVED:");
671 log_plain(" Jitter Events: %llu (rapid amplitude changes)",
672 (unsigned long long)g_received_stats.jitter_count);
673 log_plain(" Discontinuities: %llu (packet arrival gaps > 100ms)",
674 (unsigned long long)g_received_stats.discontinuity_count);
675 log_plain(" Max Gap Between Packets: %u ms (expected ~20ms per frame)",
676 g_received_stats.max_gap_ns);
677
678 // Beep/tone artifact detection
679 if (g_received_beep_events > 0 || g_received_tonal_samples > 0) {
680 double tonal_pct = g_received_stats.total_samples > 0
681 ? (100.0 * g_received_tonal_samples /
682 g_received_stats.total_samples)
683 : 0;
684 log_plain("BEEP/TONE ARTIFACTS:");
685 log_plain(" Beep Events: %llu (short tonal bursts < 500ms)",
686 (unsigned long long)g_received_beep_events);
687 log_plain(" Tonal Samples: %llu samples (%.1f%%) [consistent "
688 "frequency content]",
689 (unsigned long long)g_received_tonal_samples, tonal_pct);
690
691 if (g_received_beep_events > 10) {
692 log_plain(" 🔴 BEEPING DETECTED: %llu short tonal bursts - likely codec "
693 "artifacts or system sounds!",
694 (unsigned long long)g_received_beep_events);
695 log_plain(" Possible causes:");
696 log_plain(" - Opus codec producing tonal artifacts during "
697 "silence/transitions");
698 log_plain(" - Buffer underruns creating synthetic tones");
699 log_plain(" - AEC3 suppressor resonance");
700 log_plain(" - System notification sounds bleeding through");
701 } else if (g_received_beep_events > 3) {
702 log_plain(" ⚠️ Some beep artifacts detected (%llu events)",
703 (unsigned long long)g_received_beep_events);
704 }
705 }
706
707 log_plain("DIAGNOSTICS:");
708 if (g_sent_stats.peak_level == 0) {
709 log_plain(" No audio captured from microphone!");
710 }
711 if (g_received_stats.total_samples == 0) {
712 log_plain(" No audio received from server!");
713 } else if (g_received_stats.peak_level < 0.01f) {
714 log_plain(" ⚠️ Received audio is very quiet (peak < 0.01)");
715 }
716 if (g_sent_stats.clipping_count > 0) {
717 log_plain(" Microphone input is clipping - reduce microphone volume");
718 }
719
720 // Echo detection diagnostics
721 log_plain("ECHO DETECTION (Echo Cancellation Quality Check):");
722 if (g_echo_correlation_sample_count > 0 && g_sent_stats.total_samples > 0) {
723 uint64_t max_matches = 0;
724 int best_delay_idx = -1;
725
726 // Find which delay has the most matches (if any)
727 for (int i = 0; i < ECHO_DELAY_COUNT; i++) {
728 if (g_echo_match_count[i] > max_matches) {
729 max_matches = g_echo_match_count[i];
730 best_delay_idx = i;
731 }
732 }
733
734 double echo_threshold_pct =
735 5.0; // If > 5% of samples match at a delay, it's echo
736
737 if (best_delay_idx >= 0) {
738 double match_pct = (100.0 * g_echo_match_count[best_delay_idx]) /
739 g_echo_correlation_sample_count;
740 log_plain(" Echo correlation at different delays:");
741 for (int i = 0; i < ECHO_DELAY_COUNT; i++) {
742 double pct =
743 (100.0 * g_echo_match_count[i]) / g_echo_correlation_sample_count;
744 const char *status =
745 pct > echo_threshold_pct ? "⚠️ ECHO DETECTED" : "✓ OK";
746 log_plain(" %3u ms delay: %.1f%% match rate %s", g_echo_delays_ms[i],
747 pct, status);
748 }
749
750 if (match_pct > echo_threshold_pct) {
751 g_detected_echo_delay_ms = g_echo_delays_ms[best_delay_idx];
752 log_plain(
753 " 🔴 ECHO CANCELLATION NOT WORKING: Strong echo at %u ms delay!",
754 g_detected_echo_delay_ms);
755 log_plain(" Received audio contains %.1f%% samples matching sent "
756 "audio from %u ms ago",
757 match_pct, g_detected_echo_delay_ms);
758 } else {
759 log_plain(
760 " ✓ Echo cancellation working: No significant echo detected");
761 }
762 }
763 } else {
764 log_plain(" Insufficient data for echo detection (need both sent and "
765 "received audio)");
766 }
767
768 // AEC3 metrics from WebRTC (if available)
769 if (g_aec3_metrics_available) {
770 log_plain("AEC3 METRICS (from WebRTC GetMetrics()):");
771 log_plain(" Echo Return Loss (ERL): %.2f dB (how much echo is attenuated; "
772 ">10 dB is good)",
773 g_aec3_echo_return_loss);
774 log_plain(" Echo Return Loss Enhancement (ERLE): %.2f dB (residual echo "
775 "suppression)",
776 g_aec3_echo_return_loss_enhancement);
777 log_plain(" Estimated Echo Delay: %d ms", g_aec3_delay_ns);
778
779 if (g_aec3_echo_return_loss > 10.0) {
780 log_plain(" ✓ Good echo attenuation (ERL > 10 dB)");
781 } else if (g_aec3_echo_return_loss > 3.0) {
782 log_plain(" ⚠️ Moderate echo attenuation (3-10 dB)");
783 } else {
784 log_plain(" 🔴 Poor echo attenuation (ERL < 3 dB)");
785 }
786 }
787
788 // Audio quality diagnostics
789 if (recv_rms < 0.005f) {
790 log_plain(" ⚠️ CRITICAL: Received audio RMS is extremely low (%.6f) - "
791 "barely audible!",
792 recv_rms);
793 } else if (recv_rms < 0.02f) {
794 log_plain(" ⚠️ WARNING: Received audio RMS is low (%.6f) - may sound "
795 "quiet or muddy",
796 recv_rms);
797 }
798
799 // Silence analysis
800 double received_silence_pct = g_received_stats.total_samples > 0
801 ? (100.0 * g_received_stats.silent_samples /
802 g_received_stats.total_samples)
803 : 0;
804
805 if (received_silence_pct > 30.0) {
806 log_plain(
807 " ⚠️ SCRATCHY AUDIO DETECTED: Too much silence in received audio!");
808 log_plain(" - Silence: %.1f%% of received samples (should be < 10%%)",
809 received_silence_pct);
810 log_plain(" - Max silence burst: %llu samples",
811 (unsigned long long)g_received_max_silence_burst);
812 log_plain(
813 " - This creates jittery/choppy playback between audio bursts");
814 } else if (received_silence_pct > 15.0) {
815 log_plain(" ⚠️ WARNING: Moderate silence detected (%.1f%%)",
816 received_silence_pct);
817 }
818
819 // Sharp transition analysis (clicks/pops)
820 double sent_sharp_pct =
821 g_sent_transition_samples > 0
822 ? (100.0 * g_sent_sharp_transitions / g_sent_transition_samples)
823 : 0;
824 double recv_sharp_pct = g_received_transition_samples > 0
825 ? (100.0 * g_received_sharp_transitions /
826 g_received_transition_samples)
827 : 0;
828
829 // Zero crossing rate analysis (spectral content)
830 // Music: 1-5%, Speech: 5-15%, Static/Noise: 15-50%
831 double sent_zero_cross_pct =
832 g_sent_stats.total_samples > 0
833 ? (100.0 * g_sent_zero_crossings / g_sent_stats.total_samples)
834 : 0;
835 double recv_zero_cross_pct =
836 g_received_stats.total_samples > 0
837 ? (100.0 * g_received_zero_crossings / g_received_stats.total_samples)
838 : 0;
839
840 log_plain("WAVEFORM ANALYSIS (Is it clean music or corrupted/static?):");
841 log_plain("SENT AUDIO:");
842 log_plain(
843 " Zero crossings: %.2f%% of samples (music: 1-5%%, noise: 15-50%%)",
844 sent_zero_cross_pct);
845 log_plain(" Sharp transitions (clicks/pops): %.2f%% of samples",
846 sent_sharp_pct);
847 log_plain(" Clipping samples: %llu (%.3f%%)",
848 (unsigned long long)g_sent_clipping_samples,
849 g_sent_stats.total_samples > 0
850 ? (100.0 * g_sent_clipping_samples / g_sent_stats.total_samples)
851 : 0);
852
853 log_plain("RECEIVED AUDIO:");
854 log_plain(
855 " Zero crossings: %.2f%% of samples (music: 1-5%%, noise: 15-50%%)",
856 recv_zero_cross_pct);
857 log_plain(" Sharp transitions (clicks/pops): %.2f%% of samples",
858 recv_sharp_pct);
859 log_plain(" Clipping samples: %llu (%.3f%%)",
860 (unsigned long long)g_received_clipping_samples,
861 g_received_stats.total_samples > 0
862 ? (100.0 * g_received_clipping_samples /
863 g_received_stats.total_samples)
864 : 0);
865 log_plain(" Zero crossing increase: %.2f%% higher than sent (indicates "
866 "corruption)",
867 recv_zero_cross_pct - sent_zero_cross_pct);
868
869 // Musicality verdict
870 log_plain("SOUND QUALITY VERDICT:");
871 if (recv_zero_cross_pct > 10.0) {
872 log_plain(" ⚠️ SOUNDS LIKE STATIC/DISTORTED: Excessive zero crossings "
873 "(%.2f%%) = high frequency noise",
874 recv_zero_cross_pct);
875 log_plain(" Increase from sent: %.2f%% (waveform corruption detected)",
876 recv_zero_cross_pct - sent_zero_cross_pct);
877 log_plain(" Likely causes: Opus codec artifacts, jitter buffer issues, "
878 "or packet delivery gaps");
879 } else if (recv_zero_cross_pct - sent_zero_cross_pct > 3.0) {
880 log_plain(" ⚠️ SOUNDS CORRUPTED: Zero crossing rate increased by %.2f%% "
881 "(should be ±0.5%%)",
882 recv_zero_cross_pct - sent_zero_cross_pct);
883 log_plain(
884 " Indicates waveform distortion from network/processing artifacts");
885 } else if (recv_sharp_pct > 2.0) {
886 log_plain(" ⚠️ SOUNDS LIKE STATIC: High click/pop rate (%.2f%%) indicates "
887 "audio artifacts",
888 recv_sharp_pct);
889 log_plain(" Likely causes: Packet loss, jitter buffer issues, or frame "
890 "discontinuities");
891 } else if (g_received_clipping_samples >
892 (g_received_stats.total_samples / 1000)) {
893 log_plain(" ⚠️ SOUNDS DISTORTED: Significant clipping detected (%.3f%%)",
894 100.0 * g_received_clipping_samples /
895 g_received_stats.total_samples);
896 log_plain(" Likely causes: AGC too aggressive, gain too high, or codec "
897 "compression artifacts");
898 } else if (low_energy_pct > 50.0 && recv_rms < 0.05f) {
899 log_plain(
900 " ⚠️ SOUNDS MUDDY/QUIET: Over 50%% very quiet samples + low RMS");
901 log_plain(" Audio may sound unclear or like background noise rather "
902 "than music");
903 } else if (received_silence_pct > 10.0) {
904 log_plain(
905 " ⚠️ SOUNDS SCRATCHY: Excessive silence (%.1f%%) causes dropouts",
906 received_silence_pct);
907 } else if (recv_rms > 0.08f && recv_zero_cross_pct < 6.0 &&
908 recv_sharp_pct < 1.0 && g_received_clipping_samples == 0) {
909 log_plain(" ✓ SOUNDS LIKE MUSIC: Good RMS (%.4f), clean waveform (%.2f%% "
910 "zero crossings), minimal artifacts",
911 recv_rms, recv_zero_cross_pct);
912 log_plain(" Audio quality acceptable for communication");
913 } else {
914 log_plain(" ? BORDERLINE: Check specific metrics above");
915 }
916
917 // Low energy audio analysis
918 if (low_energy_pct > 50.0) {
919 log_plain(" ⚠️ WARNING: Over 50%% of received samples are very quiet (< "
920 "0.05 amplitude)");
921 log_plain(
922 " - This makes audio sound muddy, unclear, or hard to understand");
923 log_plain(" - Caused by: Mixing other clients' audio with your own at "
924 "wrong levels");
925 }
926
927 // Stuttering/periodic gap detection using packet inter-arrival times
928 if (g_received_packet_times_count >= 5) {
929 uint32_t inter_arrival_count = 0;
930 uint32_t min_interval_ms = 0xFFFFFFFF;
931 uint32_t max_interval_ms = 0;
932 uint64_t sum_intervals_ms = 0;
933 uint32_t intervals_around_50ms = 0; // Count intervals ~40-60ms
934
935 // Calculate inter-packet arrival times
936 for (uint32_t i = 1; i < g_received_packet_times_count; i++) {
937 uint64_t prev_ns = g_received_packet_times_ns[i - 1];
938 uint64_t curr_ns = g_received_packet_times_ns[i];
939
940 uint64_t gap_ns = time_elapsed_ns(prev_ns, curr_ns);
941 uint32_t gap_ms = (uint32_t)time_ns_to_ms(gap_ns);
942
943 (void)gap_ms;
944 inter_arrival_count++;
945 if (gap_ms < min_interval_ms)
946 min_interval_ms = gap_ms;
947 if (gap_ms > max_interval_ms)
948 max_interval_ms = gap_ms;
949 sum_intervals_ms += gap_ms;
950
951 // Check if interval is ~50ms (within 15ms tolerance for network jitter)
952 if (gap_ms >= 35 && gap_ms <= 70) {
953 intervals_around_50ms++;
954 }
955 }
956
957 uint32_t avg_interval_ms =
958 (uint32_t)(sum_intervals_ms / inter_arrival_count);
959 uint32_t interval_consistency =
960 (intervals_around_50ms * 100) / inter_arrival_count;
961
962 // Calculate how much audio is in each packet
963 // Total decoded samples / number of packets = average samples per packet
964 // At 48kHz, 960 samples = 1 Opus frame = 20ms
965 double avg_samples_per_packet =
966 g_received_stats.total_samples > 0
967 ? (double)g_received_stats.total_samples / inter_arrival_count
968 : 0;
969 double frames_per_packet =
970 avg_samples_per_packet / 960.0; // 960 samples = 1 frame @ 48kHz
971 double ms_audio_per_packet = frames_per_packet * 20.0; // 20ms per frame
972
973 // Detect if stuttering is periodic (consistent ~50ms intervals)
974 if (intervals_around_50ms >= (inter_arrival_count * 2 / 3)) {
975 // More than 66% of packets are ~50ms apart - clear periodic stuttering
976 log_plain(" 🔴 PERIODIC STUTTERING DETECTED: Server sends packets every "
977 "~%u ms (should be ~20ms)!",
978 avg_interval_ms);
979 log_plain(" - Packet inter-arrival: %u-%u ms (avg: %u ms)",
980 min_interval_ms, max_interval_ms, avg_interval_ms);
981 log_plain(" - %u/%u packets (~%u%%) are ~50ms apart (CLEAR STUTTERING "
982 "PATTERN)",
983 intervals_around_50ms, inter_arrival_count,
984 interval_consistency);
985
986 log_plain(" - PACKET ANALYSIS:");
987 log_plain(" - Total audio samples: %llu over %u packets",
988 (unsigned long long)g_received_stats.total_samples,
989 inter_arrival_count);
990 log_plain(
991 " - Avg samples per packet: %.0f (= %.2f Opus frames = %.1f ms)",
992 avg_samples_per_packet, frames_per_packet, ms_audio_per_packet);
993
994 if (frames_per_packet < 1.5) {
995 log_plain(" - ❌ PROBLEM: Each packet contains < 1.5 frames "
996 "(should be 2-3 frames!)");
997 log_plain(" - With only %.1f frames per packet arriving every %u "
998 "ms, there are gaps between chunks",
999 frames_per_packet, avg_interval_ms);
1000 log_plain(" - Audio plays for ~%.0f ms, then %u ms gap, then "
1001 "plays again",
1002 ms_audio_per_packet,
1003 avg_interval_ms - (uint32_t)ms_audio_per_packet);
1004 } else if (frames_per_packet > 2.5) {
1005 log_plain(" - ✓ Packets contain %.1f frames (~%.0f ms audio each)",
1006 frames_per_packet, ms_audio_per_packet);
1007 log_plain(
1008 " - Should play smoothly if jitter buffer is large enough");
1009 log_plain(" - If still stuttering, issue is jitter buffer depth "
1010 "or timing precision");
1011 } else {
1012 log_plain(" - Packets contain %.1f frames (~%.0f ms)",
1013 frames_per_packet, ms_audio_per_packet);
1014 log_plain(" - Borderline: buffer needs to hold %.0f ms to bridge "
1015 "%.u ms gap",
1016 ms_audio_per_packet,
1017 avg_interval_ms - (uint32_t)ms_audio_per_packet);
1018 }
1019 } else if (avg_interval_ms > 30) {
1020 log_plain(" ⚠️ AUDIO DELIVERY INCONSISTENCY: Server packets arrive "
1021 "every ~%u ms (expected ~20ms)",
1022 avg_interval_ms);
1023 log_plain(" - Interval range: %u-%u ms", min_interval_ms,
1024 max_interval_ms);
1025 log_plain(" - This causes dropouts and buffering issues");
1026 }
1027 }
1028
1029 // Packet delivery gaps
1030 if (g_received_stats.max_gap_ns > 40) {
1031 log_plain(" ⚠️ DISTORTION DETECTED: Packet delivery gaps too large!");
1032 log_plain(" - Max gap: %u ms (should be ~20ms for smooth audio)",
1033 g_received_stats.max_gap_ns);
1034 if (g_received_stats.max_gap_ns > 80) {
1035 log_plain(
1036 " - SEVERE: Gaps > 80ms cause severe distortion and dropouts");
1037 } else if (g_received_stats.max_gap_ns > 50) {
1038 log_plain(" - Gaps > 50ms cause noticeable distortion");
1039 }
1040 }
1041 if (g_received_stats.discontinuity_count > 0) {
1042 log_plain(" Packet delivery discontinuities: %llu gaps > 100ms detected",
1043 (unsigned long long)g_received_stats.discontinuity_count);
1044 }
1045 if (g_received_stats.jitter_count > (g_received_stats.total_samples / 100)) {
1046 log_plain(" High jitter detected: > 1%% of samples have rapid amplitude "
1047 "changes");
1048 log_plain(
1049 " - May indicate buffer underruns from sparse packet delivery");
1050 }
1051
1052 log_plain("=================================================================="
1053 "==============");
1054}
const audio_analysis_stats_t * audio_analysis_get_sent_stats(void)
Get sent audio statistics.
Definition analysis.c:532
const audio_analysis_stats_t * audio_analysis_get_received_stats(void)
Get received audio statistics.
Definition analysis.c:544
unsigned int uint32_t
unsigned long long uint64_t
#define log_plain(...)
Plain logging - writes to both log file and stderr without timestamps or log levels.
Definition log/log.h:635
#define NS_PER_MS_INT
Definition time.h:172
uint64_t time_elapsed_ns(uint64_t start_ns, uint64_t end_ns)
Calculate elapsed time with wraparound safety.
Definition time.c:126
Measurements used to diagnose sent or received audio quality.
Definition analysis.h:31

References audio_analysis_get_received_stats(), audio_analysis_get_sent_stats(), audio_analysis_stats_t::dc_offset, ECHO_DELAY_COUNT, log_plain, NS_PER_MS_INT, audio_analysis_stats_t::rms_level, and time_elapsed_ns().

◆ audio_analysis_set_aec3_metrics()

void audio_analysis_set_aec3_metrics ( double echo_return_loss,
double echo_return_loss_enhancement,
uint64_t delay_ns )

Set AEC3 echo cancellation metrics.

Parameters
echo_return_lossEcho return loss (dB) - how much echo is attenuated
echo_return_loss_enhancementAdditional echo suppression (dB)
delay_nsEstimated echo delay in nanoseconds

Definition at line 556 of file analysis.c.

558 {
559 // Store AEC3 metrics for reporting
560 // These come from WebRTC EchoControl::GetMetrics() call
561 g_aec3_echo_return_loss = echo_return_loss;
562 g_aec3_echo_return_loss_enhancement = echo_return_loss_enhancement;
563 g_aec3_delay_ns = delay_ns > INT_MAX ? INT_MAX : (int)delay_ns;
564 g_aec3_metrics_available = true;
565}

Referenced by client_audio_pipeline_process_duplex().

◆ audio_analysis_track_received_packet()

void audio_analysis_track_received_packet ( size_t size)

Track received packet.

Parameters
sizePacket size in bytes

Definition at line 499 of file analysis.c.

499 {
500 (void)size; // Unused parameter - reserved for future per-packet analysis
501 if (!g_analysis_enabled)
502 return;
503
504 uint64_t now_ns = time_get_ns();
505 int64_t now_us = (int64_t)time_ns_to_us(now_ns);
506
507 // Track packet timing for stuttering detection
508 if (g_received_packet_times_count < MAX_PACKET_SAMPLES) {
509 g_received_packet_times_ns[g_received_packet_times_count++] = now_ns;
510 }
511
512 // Detect gaps between consecutive packets (discontinuity)
513 if (g_received_stats.packets_count > 0) {
514 int64_t gap_us = now_us - g_received_last_packet_time_us;
515 int32_t gap_ms = (int32_t)(gap_us / 1000);
516
517 // Expected: ~20ms per Opus frame, flag if gap > 100ms
518 if (gap_ms > 100) {
519 g_received_stats.discontinuity_count++;
520 }
521
522 // Track max gap
523 if (gap_ms > (int32_t)g_received_stats.max_gap_ns) {
524 g_received_stats.max_gap_ns = (uint32_t)gap_ms;
525 }
526 }
527
528 g_received_last_packet_time_us = now_us;
529 g_received_stats.packets_count++;
530}
#define MAX_PACKET_SAMPLES
Definition analysis.c:80

References MAX_PACKET_SAMPLES.

◆ audio_analysis_track_received_sample()

void audio_analysis_track_received_sample ( float sample)

Track received audio sample.

Parameters
sampleAudio sample value

Definition at line 298 of file analysis.c.

298 {
299 if (!g_analysis_enabled)
300 return;
301
302 g_received_stats.total_samples++;
303
304 // Track peak level
305 float abs_sample = fabsf(sample);
306 if (abs_sample > g_received_stats.peak_level) {
307 g_received_stats.peak_level = abs_sample;
308 }
309
310 // Track clipping (samples > 1.0) - indicates distortion
311 if (abs_sample > 1.0f) {
312 g_received_stats.clipping_count++;
313 g_received_clipping_samples++;
314 }
315
316 // Detect sharp transitions (sudden amplitude jumps > 0.3) - indicates
317 // clicks/pops/artifacts
318 float amp_change = fabsf(sample - g_received_last_sample);
319 if (amp_change > 0.3f) {
320 g_received_sharp_transitions++;
321 }
322 g_received_transition_samples++;
323
324 // Accumulate for mean calculation
325 g_received_mean += sample;
326
327 // Detect zero crossings (waveform crossing zero) - indicates spectral content
328 // Use file-scope static variable for prev sample tracking
329 // (This function is called from the protocol reception thread, separate from
330 // the audio capture thread, so using distinct static variables is safe)
331 static float s_received_prev_sample_for_zero_crossing = 0.0f;
332 if ((s_received_prev_sample_for_zero_crossing > 0 && sample < 0) ||
333 (s_received_prev_sample_for_zero_crossing < 0 && sample > 0)) {
334 g_received_zero_crossings++;
335 }
336 s_received_prev_sample_for_zero_crossing = sample;
337
338 // Track silence and low-energy audio
339 if (abs_sample < 0.001f) {
340 g_received_stats.silent_samples++;
341 g_received_silence_burst++;
342
343 // Track when silence started
344 if (g_received_silence_burst == 1) {
345 g_received_silence_start_sample = g_received_stats.total_samples;
346 }
347 } else {
348 // Silence ended - track gap interval and max burst length
349 if (g_received_silence_burst > 0) {
350 // Calculate time gap between end of last silence and start of this one
351 if (g_received_last_silence_end_sample > 0) {
352 uint64_t samples_between = g_received_silence_start_sample -
353 g_received_last_silence_end_sample;
354 uint32_t ms_between =
355 (uint32_t)(samples_between * 1000 /
356 48000); // Convert samples to ms at 48kHz
357
358 // Track the gap interval if we have room
359 if (g_received_gap_count < MAX_GAP_SAMPLES) {
360 g_received_gap_intervals_ms[g_received_gap_count++] = ms_between;
361 }
362 }
363
364 g_received_last_silence_end_sample = g_received_stats.total_samples;
365
366 // Track max burst length
367 if (g_received_silence_burst > g_received_max_silence_burst) {
368 g_received_max_silence_burst = g_received_silence_burst;
369 }
370 }
371 g_received_silence_burst = 0;
372 }
373
374 // Track very quiet audio (< 0.05 amplitude) which contributes to muddy/quiet
375 // perception
376 if (abs_sample < 0.05f) {
377 g_received_low_energy_samples++;
378 }
379
380 // Detect jitter: rapid amplitude changes > 0.5 between consecutive samples
381 float delta = fabsf(sample - g_received_last_sample);
382 if (delta > 0.5f) {
383 g_received_stats.jitter_count++;
384 }
385 g_received_last_sample = sample;
386
387 // Accumulate for RMS calculation
388 g_received_rms_accumulator += sample * sample;
389 g_received_rms_sample_count++;
390
391 // Echo detection: check if received sample matches sent sample from N ms ago
392 // This detects if echo cancellation is working (it shouldn't find matches)
393 if (g_echo_correlation_sample_count < 500000) { // Limit to first ~10 seconds
394 for (int delay_idx = 0; delay_idx < ECHO_DELAY_COUNT; delay_idx++) {
395 // Calculate sample delay: delay_ms * (sample_rate / 1000)
396 uint32_t delay_samples = (g_echo_delays_ms[delay_idx] * 48000) / 1000;
397
398 // Get sent sample from that delay ago (from circular buffer)
399 uint64_t sent_pos;
400 if (g_echo_buffer_pos >= delay_samples) {
401 sent_pos = g_echo_buffer_pos - delay_samples;
402 } else {
403 sent_pos = (g_echo_buffer_pos + ECHO_BUFFER_SIZE) - delay_samples;
404 }
405
406 float sent_sample = g_echo_buffer[sent_pos];
407
408 // Check if samples match (correlation threshold = 0.1)
409 float diff = fabsf(sample - sent_sample);
410 if (diff < 0.1f &&
411 fabsf(sent_sample) > 0.01f) { // Only count if sent is not silence
412 g_echo_match_count[delay_idx]++;
413 g_echo_correlation_strength[delay_idx] +=
414 (0.1f - diff); // Accumulate strength
415 }
416 }
417 g_echo_correlation_sample_count++;
418 }
419
420 // Beep/tone artifact detection
421 // Store sample in sliding window for frequency analysis
422 g_received_beep_window[g_received_beep_window_idx] = sample;
423 g_received_beep_window_idx =
424 (g_received_beep_window_idx + 1) % BEEP_WINDOW_SIZE;
425
426 // Analyze window every 10ms (480 samples at 48kHz)
427 if (g_received_beep_window_idx == 0 &&
428 g_received_stats.total_samples > BEEP_WINDOW_SIZE) {
429 // Calculate zero-crossing rate in this window
430 int zero_crossings = 0;
431 float min_amp = 1.0f, max_amp = 0.0f;
432 float sum_amp = 0.0f;
433 float prev = g_received_beep_window[0];
434
435 for (int i = 1; i < BEEP_WINDOW_SIZE; i++) {
436 float curr = g_received_beep_window[i];
437 float abs_curr = fabsf(curr);
438
439 // Track amplitude range
440 if (abs_curr > max_amp)
441 max_amp = abs_curr;
442 if (abs_curr < min_amp)
443 min_amp = abs_curr;
444 sum_amp += abs_curr;
445
446 // Count zero crossings
447 if ((prev > 0 && curr < 0) || (prev < 0 && curr > 0)) {
448 zero_crossings++;
449 }
450 prev = curr;
451 }
452
453 float avg_amp = sum_amp / BEEP_WINDOW_SIZE;
454 float amp_range = max_amp - min_amp;
455
456 // A beep/tone has:
457 // 1. High zero-crossing rate (>20 per 10ms = >2000Hz equivalent, or 5-20 =
458 // 500-2000Hz)
459 // 2. Consistent amplitude (range/avg < 0.5 means sine-wave like)
460 // 3. Non-trivial amplitude (avg > 0.02)
461 bool is_tonal =
462 (zero_crossings >= 5 && zero_crossings <= 100) && // 500Hz-10kHz range
463 (avg_amp > 0.02f) && // Not silence
464 (amp_range < avg_amp * 1.5f); // Relatively consistent amplitude
465
466 if (is_tonal) {
467 g_received_tonal_samples += BEEP_WINDOW_SIZE;
468
469 if (!g_in_beep_burst) {
470 // Starting a new beep burst
471 g_in_beep_burst = true;
472 g_beep_burst_samples = BEEP_WINDOW_SIZE;
473 } else {
474 g_beep_burst_samples += BEEP_WINDOW_SIZE;
475 }
476 } else {
477 if (g_in_beep_burst) {
478 // Beep burst ended
479 // Only count as beep event if it was short (< 500ms = 24000 samples)
480 // Long tonal sounds are likely music, not artifacts
481 if (g_beep_burst_samples > 0 && g_beep_burst_samples < 24000) {
482 g_received_beep_events++;
483 g_received_stats.beep_events = g_received_beep_events;
484 }
485 g_in_beep_burst = false;
486 g_beep_burst_samples = 0;
487 }
488 }
489
490 g_received_stats.tonal_samples = g_received_tonal_samples;
491 }
492
493 // Write to WAV file if enabled
494 if (g_received_wav) {
495 wav_writer_write(g_received_wav, &sample, 1);
496 }
497}
#define MAX_GAP_SAMPLES
Definition analysis.c:71
#define ECHO_BUFFER_SIZE
Definition analysis.c:90
#define BEEP_WINDOW_SIZE
Definition analysis.c:115
int wav_writer_write(wav_writer_t *writer, const float *samples, int num_samples)
Write audio samples to WAV file.
Definition wav_writer.c:107

References BEEP_WINDOW_SIZE, ECHO_BUFFER_SIZE, ECHO_DELAY_COUNT, MAX_GAP_SAMPLES, and wav_writer_write().

Referenced by audio_process_received_samples().

◆ audio_analysis_track_sent_packet()

void audio_analysis_track_sent_packet ( size_t size)

Track sent packet.

Parameters
sizePacket size in bytes

Definition at line 271 of file analysis.c.

271 {
272 (void)size; // Unused parameter - reserved for future per-packet analysis
273 if (!g_analysis_enabled)
274 return;
275
276 int64_t now_us = (int64_t)time_ns_to_us(time_get_ns());
277
278 // Detect gaps between consecutive packets (discontinuity)
279 if (g_sent_stats.packets_count > 0) {
280 int64_t gap_us = now_us - g_sent_last_packet_time_us;
281 int32_t gap_ms = (int32_t)(gap_us / 1000);
282
283 // Expected: ~20ms per Opus frame, flag if gap > 100ms
284 if (gap_ms > 100) {
285 g_sent_stats.discontinuity_count++;
286 }
287
288 // Track max gap
289 if (gap_ms > (int32_t)g_sent_stats.max_gap_ns) {
290 g_sent_stats.max_gap_ns = (uint32_t)gap_ms;
291 }
292 }
293
294 g_sent_last_packet_time_us = now_us;
295 g_sent_stats.packets_count++;
296}

◆ audio_analysis_track_sent_sample()

void audio_analysis_track_sent_sample ( float sample)

Track sent audio sample.

Parameters
sampleAudio sample value

Definition at line 197 of file analysis.c.

197 {
198 if (!g_analysis_enabled)
199 return;
200
201 g_sent_stats.total_samples++;
202
203 // Track peak level
204 float abs_sample = fabsf(sample);
205 if (abs_sample > g_sent_stats.peak_level) {
206 g_sent_stats.peak_level = abs_sample;
207 }
208
209 // Track clipping (samples > 1.0) - indicates distortion
210 if (abs_sample > 1.0f) {
211 g_sent_stats.clipping_count++;
212 g_sent_clipping_samples++;
213 }
214
215 // Detect sharp transitions (sudden amplitude jumps > 0.3) - indicates
216 // clicks/pops
217 float amp_change = fabsf(sample - g_sent_last_sample);
218 if (amp_change > 0.3f) {
219 g_sent_sharp_transitions++;
220 }
221 g_sent_transition_samples++;
222
223 // Accumulate for mean calculation
224 g_sent_mean += sample;
225
226 // Detect zero crossings (waveform crossing zero) - indicates spectral content
227 // Use file-scope static variable for prev sample tracking
228 // (This function is only called from the audio capture thread, but using
229 // file-scope static is clearer and avoids shadowing the existing
230 // g_sent_last_sample variable)
231 static float s_sent_prev_sample_for_zero_crossing = 0.0f;
232 if ((s_sent_prev_sample_for_zero_crossing > 0 && sample < 0) ||
233 (s_sent_prev_sample_for_zero_crossing < 0 && sample > 0)) {
234 g_sent_zero_crossings++;
235 }
236 s_sent_prev_sample_for_zero_crossing = sample;
237
238 // Track silence (very low level)
239 if (abs_sample < 0.001f) {
240 g_sent_stats.silent_samples++;
241 g_sent_silence_burst++;
242 } else {
243 // Silence ended - track max burst length
244 if (g_sent_silence_burst > g_sent_max_silence_burst) {
245 g_sent_max_silence_burst = g_sent_silence_burst;
246 }
247 g_sent_silence_burst = 0;
248 }
249
250 // Detect jitter: rapid amplitude changes > 0.5 between consecutive samples
251 float delta = fabsf(sample - g_sent_last_sample);
252 if (delta > 0.5f) {
253 g_sent_stats.jitter_count++;
254 }
255 g_sent_last_sample = sample;
256
257 // Accumulate for RMS calculation
258 g_sent_rms_accumulator += sample * sample;
259 g_sent_rms_sample_count++;
260
261 // Write to WAV file if enabled
262 if (g_sent_wav) {
263 wav_writer_write(g_sent_wav, &sample, 1);
264 }
265
266 // Store in echo detection buffer (circular)
267 g_echo_buffer[g_echo_buffer_pos] = sample;
268 g_echo_buffer_pos = (g_echo_buffer_pos + 1) % ECHO_BUFFER_SIZE;
269}

References ECHO_BUFFER_SIZE, and wav_writer_write().