Files
ShakaPlayer/SOUNDCLOUD_IMPROVEMENTS.md
2026-07-12 09:50:32 -07:00

269 lines
7.7 KiB
Markdown

# Shaka Player - SoundCloud Playback Improvements
## Issues to Fix
### 1. Random Stalling/Freezing During Playback
**Problem:** DRM tracks randomly get stuck in the middle of playback
**Current Behavior:** Stall detector waits 1 second, then either:
- Skips forward 0.1s
- Or pauses/unpauses
**Files:**
- `lib/media/gap_jumping_controller.js` (lines 338-365)
- `lib/media/streaming_engine.js`
**Proposed Improvements:**
- Add more aggressive stall recovery strategies
- Try multiple recovery methods in sequence
- Add better logging for debugging
- Increase buffer sizes for audio-only playback
### 2. Songs Starting at Wrong Time After Pausing
**Problem:** When a song is paused for extended period, next song starts at wrong time
**Current Behavior:** May be related to buffer eviction or seek logic
**Files:**
- `lib/media/playhead.js`
- `lib/media/streaming_engine.js`
**Proposed Improvements:**
- More aggressive currentTime resets on load
- Better buffer management around pauses
- Clear buffers more aggressively on stream switch
## Key Files to Modify
### Critical Files (Core Issues)
1. **lib/media/gap_jumping_controller.js** (18KB)
- Stall detection and recovery (lines 338-365)
- Gap jumping logic (lines 197-305)
- Browser gap tolerance (line 383)
2. **lib/media/streaming_engine.js** (146KB)
- Main buffering loop (line 1512)
- Buffer goal calculation (lines 1588-1646)
- Segment fetching logic
3. **lib/media/playhead.js** (20KB)
- Playhead position management
- Seek handling
### Supporting Files
4. **lib/media/buffering_observer.js** (5KB)
- Buffer state monitoring
5. **lib/media/media_source_engine.js** (99KB)
- MediaSource buffer management
## Configuration Changes
Current CrossSound config (from app.js line 518-567):
```javascript
streaming: {
rebufferingGoal: 4, // was 2
bufferingGoal: 20, // was 10
bufferBehind: 60, // was 30
stallEnabled: true,
stallThreshold: 1,
stallSkip: 0.1,
forceTransmuxTS: true
}
```
## Proposed Modifications
### Phase 1: Enhanced Stall Recovery
**File:** `lib/media/gap_jumping_controller.js`
**Current stall handler (line 338-365):**
```javascript
const onStall = async (at, duration) => {
if (skip) {
shaka.log.debug(`Seeking forward ${skip} seconds to break stall.`);
this.video_.currentTime += skip;
} else {
shaka.log.debug('Pausing and unpausing to break stall.');
await this.video_.play();
this.video_.pause();
this.video_.play();
}
this.stallsDetected_++;
this.onEvent_(new shaka.util.FakeEvent(
shaka.util.FakeEvent.EventName.StallDetected));
};
```
**Improved version:**
```javascript
const onStall = async (at, duration) => {
const bufferedInfo =
shaka.media.TimeRangesUtils.getBufferedInfo(this.video_.buffered);
shaka.log.warning(
`[SC] Stall detected at ${at} for ${duration}s. Buffered ranges:`,
bufferedInfo);
// Try multiple recovery strategies in sequence
if (skip) {
// Strategy 1: Skip forward
shaka.log.debug(`[SC] Recovery 1: Seeking forward ${skip}s`);
this.video_.currentTime += skip;
// Wait a bit to see if it worked
await new Promise(resolve => setTimeout(resolve, 100));
// If still stalled, try pause/unpause
if (this.video_.paused || this.video_.readyState < 3) {
shaka.log.debug('[SC] Recovery 2: Pause/unpause');
this.video_.pause();
await new Promise(resolve => setTimeout(resolve, 50));
await this.video_.play();
}
} else {
// Strategy 1: Pause/unpause
shaka.log.debug('[SC] Recovery 1: Pause/unpause');
this.video_.pause();
await new Promise(resolve => setTimeout(resolve, 50));
await this.video_.play();
// Wait a bit
await new Promise(resolve => setTimeout(resolve, 100));
// Strategy 2: If still stuck, seek to current position
if (this.video_.paused || this.video_.readyState < 3) {
shaka.log.debug('[SC] Recovery 2: Seek to current position');
const current = this.video_.currentTime;
this.video_.currentTime = current + 0.01;
}
}
this.stallsDetected_++;
this.onEvent_(new shaka.util.FakeEvent(
shaka.util.FakeEvent.EventName.StallDetected));
};
```
### Phase 2: Audio-Optimized Buffering
**File:** `lib/media/streaming_engine.js`
Add audio-specific optimizations:
- Larger buffers for audio-only content (no video bandwidth concerns)
- More aggressive prefetching
- Better gap handling for audio
### Phase 3: Better Seek/Resume Handling
**File:** `lib/media/playhead.js`
Improve handling of seeks after pauses:
- Force currentTime reset on stream switch
- Clear stale buffer state
- More aggressive time validation
## Build Configuration
The project uses Python build scripts. To build:
```bash
cd /c/Users/RedLintu16/Documents/Shaka
python3 build/all.py
```
Output will be in `dist/shaka-player.compiled.js`
## Integration with CrossSound
After building, copy the compiled file to CrossSound:
```bash
# Build Shaka
cd /c/Users/RedLintu16/Documents/Shaka
python3 build/all.py
# Copy to CrossSound (assuming it uses npm package or local copy)
cp dist/shaka-player.compiled.js /c/Users/RedLintu16/Documents/SCSC/node_modules/shaka-player/dist/
```
Or update CrossSound's package.json to use the local fork:
```json
{
"dependencies": {
"shaka-player": "file:../Shaka/dist"
}
}
```
## Testing Strategy
1. **Stall Testing:**
- Play DRM tracks for extended periods (10+ minutes)
- Monitor console for `[SC]` prefixed logs
- Count stall events and recovery success
2. **Resume Testing:**
- Pause tracks for varying durations (30s, 2min, 5min)
- Switch tracks while paused
- Verify next track starts at 0:00
3. **Buffer Testing:**
- Monitor buffer sizes during playback
- Check for excessive rebuffering
- Verify smooth playback with poor network
## Implementation Status
### Phase 1: Enhanced Stall Recovery ✅ COMPLETED
**Changes Made:**
1. **lib/media/gap_jumping_controller.js** (lines 338-365)
- Added multi-stage stall recovery with 3 strategies
- Strategy 1: Skip forward (if configured)
- Strategy 2: Pause/unpause after 100ms
- Strategy 3: Force buffer refresh with micro-seek
- Added detailed `[SC]` prefixed logging for debugging
- Each strategy waits 50-100ms before trying next one
2. **lib/media/gap_jumping_controller.js** (line 241)
- Reduced gap edge detection margin from 0.1s to 0.05s
- Faster gap detection for smoother audio playback
- Added logging when gap detected at range edge
3. **lib/media/gap_jumping_controller.js** (lines 284-291)
- Added `[SC]` prefix to gap jumping logs
- Easier to filter SoundCloud-specific events in console
**Build Status:** ⏳ In Progress
## Next Steps
1. ✅ Clone repository to C:\Users\RedLintu16\Documents\Shaka
2. ✅ Implement Phase 1 (Enhanced Stall Recovery)
3. ⏳ Build and test in CrossSound
4. ⏳ Implement Phase 2 (Audio-Optimized Buffering) if needed
5. ⏳ Implement Phase 3 (Better Seek/Resume) if needed
## Testing Instructions
After the build completes:
1. Copy `dist/shaka-player.compiled.js` to CrossSound
2. Replace the current Shaka Player in SCSC
3. Start CrossSound and test DRM playback
4. Monitor console for `[SC]` logs:
- `[SC] Stall detected at X for Ys` - When stall occurs
- `[SC] Recovery 1/3: ...` - First recovery attempt
- `[SC] Recovery 2/3: ...` - Second recovery attempt
- `[SC] Recovery 3/3: ...` - Final recovery attempt
- `[SC] Jumping forward X seconds` - Gap jumping events
- `[SC] Gap detected at range edge: X` - Edge gap detection
5. Test scenarios:
- Long playback sessions (30+ minutes)
- Pause for extended periods (5+ minutes) then resume
- Skip between tracks rapidly
- Poor network conditions (throttle network in DevTools)