Chatterbox-TTS-Server icon indicating copy to clipboard operation
Chatterbox-TTS-Server copied to clipboard

Issues with streaming audio

Open camr0 opened this issue 1 year ago β€’ 9 comments

I'm having some trouble trying to stream the audio output from the server. It's seems like it doesn't send the audio data until the audio is fully generated, resulting in a long pause. I've attached the quick test script I'm using to test response times for both APIs.


#!/usr/bin/env python3
"""
Test Chatterbox's custom /tts endpoint for TRUE streaming capability
"""
import requests
import time
import json

def test_custom_tts_streaming():
    """Test if /tts endpoint actually streams in real-time"""
    
    url = "http://localhost:8004/tts"
    headers = {
        "Content-Type": "application/json"
    }
    
    payload = {
        "text": "This is a long test sentence to see if the custom TTS endpoint streams audio in real-time chunks as the audio is being generated, rather than waiting until the entire audio is complete. We want to see if chunks arrive progressively during generation, not all at once after a long delay.",
        "voice_mode": "predefined",
        "predefined_voice_id": "Emily.wav",
        "output_format": "wav",
        "split_text": False,  # Don't split text to get pure streaming behavior
        "temperature": 0.7,
        "speed_factor": 1.0
    }
    
    print("πŸ§ͺ Testing Chatterbox Custom /tts Endpoint for TRUE Streaming")
    print("="*60)
    print(f"URL: {url}")
    print(f"Payload: {json.dumps(payload, indent=2)}")
    print("\n" + "="*60)
    
    start_time = time.time()
    first_chunk_time = None
    chunk_count = 0
    chunk_times = []
    total_bytes = 0
    
    try:
        with requests.post(url, headers=headers, json=payload, stream=True, timeout=120) as response:
            print(f"⏱️ Request sent at: {start_time:.3f}")
            print(f"πŸ“‘ Response status: {response.status_code}")
            print(f"πŸ“‹ Response headers: {dict(response.headers)}")
            
            if response.status_code != 200:
                print(f"❌ Error: {response.status_code}")
                print(f"Response text: {response.text}")
                return
            
            print(f"\nπŸ”„ Receiving chunks from CUSTOM /tts endpoint...")
            print("Chunk# | Time Since Start | Chunk Size | Time Between | Cumulative")
            print("-" * 70)
            
            last_chunk_time = start_time
            
            for chunk in response.iter_content(chunk_size=8192):  # 8KB chunks
                if chunk:
                    chunk_count += 1
                    current_time = time.time()
                    total_bytes += len(chunk)
                    
                    if first_chunk_time is None:
                        first_chunk_time = current_time
                        time_to_first = current_time - start_time
                        print(f"πŸŽ‰ FIRST CHUNK from /tts after {time_to_first:.3f}s")
                    
                    time_since_start = current_time - start_time
                    time_between = current_time - last_chunk_time
                    
                    print(f"{chunk_count:5d} | {time_since_start:13.3f}s | {len(chunk):9d}B | {time_between:8.3f}s | {total_bytes:8d}B")
                    
                    chunk_times.append(time_since_start)
                    last_chunk_time = current_time
                    
                    # Show first 15 chunks for analysis
                    if chunk_count >= 15:
                        print(f"... (showing first {chunk_count} chunks)")
                        break
            
            total_time = time.time() - start_time
            print(f"\nπŸ“Š CUSTOM /tts ENDPOINT RESULTS:")
            print(f"   Total chunks received: {chunk_count}")
            print(f"   Total bytes: {total_bytes}")
            print(f"   Time to first chunk: {time_to_first:.3f}s")
            print(f"   Total time: {total_time:.3f}s")
            
            # Analyze streaming behavior
            if time_to_first < 1.0:
                print(f"   βœ… FAST first chunk suggests TRUE STREAMING capability!")
            elif time_to_first < 2.0:
                print(f"   ⚑ Moderate delay - possible streaming with initial processing")
            else:
                print(f"   🚨 Large delay suggests this endpoint also pre-generates")
                
            # Check chunk timing pattern for TRUE streaming
            if len(chunk_times) > 3:
                gaps = [chunk_times[i] - chunk_times[i-1] for i in range(1, len(chunk_times))]
                avg_gap = sum(gaps) / len(gaps)
                
                # For TRUE streaming, we expect more variable timing
                instant_chunks = sum(1 for gap in gaps if gap < 0.05)  # < 50ms
                total_gaps = len(gaps)
                instant_ratio = instant_chunks / total_gaps
                
                print(f"   πŸ“Š Average time between chunks: {avg_gap:.3f}s")
                print(f"   πŸ“Š Instant chunks ratio: {instant_ratio:.2%} ({instant_chunks}/{total_gaps})")
                
                if instant_ratio > 0.8:  # More than 80% instant
                    print(f"   🚨 HIGH instant ratio - likely BATCH TRANSFER")
                    print(f"   πŸ“ Server probably generates complete audio first")
                else:
                    print(f"   βœ… VARIABLE timing suggests TRUE STREAMING!")
                    print(f"   🎯 This endpoint appears to stream during generation")
                    
    except Exception as e:
        print(f"❌ Error during custom /tts test: {e}")
        import traceback
        traceback.print_exc()

def compare_endpoints():
    """Quick comparison test between both endpoints"""
    print(f"\nπŸ” QUICK COMPARISON TEST")
    print("="*40)
    
    test_text = "Short test for comparison."
    
    endpoints = [
        {
            "name": "OpenAI Compatible",
            "url": "http://localhost:8004/v1/audio/speech",
            "headers": {"Authorization": "Bearer local-key", "Content-Type": "application/json"},
            "payload": {
                "model": "tts-1",
                "input": test_text,
                "voice": "Emily.wav",
                "response_format": "wav"
            }
        },
        {
            "name": "Custom /tts",
            "url": "http://localhost:8004/tts",
            "headers": {"Content-Type": "application/json"},
            "payload": {
                "text": test_text,
                "voice_mode": "predefined", 
                "predefined_voice_id": "Emily.wav",
                "output_format": "wav"
            }
        }
    ]
    
    for endpoint in endpoints:
        print(f"\nπŸ§ͺ Testing {endpoint['name']}...")
        start = time.time()
        
        try:
            response = requests.post(
                endpoint['url'],
                headers=endpoint['headers'], 
                json=endpoint['payload'],
                stream=True,
                timeout=30
            )
            
            first_chunk = next(response.iter_content(chunk_size=1024), None)
            first_chunk_time = time.time() - start
            
            print(f"   ⏱️ Time to first chunk: {first_chunk_time:.3f}s")
            print(f"   πŸ“‘ Status: {response.status_code}")
            
            if first_chunk_time < 1.0:
                print(f"   βœ… FAST - Likely supports streaming")
            else:
                print(f"   🚨 SLOW - Likely pre-generates audio")
                
        except Exception as e:
            print(f"   ❌ Error: {e}")

if __name__ == "__main__":
    print("πŸ§ͺ CHATTERBOX CUSTOM API STREAMING TEST")
    print("="*50)
    
    # Test the custom /tts endpoint thoroughly
    test_custom_tts_streaming()
    
    # Quick comparison between endpoints
    compare_endpoints()
    
    print(f"\n🎯 CONCLUSIONS:")
    print(f"   β€’ OpenAI /v1/audio/speech = Pre-generate + chunked transfer")
    print(f"   β€’ Custom /tts = ? (testing will reveal)")
    print(f"   β€’ If /tts shows TRUE streaming β†’ implement custom API client")

camr0 avatar Jun 07 '25 01:06 camr0

Is proper streaming supported? Any help would be appreciated!

camr0 avatar Jun 07 '25 01:06 camr0

Streaming is not supported. The server needs to generate the full audio before returning it to the client. However, the way to accomplish this is by processing smaller text chunks and pulling audio for each chunk from the /tts endpoint, then playing them continuously. That gets you pretty close to a streaming experience.

devnen avatar Jun 07 '25 09:06 devnen

Streaming is not supported. The server needs to generate the full audio before returning it to the client. However, the way to accomplish this is by processing smaller text chunks and pulling audio for each chunk from the /tts endpoint, then playing them continuously. That gets you pretty close to a streaming experience.

Do you think that this would negatively impact the overall "performance" of the reading?

drew-goody avatar Jun 13 '25 16:06 drew-goody

Streaming is not supported. The server needs to generate the full audio before returning it to the client. However, the way to accomplish this is by processing smaller text chunks and pulling audio for each chunk from the /tts endpoint, then playing them continuously. That gets you pretty close to a streaming experience.

Do you think that this would negatively impact the overall "performance" of the reading?

Not at all. Just combine all chunks and play them sequentially. As long as the generation is faster than reading the speech should sound natural.

devnen avatar Jun 13 '25 16:06 devnen

It definitely works, but it seems like the tone can shift in weird ways at times. I am not sure if that is a model, settings, or an implementation issue.

I appreciate you getting back to me!

drew-goody avatar Jun 13 '25 16:06 drew-goody

Try using the recommended settings and a fixed seed with the /TTS api endpoint for all chunks. For example:

Cfg: 0.5 Exaggeration: 0.5 Temperature: 0.8 Seed: 100

devnen avatar Jun 13 '25 17:06 devnen

any plans to allow for the streaming to happen on the frontend? that would be much better than only through the API.

IV2KBMoFxYIA avatar Jun 29 '25 04:06 IV2KBMoFxYIA

Streaming would also have to depend on how good one’s hardware is. Even with a RTX 4090, it takes time to generate even a few sentences.

@Mushy-Snugglebites-badonkadonk "Even with a RTX 4090, it takes time to generate even a few sentences." What realtime factor (RTF) do you suspect?

DoS007 avatar Dec 17 '25 15:12 DoS007