# Investigation Results: Media File Skipping

## Diagnostic Summary
✅ **All 3 media files are present and valid:**
- music.jpg (36,481 bytes) - IMAGE
- 130414-746934884.mp4 (6,474,921 bytes) - VIDEO (H.264, 1920x1080, compatible)
- IMG_0386.jpeg (592,162 bytes) - IMAGE

✅ **No file system issues found:**
- All files exist
- Correct permissions
- No case sensitivity problems
- Supported file types

✅ **Video codec is compatible:**
- H.264 codec (fully supported by ffpyplayer)
- 1920x1080 @ 29.97fps
- Reasonable bitrate (2.3 Mbps)

## Potential Root Causes Identified

### 1. **Video Widget Not Properly Stopping** (Most Likely)
When transitioning from video to the next media, the video widget may not be properly stopped before removal. This could cause:
- The video to continue playing in background
- Race conditions with scheduling
- Next media appearing to "skip"

**Location**: `play_current_media()` line 417-420
```python
if self.current_widget:
    self.ids.content_area.remove_widget(self.current_widget)
    self.current_widget = None
```

**Fix**: Stop video before removing widget

### 2. **Multiple Scheduled Events**
The `Clock.schedule_once(self.next_media, duration)` could be called multiple times if widget loading triggers multiple events.

**Location**: Lines 510, 548

**Fix**: Add `Clock.unschedule()` before scheduling

### 3. **Video Loading Callback Issues**
The video `loaded` callback might not fire or might fire multiple times, causing state confusion.

**Location**: `_on_video_loaded()` line 516

### 4. **Pause State Not Properly Checked**
If the player gets paused/unpaused during media transition, scheduling could get confused.

**Location**: `next_media()` line 551

## What Enhanced Logging Will Show

With the new logging, you'll see patterns like:

### If Videos Are Being Skipped:
```
===== Playing item 2/3 =====
File: 130414-746934884.mp4
Extension: .mp4
Media type: VIDEO
Loading video...
Creating Video widget...
[SHORT PAUSE OR ERROR]
Transitioning to next media (was index 1)
===== Playing item 3/3 =====
```

### If Duration Is Too Short:
```
Creating Video widget...
Scheduled next media in 23s
[Only 1-2 seconds pass]
Transitioning to next media
```

## Recommended Fixes

I've added comprehensive logging. Here are additional fixes to try:

### Fix 1: Properly Stop Video Widget Before Removal
Add this to `play_current_media()` before removing widget:

```python
# Remove previous media widget
if self.current_widget:
    # Stop video if it's playing
    if isinstance(self.current_widget, Video):
        self.current_widget.state = 'stop'
        self.current_widget.unload()
    self.ids.content_area.remove_widget(self.current_widget)
    self.current_widget = None
```

### Fix 2: Ensure Scheduled Events Don't Overlap
Modify scheduling in both `play_video()` and `play_image()`:

```python
# Unschedule any pending transitions before scheduling new one
Clock.unschedule(self.next_media)
Clock.schedule_once(self.next_media, duration)
```

### Fix 3: Add Video State Monitoring
Track when video actually starts playing vs when widget is created.

## How to Test

### 1. Run with Enhanced Logging
```bash
cd /home/pi/Desktop/Kiwy-Signage
source .venv/bin/activate
cd src
python3 main.py 2>&1 | tee ../playback_debug.log
```

Watch the console output. You should see:
- Each media file being loaded
- Timing information
- Any errors or skips

### 2. Check Timing
If media skips, check the log for timing:
- Does "Scheduled next media in Xs" appear?
- How long until "Transitioning to next media" appears?
- Is it immediate (< 1 second) = scheduling bug
- Is it after full duration = normal operation

### 3. Look for Error Patterns
Search the log for:
```bash
grep "❌" playback_debug.log
grep "Error" playback_debug.log
grep "consecutive_errors" playback_debug.log
```

## Quick Test Scenario

Create a test with just one file to isolate the issue:

```json
{
  "playlist": [
    {
      "file_name": "music.jpg",
      "url": "media/music.jpg",
      "duration": 10
    }
  ],
  "version": 99
}
```

If this single image repeats correctly every 10s, the issue is with video playback or transitions.

## What to Report

When you run the app, please capture:

1. **Console output** - especially the pattern around skipped files
2. **Which files skip?** - Is it always videos? Always after videos?
3. **Timing** - Do files play for full duration before skipping?
4. **Pattern** - First loop OK then skips? Always skips certain file?

## Tools Created

1. **diagnose_playlist.py** - Check file system issues
2. **test_playback_logging.py** - Simulate playback logic
3. **check_video_codecs.py** - Verify video compatibility
4. **Enhanced main.py** - Detailed logging throughout

## Next Actions

1. ✅ Run `diagnose_playlist.py` - **PASSED**
2. ✅ Run `check_video_codecs.py` - **PASSED** 
3. ⏳ Run app with logging and observe pattern
4. ⏳ Apply video widget fixes if needed
5. ⏳ Report findings for further diagnosis

The enhanced logging will pinpoint exactly where and why files are being skipped!
