Compare commits
6 Commits
ae5cdfb5e9
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 28b0907c70 | |||
| e895c22b6e | |||
| 89b80225c1 | |||
| 104c264af6 | |||
| dd02f0250c | |||
| d10869dd3e |
2
.specstory/.gitignore
vendored
2
.specstory/.gitignore
vendored
@@ -1,2 +1,4 @@
|
||||
# SpecStory explanation file
|
||||
/.what-is-this.md
|
||||
# SpecStory project identity file
|
||||
/.project.json
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
<!-- Generated by SpecStory -->
|
||||
|
||||
<!-- cursor Session c905dc1e-3b07-499f-8906-d3b9d49bb984 (2025-06-26 04:00Z) -->
|
||||
|
||||
# Test encode for one minute (2025-06-26 04:00Z)
|
||||
|
||||
_**User**_
|
||||
_**User (2025-07-03 15:00Z)**_
|
||||
|
||||
can we do a test encode for 1 min?
|
||||
|
||||
---
|
||||
|
||||
_**Assistant**_
|
||||
_**Assistant (default)**_
|
||||
|
||||
Yes, you can perform a test encode for just 1 minute of each file by modifying the FFmpeg command to only process the first 60 seconds. In FFmpeg, you can use the -t 60 option to limit the output duration to 60 seconds.
|
||||
|
||||
@@ -20,7 +22,7 @@ Would you like this as a permanent option (e.g., via a command-line flag or prom
|
||||
|
||||
---
|
||||
|
||||
_**User**_
|
||||
_**User (2025-07-03 15:00Z)**_
|
||||
|
||||
the output got stuck on this, but it shows my download rate @ ~300-400 mbps (it's encoding on a network share) do I just wait?
|
||||
|
||||
@@ -36,7 +38,7 @@ FFmpeg: [out#0/mp4 @ 00000287de38b840] Terminating thread with return code 0 (su
|
||||
|
||||
---
|
||||
|
||||
_**Assistant**_
|
||||
_**Assistant (default)**_
|
||||
|
||||
Yes, you should wait! The output shows that FFmpeg is still processing and hasn't actually gotten stuck. Here's what's happening:
|
||||
|
||||
@@ -60,7 +62,7 @@ The 300-400 Mbps network activity you're seeing is likely the input file being r
|
||||
|
||||
---
|
||||
|
||||
_**User**_
|
||||
_**User (2025-07-03 15:00Z)**_
|
||||
|
||||
what does this mean then? keep in mind my cpu is no longer being utilized
|
||||
FFmpeg: [out#0/mp4 @ 00000287de38b840] All streams finished
|
||||
@@ -68,7 +70,7 @@ FFmpeg: [out#0/mp4 @ 00000287de38b840] Terminating thread with return code 0 (su
|
||||
|
||||
---
|
||||
|
||||
_**Assistant**_
|
||||
_**Assistant (default)**_
|
||||
|
||||
That output means **the encoding is complete and successful!**
|
||||
|
||||
@@ -89,13 +91,13 @@ The 15-second test encode is complete! You should find the output file in your `
|
||||
|
||||
---
|
||||
|
||||
_**User**_
|
||||
_**User (2025-07-03 15:00Z)**_
|
||||
|
||||
why would ffmpeg.exe still be accessing files at this point?
|
||||
|
||||
---
|
||||
|
||||
_**Assistant**_
|
||||
_**Assistant (default)**_
|
||||
|
||||
FFmpeg might still be accessing files for several reasons even after the encoding is "complete":
|
||||
|
||||
@@ -116,19 +118,21 @@ If it's taking an unusually long time (>30 seconds), you could check if there ar
|
||||
|
||||
---
|
||||
|
||||
_**User**_
|
||||
_**User (2025-07-03 15:00Z)**_
|
||||
|
||||
the resultant file is broken.
|
||||
|
||||
---
|
||||
|
||||
_**Assistant**_
|
||||
_**Assistant (default)**_
|
||||
|
||||
The broken output file could be due to several issues. Let me help you troubleshoot:
|
||||
|
||||
|
||||
---
|
||||
|
||||
Tool use: **read_file**
|
||||
|
||||
Read file: encode_dvr_lossless_vp9.py
|
||||
|
||||
---
|
||||
@@ -146,7 +150,18 @@ The issue is likely that the process was interrupted or didn't complete properly
|
||||
|
||||
---
|
||||
|
||||
Tool use: **edit_file**
|
||||
|
||||
|
||||
<details><summary>Edit file: encode_dvr_lossless_vp9.py</summary>
|
||||
|
||||
I'll modify the FFmpeg command to be more robust by adding proper output format specification and ensuring clean termination
|
||||
|
||||
**Chunk 1**
|
||||
Lines added: 2, lines removed: undefined
|
||||
|
||||
```diff
|
||||
@@ -117,4 +117,6 @@
|
||||
'-c:a', 'copy',
|
||||
'-map', '0',
|
||||
+ '-f', 'mp4', # Explicitly specify output format
|
||||
@@ -155,6 +170,8 @@ The issue is likely that the process was interrupted or didn't complete properly
|
||||
# Add metadata for each audio stream if label exists
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
**Also, let's add a simple test to verify the output file:**
|
||||
@@ -162,7 +179,18 @@ The issue is likely that the process was interrupted or didn't complete properly
|
||||
|
||||
---
|
||||
|
||||
Tool use: **edit_file**
|
||||
|
||||
|
||||
<details><summary>Edit file: encode_dvr_lossless_vp9.py</summary>
|
||||
|
||||
I'll add a function to verify the output file integrity after encoding
|
||||
|
||||
**Chunk 1**
|
||||
Lines added: 9, lines removed: undefined
|
||||
|
||||
```diff
|
||||
@@ -68,4 +68,13 @@
|
||||
return f"{size_bytes:.2f} TB"
|
||||
|
||||
+ def verify_output_file(output_path):
|
||||
@@ -178,9 +206,22 @@ The issue is likely that the process was interrupted or didn't complete properly
|
||||
input_path = Path(input_file)
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
Tool use: **edit_file**
|
||||
|
||||
|
||||
<details><summary>Edit file: encode_dvr_lossless_vp9.py</summary>
|
||||
|
||||
I'll add file verification after successful encoding
|
||||
|
||||
**Chunk 1**
|
||||
Lines added: 8, lines removed: undefined
|
||||
|
||||
```diff
|
||||
@@ -159,9 +159,17 @@
|
||||
compression_ratio = input_size / output_size if output_size > 0 else 0
|
||||
|
||||
+ # Verify output file integrity
|
||||
@@ -200,6 +241,8 @@ The issue is likely that the process was interrupted or didn't complete properly
|
||||
logging.error(f"FFmpeg process failed with return code {process.returncode}")
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
**Now try the test again with these improvements:**
|
||||
@@ -217,13 +260,13 @@ The updated script should be more robust and will automatically detect and remov
|
||||
|
||||
---
|
||||
|
||||
_**User**_
|
||||
_**User (2025-07-09 00:17Z)**_
|
||||
|
||||
results are working, but I'm noticing massive sizes. is there a cq 0 option?
|
||||
|
||||
---
|
||||
|
||||
_**Assistant**_
|
||||
_**Assistant (default)**_
|
||||
|
||||
Yes! The issue is that you're using lossless VP9 encoding, which creates very large files. VP9 doesn't have a traditional "CQ 0" option like H.264/H.265, but you can use **CRF (Constant Rate Factor)** which is similar.
|
||||
|
||||
@@ -238,8 +281,42 @@ Let me modify the script to use CRF instead of lossless:
|
||||
|
||||
---
|
||||
|
||||
Tool use: **search_replace**
|
||||
|
||||
|
||||
<details><summary>Edit file: encode_dvr_lossless_vp9.py</summary>
|
||||
|
||||
**Chunk 1**
|
||||
Lines added: 1, lines removed: 1
|
||||
|
||||
```diff
|
||||
@@ -104,5 +104,5 @@
|
||||
logging.info(f"Audio labels: {audio_labels}")
|
||||
|
||||
- # FFmpeg command for lossless VP9 encoding with 60s timeout
|
||||
+ # FFmpeg command for high-quality VP9 encoding with 60s timeout
|
||||
cmd = [
|
||||
'ffmpeg',
|
||||
```
|
||||
|
||||
**Chunk 2**
|
||||
Lines added: 3, lines removed: 2
|
||||
|
||||
```diff
|
||||
@@ -111,6 +111,7 @@
|
||||
'-t', '1',
|
||||
'-c:v', 'libvpx-vp9',
|
||||
- '-lossless', '1',
|
||||
- '-cpu-used', '0',
|
||||
+ '-crf', '15', # High quality (0=lossless, 10-20=visually lossless, 20-30=high quality)
|
||||
+ '-b:v', '0', # Let CRF control bitrate
|
||||
+ '-cpu-used', '2', # Faster encoding (0=slowest, 5=fastest)
|
||||
'-row-mt', '1',
|
||||
'-threads', '0',
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
**Key changes:**
|
||||
@@ -258,21 +335,44 @@ The current setting of CRF 15 should give you excellent quality with much smalle
|
||||
|
||||
---
|
||||
|
||||
_**User**_
|
||||
_**User (2025-07-09 00:17Z)**_
|
||||
|
||||
these look good, can I test the full video lengths now?
|
||||
|
||||
---
|
||||
|
||||
_**Assistant**_
|
||||
_**Assistant (default)**_
|
||||
|
||||
Yes! To test the full video lengths, you just need to remove the `-t 1` parameter from the FFmpeg command. This will encode the entire duration of each video.
|
||||
|
||||
|
||||
---
|
||||
|
||||
Tool use: **search_replace**
|
||||
|
||||
|
||||
<details><summary>Edit file: encode_dvr_lossless_vp9.py</summary>
|
||||
|
||||
**Chunk 1**
|
||||
Lines added: 1, lines removed: 2
|
||||
|
||||
```diff
|
||||
@@ -104,10 +104,9 @@
|
||||
logging.info(f"Audio labels: {audio_labels}")
|
||||
|
||||
- # FFmpeg command for high-quality VP9 encoding with 60s timeout
|
||||
+ # FFmpeg command for high-quality VP9 encoding
|
||||
cmd = [
|
||||
'ffmpeg',
|
||||
'-v', 'verbose',
|
||||
'-i', str(input_path),
|
||||
- '-t', '1',
|
||||
'-c:v', 'libvpx-vp9',
|
||||
'-crf', '15', # High quality (0=lossless, 10-20=visually lossless, 20-30=high quality)
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
Perfect! Now the script will encode the full duration of each video. With your current settings:
|
||||
@@ -287,13 +387,13 @@ You can run the script now and it will process all 14 files in your input direct
|
||||
|
||||
---
|
||||
|
||||
_**User**_
|
||||
_**User (2025-07-09 00:17Z)**_
|
||||
|
||||
other than increasing the rate limit, how can I make this higher quality?
|
||||
|
||||
---
|
||||
|
||||
_**Assistant**_
|
||||
_**Assistant (default)**_
|
||||
|
||||
For higher quality VP9 encoding, here are the key parameters you can adjust:
|
||||
|
||||
@@ -312,8 +412,35 @@ For higher quality VP9 encoding, here are the key parameters you can adjust:
|
||||
|
||||
---
|
||||
|
||||
Tool use: **search_replace**
|
||||
|
||||
|
||||
<details><summary>Edit file: encode_dvr_lossless_vp9.py</summary>
|
||||
|
||||
**Chunk 1**
|
||||
Lines added: 5, lines removed: 2
|
||||
|
||||
```diff
|
||||
@@ -111,10 +111,13 @@
|
||||
'-t', '1', # Render only 1 second
|
||||
'-c:v', 'libvpx-vp9',
|
||||
- '-crf', '0',
|
||||
+ '-crf', '5', # Extremely high quality (0=lossless, 5-10=extremely high)
|
||||
'-b:v', '10000k',
|
||||
'-maxrate', '10000k',
|
||||
- '-cpu-used', '0',
|
||||
+ '-cpu-used', '0', # Slowest encoding for highest quality
|
||||
'-row-mt', '1',
|
||||
'-threads', '0',
|
||||
+ '-tile-columns', '2', # Better quality for 1080p
|
||||
+ '-frame-parallel', '1', # Parallel frame processing
|
||||
+ '-lag-in-frames', '25', # More frames for better compression
|
||||
'-c:a', 'copy',
|
||||
'-map', '0',
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
**Quality improvements added:**
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
<!-- Generated by SpecStory -->
|
||||
|
||||
<!-- cursor Session fd1849e6-e572-4051-8efe-3106af3956ce (2025-10-01 20:10Z) -->
|
||||
|
||||
# Delete specific files from output (2025-10-01 20:10Z)
|
||||
|
||||
_**User (2025-10-01 20:08Z)**_
|
||||
|
||||
could you delete these 4 files from output? don't touch input, and don't touch any other files in output.
|
||||
|
||||
---
|
||||
|
||||
_**Assistant (default)**_
|
||||
|
||||
Deleting the 4 problematic files from the output directory.
|
||||
|
||||
|
||||
---
|
||||
|
||||
Tool use: **delete_file**
|
||||
|
||||
undefined
|
||||
|
||||
---
|
||||
|
||||
Tool use: **delete_file**
|
||||
|
||||
undefined
|
||||
|
||||
---
|
||||
|
||||
Tool use: **delete_file**
|
||||
|
||||
undefined
|
||||
|
||||
---
|
||||
|
||||
Tool use: **delete_file**
|
||||
|
||||
undefined
|
||||
|
||||
---
|
||||
|
||||
Deleted the 4 files from the output directory:
|
||||
|
||||
- `2024-08-08 smithereens.ts.mp4` (audio stream count mismatch)
|
||||
- `2024-08-28 dejection.ts.mp4` (duration mismatch)
|
||||
- `2024-09-04 chaos.ts.mp4` (audio stream count mismatch)
|
||||
- `2024-09-05 resolute.ts.mp4` (duration mismatch)
|
||||
|
||||
No other files were modified.
|
||||
|
||||
---
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
@@ -0,0 +1,496 @@
|
||||
<!-- Generated by SpecStory, Markdown v2.1.0 -->
|
||||
|
||||
<!-- cursor Session 63dc8d99-2f1d-42e1-8f92-f9e14be8f352 (2025-10-08 02:35Z) -->
|
||||
|
||||
# Can damaged HEVC mp4s be repaired? (2025-10-08 02:35Z)
|
||||
|
||||
_**User (2025-10-08 02:35Z)**_
|
||||
|
||||
multiple damaged HEVC mp4s in input. can they be fixed?
|
||||
|
||||
---
|
||||
|
||||
_**Agent (model claude-4.5-sonnet-thinking, mode Agent)**_
|
||||
|
||||
<think><details><summary>Thought Process</summary>
|
||||
The user is asking about damaged HEVC mp4 files in the input directory. They want to know if they can be fixed. Let me first check what files are in the input directory to understand what we're working with.
|
||||
|
||||
I should:
|
||||
1. List the input directory to see what files are there
|
||||
2. Check if there are any tools or scripts already in place for fixing files
|
||||
3. Potentially suggest or implement a solution for fixing damaged MP4 files
|
||||
|
||||
Let me start by exploring the input directory.</details></think>
|
||||
|
||||
---
|
||||
|
||||
I'll help you check the damaged HEVC MP4 files in your input directory and see what can be done to fix them.
|
||||
|
||||
---
|
||||
|
||||
<tool-use data-tool-type="generic" data-tool-name="list_dir">
|
||||
<details>
|
||||
<summary>Tool use: **list_directory** • Listed directory undefined • **0** results</summary>
|
||||
|
||||
No results found
|
||||
</details>
|
||||
</tool-use>
|
||||
|
||||
---
|
||||
|
||||
<think><details><summary>Thought Process</summary>
|
||||
I can see there are many MP4 files in the input directory. The user says they are damaged HEVC MP4 files. Let me check one of the existing scripts to understand the structure, and then I can create a tool to analyze and potentially fix these files.
|
||||
|
||||
For damaged MP4 files, common fixes include:
|
||||
1. Using ffmpeg to remux (copy streams without re-encoding) which can fix container issues
|
||||
2. Using ffmpeg to recover what's possible from the damaged file
|
||||
3. Using specialized tools like untrunc, recover_mp4, or ffmpeg's error concealment
|
||||
|
||||
Let me check one of the existing encode scripts to see the pattern they use.</details></think>
|
||||
|
||||
---
|
||||
|
||||
I can see you have many DVR MP4 files. Let me check what kind of damage we're dealing with and create a tool to fix them. First, let me look at one of your existing scripts to understand your setup:
|
||||
|
||||
---
|
||||
|
||||
<tool-use data-tool-type="read" data-tool-name="read_file">
|
||||
<details><summary>Tool use: **read_file** • Read file: encode_dvr.py</summary>
|
||||
|
||||
</details>
|
||||
</tool-use>
|
||||
|
||||
---
|
||||
|
||||
<think><details><summary>Thought Process</summary>
|
||||
Good, I can see the structure. Now let me create a repair tool for damaged MP4 files. The best approaches for fixing damaged HEVC MP4s are:
|
||||
|
||||
1. Try to remux with ffmpeg (copy streams to a new container)
|
||||
2. Use ffmpeg with error concealment to recover what's possible
|
||||
3. Try to rebuild the MP4 structure
|
||||
|
||||
Let me create a Python script that follows their existing pattern and attempts to fix damaged MP4s using ffmpeg.</details></think>
|
||||
|
||||
---
|
||||
|
||||
Now let me create a repair tool to analyze and fix the damaged MP4 files. I'll create a script that attempts several repair strategies:
|
||||
|
||||
---
|
||||
|
||||
<tool-use data-tool-type="write" data-tool-name="write">
|
||||
|
||||
<details><summary>Tool use: **code_edit** • Edit file: repair_mp4.py</summary>
|
||||
|
||||
**Chunk 1**
|
||||
Lines added: 237, lines removed: 1
|
||||
|
||||
```diff
|
||||
@@ -1,1 +1,237 @@
|
||||
-
|
||||
+ import os
|
||||
+ import subprocess
|
||||
+ from pathlib import Path
|
||||
+ import json
|
||||
+ import logging
|
||||
+ from datetime import datetime
|
||||
+
|
||||
+ # ANSI color codes
|
||||
+ class Colors:
|
||||
+ PURPLE = '\033[95m'
|
||||
+ BLUE = '\033[94m'
|
||||
+ GREEN = '\033[92m'
|
||||
+ YELLOW = '\033[93m'
|
||||
+ RED = '\033[91m'
|
||||
+ ENDC = '\033[0m'
|
||||
+
|
||||
+ # Set up logging
|
||||
+ log_dir = "logs"
|
||||
+ os.makedirs(log_dir, exist_ok=True)
|
||||
+ log_file = os.path.join(log_dir, f"repair_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log")
|
||||
+ logging.basicConfig(filename=log_file, level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
||||
+
|
||||
+ def check_file_health(input_file):
|
||||
+ """Check if MP4 file has issues using ffmpeg"""
|
||||
+ print(f"\n{Colors.BLUE}Analyzing: {input_file}{Colors.ENDC}")
|
||||
+ logging.info(f"Analyzing file: {input_file}")
|
||||
+
|
||||
+ cmd = [
|
||||
+ 'ffmpeg',
|
||||
+ '-v', 'error',
|
||||
+ '-i', str(input_file),
|
||||
+ '-f', 'null',
|
||||
+ '-'
|
||||
+ ]
|
||||
+
|
||||
+ result = subprocess.run(cmd, capture_output=True, text=True)
|
||||
+
|
||||
+ if result.stderr:
|
||||
+ print(f"{Colors.RED}Issues found:{Colors.ENDC}")
|
||||
+ for line in result.stderr.split('\n')[:10]: # Show first 10 errors
|
||||
+ if line.strip():
|
||||
+ print(f" {Colors.YELLOW}{line}{Colors.ENDC}")
|
||||
+ logging.warning(f"File has errors: {result.stderr[:500]}")
|
||||
+ return False
|
||||
+ else:
|
||||
+ print(f"{Colors.GREEN}No errors detected{Colors.ENDC}")
|
||||
+ logging.info("File appears healthy")
|
||||
+ return True
|
||||
+
|
||||
+ def get_file_info(input_file):
|
||||
+ """Get basic file info"""
|
||||
+ cmd = [
|
||||
+ 'ffprobe',
|
||||
+ '-v', 'error',
|
||||
+ '-show_entries', 'format=duration,size:stream=codec_name,width,height',
|
||||
+ '-of', 'json',
|
||||
+ input_file
|
||||
+ ]
|
||||
+ result = subprocess.run(cmd, capture_output=True, text=True)
|
||||
+ try:
|
||||
+ return json.loads(result.stdout)
|
||||
+ except:
|
||||
+ return None
|
||||
+
|
||||
+ def repair_method_1_remux(input_file, output_file):
|
||||
+ """Method 1: Simple remux (copy streams to new container)"""
|
||||
+ print(f"\n{Colors.BLUE}Trying Method 1: Remux (copy streams){Colors.ENDC}")
|
||||
+ logging.info("Attempting repair method 1: Remux")
|
||||
+
|
||||
+ cmd = [
|
||||
+ 'ffmpeg',
|
||||
+ '-v', 'warning',
|
||||
+ '-i', str(input_file),
|
||||
+ '-c', 'copy',
|
||||
+ '-map', '0',
|
||||
+ '-y',
|
||||
+ str(output_file)
|
||||
+ ]
|
||||
+
|
||||
+ try:
|
||||
+ result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
|
||||
+ if result.returncode == 0 and Path(output_file).exists():
|
||||
+ print(f"{Colors.GREEN}Method 1 successful!{Colors.ENDC}")
|
||||
+ logging.info("Method 1 successful")
|
||||
+ return True
|
||||
+ else:
|
||||
+ print(f"{Colors.RED}Method 1 failed{Colors.ENDC}")
|
||||
+ logging.warning(f"Method 1 failed: {result.stderr[:200]}")
|
||||
+ return False
|
||||
+ except Exception as e:
|
||||
+ print(f"{Colors.RED}Method 1 error: {e}{Colors.ENDC}")
|
||||
+ logging.error(f"Method 1 error: {e}")
|
||||
+ return False
|
||||
+
|
||||
+ def repair_method_2_error_concealment(input_file, output_file):
|
||||
+ """Method 2: Remux with error concealment"""
|
||||
+ print(f"\n{Colors.BLUE}Trying Method 2: Error concealment{Colors.ENDC}")
|
||||
+ logging.info("Attempting repair method 2: Error concealment")
|
||||
+
|
||||
+ cmd = [
|
||||
+ 'ffmpeg',
|
||||
+ '-v', 'warning',
|
||||
+ '-err_detect', 'ignore_err',
|
||||
+ '-i', str(input_file),
|
||||
+ '-c', 'copy',
|
||||
+ '-map', '0',
|
||||
+ '-fflags', '+genpts+igndts',
|
||||
+ '-y',
|
||||
+ str(output_file)
|
||||
+ ]
|
||||
+
|
||||
+ try:
|
||||
+ result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
|
||||
+ if result.returncode == 0 and Path(output_file).exists():
|
||||
+ print(f"{Colors.GREEN}Method 2 successful!{Colors.ENDC}")
|
||||
+ logging.info("Method 2 successful")
|
||||
+ return True
|
||||
+ else:
|
||||
+ print(f"{Colors.RED}Method 2 failed{Colors.ENDC}")
|
||||
+ logging.warning(f"Method 2 failed: {result.stderr[:200]}")
|
||||
+ return False
|
||||
+ except Exception as e:
|
||||
+ print(f"{Colors.RED}Method 2 error: {e}{Colors.ENDC}")
|
||||
+ logging.error(f"Method 2 error: {e}")
|
||||
+ return False
|
||||
+
|
||||
+ def repair_method_3_force_keyframes(input_file, output_file):
|
||||
+ """Method 3: Force keyframe processing"""
|
||||
+ print(f"\n{Colors.BLUE}Trying Method 3: Force keyframe processing{Colors.ENDC}")
|
||||
+ logging.info("Attempting repair method 3: Force keyframe processing")
|
||||
+
|
||||
+ cmd = [
|
||||
+ 'ffmpeg',
|
||||
+ '-v', 'warning',
|
||||
+ '-fflags', '+discardcorrupt+genpts',
|
||||
+ '-i', str(input_file),
|
||||
+ '-c', 'copy',
|
||||
+ '-map', '0',
|
||||
+ '-avoid_negative_ts', 'make_zero',
|
||||
+ '-y',
|
||||
+ str(output_file)
|
||||
+ ]
|
||||
+
|
||||
+ try:
|
||||
+ result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
|
||||
+ if result.returncode == 0 and Path(output_file).exists():
|
||||
+ print(f"{Colors.GREEN}Method 3 successful!{Colors.ENDC}")
|
||||
+ logging.info("Method 3 successful")
|
||||
+ return True
|
||||
+ else:
|
||||
+ print(f"{Colors.RED}Method 3 failed{Colors.ENDC}")
|
||||
+ logging.warning(f"Method 3 failed: {result.stderr[:200]}")
|
||||
+ return False
|
||||
+ except Exception as e:
|
||||
+ print(f"{Colors.RED}Method 3 error: {e}{Colors.ENDC}")
|
||||
+ logging.error(f"Method 3 error: {e}")
|
||||
+ return False
|
||||
+
|
||||
+ def repair_file(input_file, output_dir):
|
||||
+ """Attempt to repair a damaged MP4 file"""
|
||||
+ input_path = Path(input_file)
|
||||
+ output_path = Path(output_dir) / f"{input_path.stem}_repaired{input_path.suffix}"
|
||||
+
|
||||
+ print(f"\n{Colors.PURPLE}{'='*60}{Colors.ENDC}")
|
||||
+ print(f"{Colors.PURPLE}Processing: {input_path.name}{Colors.ENDC}")
|
||||
+ print(f"{Colors.PURPLE}{'='*60}{Colors.ENDC}")
|
||||
+
|
||||
+ # Skip if already repaired
|
||||
+ if output_path.exists():
|
||||
+ print(f"{Colors.YELLOW}Already repaired: {output_path.name}{Colors.ENDC}")
|
||||
+ logging.info(f"Skipping {input_path} - already repaired")
|
||||
+ return
|
||||
+
|
||||
+ # Check file health first
|
||||
+ is_healthy = check_file_health(str(input_path))
|
||||
+
|
||||
+ if is_healthy:
|
||||
+ print(f"{Colors.GREEN}File appears healthy, no repair needed{Colors.ENDC}")
|
||||
+ logging.info("File is healthy, skipping")
|
||||
+ return
|
||||
+
|
||||
+ # Try repair methods in sequence
|
||||
+ methods = [
|
||||
+ repair_method_1_remux,
|
||||
+ repair_method_2_error_concealment,
|
||||
+ repair_method_3_force_keyframes
|
||||
+ ]
|
||||
+
|
||||
+ for method in methods:
|
||||
+ if method(str(input_path), str(output_path)):
|
||||
+ # Verify the repaired file
|
||||
+ print(f"\n{Colors.BLUE}Verifying repaired file...{Colors.ENDC}")
|
||||
+ if check_file_health(str(output_path)):
|
||||
+ print(f"{Colors.GREEN}✓ Repair successful and verified!{Colors.ENDC}")
|
||||
+ logging.info(f"Successfully repaired: {output_path}")
|
||||
+
|
||||
+ # Show size comparison
|
||||
+ original_size = input_path.stat().st_size / (1024*1024)
|
||||
+ repaired_size = output_path.stat().st_size / (1024*1024)
|
||||
+ print(f"Original: {original_size:.2f} MB → Repaired: {repaired_size:.2f} MB")
|
||||
+ logging.info(f"Size: {original_size:.2f} MB → {repaired_size:.2f} MB")
|
||||
+ return
|
||||
+ else:
|
||||
+ print(f"{Colors.YELLOW}Repair completed but file still has issues{Colors.ENDC}")
|
||||
+ logging.warning("Repaired file still has issues")
|
||||
+ return
|
||||
+
|
||||
+ print(f"{Colors.RED}All repair methods failed{Colors.ENDC}")
|
||||
+ logging.error(f"Failed to repair: {input_path}")
|
||||
+
|
||||
+ if __name__ == "__main__":
|
||||
+ input_dir = "input"
|
||||
+ output_dir = "output"
|
||||
+ os.makedirs(output_dir, exist_ok=True)
|
||||
+
|
||||
+ # Get list of MP4 files
|
||||
+ files = [f for f in os.listdir(input_dir) if f.endswith(('.mp4', '.DVR.mp4'))]
|
||||
+ total_files = len(files)
|
||||
+
|
||||
+ if total_files == 0:
|
||||
+ print(f"{Colors.YELLOW}No MP4 files found in input directory{Colors.ENDC}")
|
||||
+ logging.info("No files to process")
|
||||
+ else:
|
||||
+ print(f"\n{Colors.BLUE}Found {total_files} MP4 files to check{Colors.ENDC}")
|
||||
+ logging.info(f"Found {total_files} files to process")
|
||||
+
|
||||
+ for i, file in enumerate(files, 1):
|
||||
+ input_file = os.path.join(input_dir, file)
|
||||
+ print(f"\n{Colors.BLUE}[{i}/{total_files}]{Colors.ENDC}")
|
||||
+ repair_file(input_file, output_dir)
|
||||
+
|
||||
+ print(f"\n{Colors.GREEN}{'='*60}{Colors.ENDC}")
|
||||
+ print(f"{Colors.GREEN}Repair process complete!{Colors.ENDC}")
|
||||
+ print(f"{Colors.GREEN}Check the output directory for repaired files{Colors.ENDC}")
|
||||
+ print(f"{Colors.GREEN}Log file: {log_file}{Colors.ENDC}")
|
||||
+ print(f"{Colors.GREEN}{'='*60}{Colors.ENDC}")
|
||||
+
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
</tool-use>
|
||||
|
||||
---
|
||||
|
||||
<tool-use data-tool-type="write" data-tool-name="write">
|
||||
|
||||
<details><summary>Tool use: **code_edit** • Edit file: repair_mp4.bat</summary>
|
||||
|
||||
**Chunk 1**
|
||||
Lines added: 4, lines removed: 1
|
||||
|
||||
```diff
|
||||
@@ -1,1 +1,4 @@
|
||||
-
|
||||
+ @echo off
|
||||
+ python repair_mp4.py
|
||||
+ pause
|
||||
+
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
</tool-use>
|
||||
|
||||
---
|
||||
|
||||
<think><details><summary>Thought Process</summary>
|
||||
Great! I've created the repair script. Now let me explain to the user what I've created and how it works. The script will:
|
||||
|
||||
1. Check each MP4 file for errors using ffmpeg
|
||||
2. Try multiple repair methods if issues are found
|
||||
3. Verify the repaired files
|
||||
4. Log everything
|
||||
|
||||
Let me provide a comprehensive explanation to the user.</details></think>
|
||||
|
||||
---
|
||||
|
||||
I've created a repair tool for your damaged HEVC MP4 files! Here's what it does:
|
||||
|
||||
## **`repair_mp4.py`** - MP4 Repair Tool
|
||||
|
||||
The script will:
|
||||
|
||||
1. **Analyze each file** - Uses ffmpeg to detect errors and issues
|
||||
2. **Skip healthy files** - Only attempts repair on damaged files
|
||||
3. **Try 3 repair methods** in sequence:
|
||||
- **Method 1**: Simple remux (copy streams to new container)
|
||||
- **Method 2**: Error concealment mode (ignore errors and regenerate timestamps)
|
||||
- **Method 3**: Force keyframe processing with corruption discard
|
||||
4. **Verify repairs** - Checks if the repaired file is actually fixed
|
||||
5. **Log everything** - Creates detailed logs in the `logs` directory
|
||||
|
||||
### Repaired files will be saved as:
|
||||
- Input: `input/filename.mp4`
|
||||
- Output: `output/filename_repaired.mp4`
|
||||
|
||||
### To use it:
|
||||
|
||||
Just run `repair_mp4.bat` or `python repair_mp4.py`
|
||||
|
||||
The script will automatically:
|
||||
- Process all MP4 files in the `input` directory
|
||||
- Show colored output with progress and results
|
||||
- Skip files that are already healthy
|
||||
- Skip files already repaired
|
||||
- Create a timestamped log file
|
||||
|
||||
### What causes MP4 damage?
|
||||
- Interrupted recordings (DVR stopped abruptly)
|
||||
- Missing/corrupted moov atom (MP4 metadata)
|
||||
- Corrupted keyframes
|
||||
- Invalid timestamps
|
||||
|
||||
These repair methods work well for most common DVR recording issues. If files can't be repaired, the script will tell you which ones failed and you can check the log for details.
|
||||
|
||||
Would you like me to run it now to see which files are damaged and attempt repairs?
|
||||
|
||||
---
|
||||
|
||||
_**User (2025-10-08 05:55Z)**_
|
||||
|
||||
@repair_20251007_203713.log
|
||||
|
||||
---
|
||||
|
||||
_**Agent (model gpt-5, mode Agent)**_
|
||||
|
||||
<think><details><summary>Thought Process</summary>
|
||||
**Evaluating code logic**
|
||||
|
||||
I'm seeing a problem in the log after method 1 succeeds—it's showing errors and saying the "Repaired file still has issues." In our code, when verification fails, it prints that "Repair completed but the file still has issues" and then returns. This means we aren't continuing to methods 2 and 3 if method 1 has an output but isn't verified as healthy. We should adjust the design to allow proceeding with subsequent methods, ensuring they’re all attempted if verification fails. I'll need to edit the repair_mp4.py file for this.
|
||||
**Improving video processing methods**
|
||||
|
||||
I'm considering adding a method to re-encode the video track for fixing DTS issues. This could involve decoding and re-encoding using flags like `-fflags +genpts`, `-vsync 1`, or `-bsf:v hevc_mp4toannexb`. For non-monotonic DTS issues, re-muxing with `-fflags +genpts` may help too. I think we should also allow the script to proceed to methods 2 and 3 if method 1 reveals errors. Overall, I need to ensure that all methods are tested to fully address the problems.
|
||||
**Addressing HEVC stream errors**
|
||||
|
||||
When dealing with HEVC stream corruption and POC errors, I think transcoding the video stream to create clean frames while copying the audio could be essential. I could propose method 4, which involves re-encoding the video with `hevc_nvenc` and resetting PTS using specific flags. Alternatively, I might consider re-encoding to H.264 for compatibility, but since the user is using HEVC, I should focus on the best HEVC commands. Overall, I want to ensure the solution addresses the monotonic DTS issues effectively.
|
||||
**Resolving DTS issues**
|
||||
|
||||
The "non-monotonically increasing DTS to muxer" error seems to happen when decode timestamps are out of order. To fix this, I think using `-vsync 1` can enforce CFR, or possibly `-copyts 1` to keep input timestamps. Our method 2 uses `-err_detect ignore_err` and `-fflags +genpts+igndts`, which might be helpful. For method 3, it employs `-fflags +discardcorrupt+genpts`. I should consider trying both methods. I could even explore using `-vsync 1` or `-vsync 2` to manage frame rates as part of this solution.
|
||||
**Analyzing HEVC MP4 Issues**
|
||||
|
||||
I've reviewed the user's question about fixing multiple damaged HEVC MP4 files, and the log indicates most have DTS monotonic issues. Simple remuxing didn't resolve the problems, and our script didn't move on to advanced steps due to control-flow issues. I propose modifying the script to continue to the next methods and add a re-encode option to regenerate timestamps. Since the user didn't request a new script, I'll recommend commands they can run instead. I can provide concise commands for PowerShell that could help fix the files. Let’s outline some clear options for them!
|
||||
**Preparing FFmpeg Commands**
|
||||
|
||||
I’ll provide a command for re-encoding videos with FFmpeg, specifically using HEVC settings. Here's a sample command that utilizes hardware acceleration:
|
||||
|
||||
```
|
||||
ffmpeg -v warning -hwaccel cuda -i "in.mp4" -map 0:v:0 -map 0:a? -c:v hevc_nvenc -preset p6 -tune hq -rc vbr -cq 28 -g 240 -fflags +genpts -vsync 1 -c:a copy -movflags +faststart -max_interleave_delta 0 -avoid_negative_ts make_zero "output\in_clean.mp4"
|
||||
```
|
||||
|
||||
For a PowerShell one-liner that processes files with errors:
|
||||
|
||||
```
|
||||
Get-ChildItem input -File -Include *.mp4, *.DVR.mp4 | ForEach-Object { $out = Join-Path output ($_.BaseName + "_clean" + $_.Extension); ffmpeg -v warning -hwaccel cuda -fflags +genpts -err_detect ignore_err -i $_.FullName -map 0 -c:v hevc_nvenc -preset p6 -tune hq -rc vbr -cq 28 -g 240 -c:a copy -movflags +faststart -max_interleave_delta 0 -avoid_negative_ts make_zero $out }
|
||||
```
|
||||
|
||||
If needed, I can update `repair_mp4.py` to continue processing methods after failures and add a re-encode option. Most files are experiencing 'non-monotonically increasing DTS' issues, persisting despite remuxing. Many files appear healthy, but the warnings remain.
|
||||
|
||||
I'm ready to assist with further actions!</details></think>
|
||||
|
||||
---
|
||||
|
||||
- I reviewed your `repair_20251007_203713.log`. The script only tried Method 1 (remux) and then stopped even when verification still showed errors. It never attempted Methods 2/3. Most failures are timestamp issues: “non monotonically increasing dts”; a few have actual HEVC decode corruption (POC/ref errors). Many files are fine.
|
||||
|
||||
### What this means
|
||||
- **Timestamp-only issues (DTS/PTS)**: Usually fixable by regenerating timestamps; remux alone often isn’t enough.
|
||||
- **Decode corruption (HEVC/H264 errors)**: Requires re-encoding video to make a clean stream; audio can usually be copied.
|
||||
|
||||
### Quick fixes you can run (no new scripts)
|
||||
- **Try “copy with regenerated PTS” (handles many DTS issues):**
|
||||
```powershell
|
||||
# One file example
|
||||
ffmpeg -v warning -err_detect ignore_err -fflags +genpts+igndts -i "input\FILE.mp4" -map 0 -c copy -max_interleave_delta 0 -movflags +faststart -avoid_negative_ts make_zero "output\FILE_ptsfix.mp4"
|
||||
```
|
||||
|
||||
- **If still broken, re-encode video, copy audio (fixes DTS + decode errors):**
|
||||
```powershell
|
||||
# NVIDIA (uses your GPU)
|
||||
ffmpeg -v warning -hwaccel cuda -fflags +genpts -err_detect ignore_err -i "input\FILE.mp4" -map 0:v:0 -map 0:a? -c:v hevc_nvenc -preset p6 -tune hq -rc vbr -cq 28 -g 240 -vsync 1 -c:a copy -movflags +faststart -max_interleave_delta 0 -avoid_negative_ts make_zero "output\FILE_clean.mp4"
|
||||
```
|
||||
|
||||
- **Batch across all MP4/DVR files (re-encode video, copy audio):**
|
||||
```powershell
|
||||
Get-ChildItem input -File -Include *.mp4,*.DVR.mp4 | ForEach-Object {
|
||||
$out = Join-Path output ($_.BaseName + "_clean" + $_.Extension)
|
||||
ffmpeg -v warning -hwaccel cuda -fflags +genpts -err_detect ignore_err -i $_.FullName `
|
||||
-map 0:v:0 -map 0:a? -c:v hevc_nvenc -preset p6 -tune hq -rc vbr -cq 28 -g 240 -vsync 1 `
|
||||
-c:a copy -movflags +faststart -max_interleave_delta 0 -avoid_negative_ts make_zero $out
|
||||
}
|
||||
```
|
||||
|
||||
Notes:
|
||||
- `-fflags +genpts`/`-vsync 1` rebuild timestamps; `-err_detect ignore_err` skips bad frames; `-g 240` adds periodic keyframes; audio is copied to avoid quality loss.
|
||||
- This will repair both the DTS warnings and most HEVC “POC/ref” decode errors by producing a clean stream.
|
||||
|
||||
### Optional: fix your tool
|
||||
If you want, I can update `repair_mp4.py` to:
|
||||
- Keep trying Method 2 and 3 when Method 1’s verification fails.
|
||||
- Add a Method 4 that re-encodes video as shown above (audio copy), only used if 1–3 fail.
|
||||
|
||||
Say “update the repair script” and I’ll apply the edits.
|
||||
|
||||
---
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
<!-- Generated by SpecStory, Markdown v2.0.0 -->
|
||||
|
||||
<!-- cursor Session 3bab80f9-de45-4af3-9283-05d0a836948d (2025-11-07 07:55Z) -->
|
||||
|
||||
# OBS update issues and encoding speed (2025-11-07 07:55Z)
|
||||
|
||||
_**User (2025-11-07 07:55Z)**_
|
||||
|
||||
Kinda crazy. OBS updating murdered all of my preferences, so I forgot to change the default rescaled output and default framerate from 60. My @encode_VOD.py script recoded the 2hr+ file in 18 minutes. @1080p60, I would normally expect that to take at least an hour... That's the difference between ~2x speed and ~7x speed... @encode_20251107_003149.log
|
||||
|
||||
---
|
||||
|
||||
_**Agent (model default, mode Agent)**_
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
Reviewing the log to understand why encoding was faster than expected.
|
||||
|
||||
|
||||
---
|
||||
|
||||
<tool-use data-tool-type="read" data-tool-name="read_file">
|
||||
<details><summary>Tool use: **read_file** • Read file: logs/encode_20251107_003149.log</summary>
|
||||
|
||||
</details>
|
||||
</tool-use>
|
||||
|
||||
---
|
||||
|
||||
<tool-use data-tool-type="read" data-tool-name="read_file">
|
||||
<details><summary>Tool use: **read_file** • Read file: encode_VOD.py</summary>
|
||||
|
||||
</details>
|
||||
</tool-use>
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
Checking key sections of the log for input file details and encoding speed:
|
||||
|
||||
|
||||
---
|
||||
|
||||
<tool-use data-tool-type="read" data-tool-name="read_file">
|
||||
<details><summary>Tool use: **read_file** • Read file: logs/encode_20251107_003149.log</summary>
|
||||
|
||||
</details>
|
||||
</tool-use>
|
||||
|
||||
---
|
||||
|
||||
<tool-use data-tool-type="grep" data-tool-name="grep">
|
||||
<details>
|
||||
<summary>Tool use: **grep** • Grep for "width|height|r_frame_rate|fps=|frame=" in "logs/encode_20251107_003149.log" • 49 matches</summary>
|
||||
|
||||
Output mode: content
|
||||
|
||||
|
||||
| File | Content | Line |
|
||||
|------|------|------|
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:31:50,958 - INFO - width: 1280` | L9 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:31:50,959 - INFO - height: 720` | L10 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:31:50,959 - INFO - r_frame_rate: 30/1` | L11 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:31:50,960 - INFO - r_frame_rate: 0/0` | L16 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:31:50,961 - INFO - r_frame_rate: 0/0` | L21 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:31:53,413 - INFO - Progress: frame= 211 fps=205 q=3.0 size= 3072KiB time=00:00:06.86 bitrate=3665.0kbits/s speed=6.69x elapsed=0:00:01.02` | L87 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:31:54,433 - INFO - Progress: frame= 478 fps=235 q=3.0 size= 3584KiB time=00:00:15.83 bitrate=1854.3kbits/s speed=7.78x elapsed=0:00:02.03` | L88 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:31:55,436 - INFO - Progress: frame= 783 fps=256 q=3.0 size= 4352KiB time=00:00:26.00 bitrate=1371.2kbits/s speed=8.51x elapsed=0:00:03.05` | L89 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:31:56,458 - INFO - Progress: frame= 1080 fps=266 q=3.0 size= 5376KiB time=00:00:35.90 bitrate=1226.8kbits/s speed=8.84x elapsed=0:00:04.05` | L90 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:31:57,475 - INFO - Progress: frame= 1382 fps=272 q=3.0 size= 6144KiB time=00:00:45.96 bitrate=1095.0kbits/s speed=9.05x elapsed=0:00:05.08` | L91 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:31:58,493 - INFO - Progress: frame= 1684 fps=276 q=3.0 size= 9984KiB time=00:00:56.03 bitrate=1459.7kbits/s speed=9.19x elapsed=0:00:06.09` | L92 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:31:59,511 - INFO - Progress: frame= 1982 fps=279 q=4.0 size= 14336KiB time=00:01:05.96 bitrate=1780.3kbits/s speed=9.27x elapsed=0:00:07.11` | L93 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:00,515 - INFO - Progress: frame= 2282 fps=281 q=4.0 size= 20224KiB time=00:01:15.96 bitrate=2180.9kbits/s speed=9.34x elapsed=0:00:08.13` | L94 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:01,534 - INFO - Progress: frame= 2552 fps=279 q=2.0 size= 23808KiB time=00:01:25.10 bitrate=2291.8kbits/s speed=9.31x elapsed=0:00:09.13` | L95 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:02,558 - INFO - Progress: frame= 2854 fps=281 q=2.0 size= 28160KiB time=00:01:35.03 bitrate=2427.4kbits/s speed=9.36x elapsed=0:00:10.15` | L96 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:03,564 - INFO - Progress: frame= 3156 fps=282 q=4.0 size= 32000KiB time=00:01:45.10 bitrate=2494.2kbits/s speed= 9.4x elapsed=0:00:11.18` | L97 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:04,583 - INFO - Progress: frame= 3454 fps=283 q=2.0 size= 34816KiB time=00:01:55.03 bitrate=2479.4kbits/s speed=9.44x elapsed=0:00:12.18` | L98 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:05,599 - INFO - Progress: frame= 3746 fps=284 q=3.0 size= 38912KiB time=00:02:04.76 bitrate=2554.9kbits/s speed=9.45x elapsed=0:00:13.20` | L99 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:06,620 - INFO - Progress: frame= 3910 fps=275 q=4.0 size= 40192KiB time=00:02:10.23 bitrate=2528.2kbits/s speed=9.16x elapsed=0:00:14.22` | L100 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:07,627 - INFO - Progress: frame= 4212 fps=276 q=4.0 size= 44544KiB time=00:02:20.30 bitrate=2600.9kbits/s speed= 9.2x elapsed=0:00:15.24` | L101 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:08,645 - INFO - Progress: frame= 4442 fps=273 q=4.0 size= 47104KiB time=00:02:27.96 bitrate=2607.9kbits/s speed=9.11x elapsed=0:00:16.25` | L102 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:09,664 - INFO - Progress: frame= 4744 fps=275 q=4.0 size= 50688KiB time=00:02:38.03 bitrate=2627.5kbits/s speed=9.15x elapsed=0:00:17.26` | L103 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:10,681 - INFO - Progress: frame= 5044 fps=276 q=4.0 size= 54784KiB time=00:02:48.03 bitrate=2670.8kbits/s speed=9.19x elapsed=0:00:18.28` | L104 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:11,688 - INFO - Progress: frame= 5342 fps=277 q=4.0 size= 58624KiB time=00:02:57.96 bitrate=2698.5kbits/s speed=9.22x elapsed=0:00:19.30` | L105 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:12,707 - INFO - Progress: frame= 5616 fps=276 q=4.0 size= 62464KiB time=00:03:07.10 bitrate=2734.9kbits/s speed=9.21x elapsed=0:00:20.31` | L106 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:13,727 - INFO - Progress: frame= 5918 fps=277 q=4.0 size= 66304KiB time=00:03:17.16 bitrate=2754.8kbits/s speed=9.24x elapsed=0:00:21.33` | L107 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:14,737 - INFO - Progress: frame= 6220 fps=278 q=4.0 size= 70656KiB time=00:03:27.23 bitrate=2793.1kbits/s speed=9.27x elapsed=0:00:22.35` | L108 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:15,755 - INFO - Progress: frame= 6516 fps=279 q=3.0 size= 74496KiB time=00:03:37.10 bitrate=2811.0kbits/s speed=9.29x elapsed=0:00:23.36` | L109 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:16,774 - INFO - Progress: frame= 6818 fps=280 q=12.0 size= 79616KiB time=00:03:47.16 bitrate=2871.1kbits/s speed=9.32x elapsed=0:00:24.37` | L110 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:17,794 - INFO - Progress: frame= 7116 fps=280 q=9.0 size= 92160KiB time=00:03:57.10 bitrate=3184.2kbits/s speed=9.34x elapsed=0:00:25.39` | L111 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:18,798 - INFO - Progress: frame= 7383 fps=279 q=9.0 size= 103424KiB time=00:04:06.00 bitrate=3444.1kbits/s speed=9.31x elapsed=0:00:26.41` | L112 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:19,818 - INFO - Progress: frame= 7594 fps=277 q=11.0 size= 112384KiB time=00:04:13.03 bitrate=3638.5kbits/s speed=9.23x elapsed=0:00:27.42` | L113 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:20,836 - INFO - Progress: frame= 7878 fps=277 q=14.0 size= 124160KiB time=00:04:22.50 bitrate=3874.7kbits/s speed=9.23x elapsed=0:00:28.44` | L114 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:21,843 - INFO - Progress: frame= 8165 fps=277 q=9.0 size= 136192KiB time=00:04:32.06 bitrate=4100.8kbits/s speed=9.24x elapsed=0:00:29.45` | L115 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:22,867 - INFO - Progress: frame= 8434 fps=277 q=17.0 size= 147712KiB time=00:04:41.03 bitrate=4305.7kbits/s speed=9.22x elapsed=0:00:30.46` | L116 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:23,874 - INFO - Progress: frame= 8708 fps=277 q=16.0 size= 158720KiB time=00:04:50.16 bitrate=4481.0kbits/s speed=9.21x elapsed=0:00:31.49` | L117 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:24,894 - INFO - Progress: frame= 8984 fps=276 q=18.0 size= 170496KiB time=00:04:59.40 bitrate=4665.0kbits/s speed=9.21x elapsed=0:00:32.49` | L118 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:25,904 - INFO - Progress: frame= 9279 fps=277 q=17.0 size= 182528KiB time=00:05:09.20 bitrate=4835.9kbits/s speed=9.23x elapsed=0:00:33.51` | L119 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:26,928 - INFO - Progress: frame= 9567 fps=277 q=10.0 size= 195072KiB time=00:05:18.80 bitrate=5012.6kbits/s speed=9.23x elapsed=0:00:34.52` | L120 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:27,949 - INFO - Progress: frame= 9863 fps=277 q=11.0 size= 207104KiB time=00:05:28.70 bitrate=5161.5kbits/s speed=9.25x elapsed=0:00:35.55` | L121 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:28,961 - INFO - Progress: frame=10121 fps=277 q=12.0 size= 217856KiB time=00:05:37.26 bitrate=5291.6kbits/s speed=9.22x elapsed=0:00:36.57` | L122 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:29,980 - INFO - Progress: frame=10398 fps=277 q=-1.0 size= 228352KiB time=00:05:46.50 bitrate=5398.7kbits/s speed=9.22x elapsed=0:00:37.58` | L123 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:30,991 - INFO - Progress: frame=10663 fps=276 q=4.0 size= 237568KiB time=00:05:55.33 bitrate=5477.0kbits/s speed= 9.2x elapsed=0:00:38.60` | L124 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:32,001 - INFO - Progress: frame=10933 fps=276 q=9.0 size= 248576KiB time=00:06:04.33 bitrate=5589.2kbits/s speed= 9.2x elapsed=0:00:39.61` | L125 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:33,022 - INFO - Progress: frame=11176 fps=275 q=8.0 size= 258560KiB time=00:06:12.43 bitrate=5687.3kbits/s speed=9.17x elapsed=0:00:40.62` | L126 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:34,039 - INFO - Progress: frame=11472 fps=275 q=8.0 size= 271104KiB time=00:06:22.30 bitrate=5809.3kbits/s speed=9.18x elapsed=0:00:41.64` | L127 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:35,058 - INFO - Progress: frame=11774 fps=276 q=11.0 size= 283392KiB time=00:06:32.36 bitrate=5916.8kbits/s speed= 9.2x elapsed=0:00:42.66` | L128 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:36,070 - INFO - Progress: frame=12049 fps=276 q=5.0 size= 294656KiB time=00:06:41.53 bitrate=6011.5kbits/s speed=9.19x elapsed=0:00:43.68` | L129 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:32:37,085 - INFO - Progress: frame=12274 fps=275 q=12.0 size= 304128KiB time=00:06:49.03 bitrate=6091.0kbits/s speed=9.15x elapsed=0:00:44.69` | L130 |
|
||||
|
||||
|
||||
</details>
|
||||
</tool-use>
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
Checking the end of the log for completion stats:
|
||||
|
||||
|
||||
---
|
||||
|
||||
<tool-use data-tool-type="grep" data-tool-name="grep">
|
||||
<details>
|
||||
<summary>Tool use: **grep** • Grep for "Successfully encoded|Compression ratio|Processing file" in "logs/encode_20251107_003149.log" • 6 matches</summary>
|
||||
|
||||
Output mode: content
|
||||
|
||||
|
||||
| File | Content | Line |
|
||||
|------|------|------|
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:31:50,612 - INFO - Processing file 1/2: 2025-11-06 graveyard_gameplay.mp4` | L3 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:31:50,956 - INFO - Processing file: input\2025-11-06 graveyard_gameplay.mp4` | L4 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:50:34,966 - INFO - Successfully encoded: output\2025-11-06 graveyard_gameplay.mp4` | L1194 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:50:34,967 - INFO - Compression ratio: 2.78x` | L1196 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:50:34,968 - INFO - Processing file 2/2: 2025-11-06 graveyard.ts.mp4` | L1197 |
|
||||
| `logs/encode_20251107_003149.log` | `2025-11-07 00:50:35,767 - INFO - Processing file: input\2025-11-06 graveyard.ts.mp4` | L1198 |
|
||||
|
||||
|
||||
</details>
|
||||
</tool-use>
|
||||
|
||||
---
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
The log shows why it was faster than expected:
|
||||
|
||||
**Input file specs:**
|
||||
- Resolution: **1280x720** (not 1080p)
|
||||
- Frame rate: **30 fps** (not 60 fps)
|
||||
- Duration: 2h 14m 30s (8070 seconds)
|
||||
|
||||
**Encoding performance:**
|
||||
- Speed: consistently **~9.2x–9.4x**
|
||||
- Total time: ~18 minutes (00:31:50 → 00:50:34)
|
||||
|
||||
**Why it was faster:**
|
||||
|
||||
720p30 vs 1080p60:
|
||||
- Pixels: 921,600 vs 2,073,600 (2.25x fewer)
|
||||
- Frame rate: 30 vs 60 fps (2x fewer frames)
|
||||
- Combined: ~4.5x less work
|
||||
|
||||
So ~9x speed for 720p30 roughly matches ~2x speed for 1080p60, which aligns with your expectation.
|
||||
|
||||
The script is working as expected; the input was recorded at 720p30 due to OBS settings resetting. If you re-encode a true 1080p60 file, expect ~2x speed.
|
||||
|
||||
The encoding completed successfully with a **2.78x compression ratio** (19.10 GB → ~6.87 GB).
|
||||
|
||||
---
|
||||
|
||||
@@ -20,8 +20,7 @@ log_file = os.path.join(log_dir, f"check_{datetime.now().strftime('%Y%m%d_%H%M%S
|
||||
logging.basicConfig(filename=log_file, level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
||||
|
||||
def write_debug_info(message):
|
||||
with open("debug_output.txt", "a", encoding='utf-8') as f:
|
||||
f.write(f"{message}\n")
|
||||
logging.info(message)
|
||||
|
||||
def get_file_info(file_path):
|
||||
try:
|
||||
@@ -107,9 +106,8 @@ def check_file(input_path, output_path):
|
||||
return f"Error checking file: {str(e)}"
|
||||
|
||||
def main():
|
||||
# Clear previous debug output
|
||||
with open("debug_output.txt", "w", encoding='utf-8') as f:
|
||||
f.write("=== Debug Output ===\n")
|
||||
# Start debug section in the log file
|
||||
logging.info("=== Debug Output ===")
|
||||
|
||||
input_dir = "input"
|
||||
output_dir = "output"
|
||||
@@ -139,7 +137,7 @@ def main():
|
||||
# Try to list contents using different methods
|
||||
write_debug_info("\nTrying 'dir' command:")
|
||||
try:
|
||||
result = subprocess.run(['dir', input_dir], capture_output=True, text=True)
|
||||
result = subprocess.run(['cmd', '/c', 'dir', input_dir], capture_output=True, text=True)
|
||||
write_debug_info("Input directory contents (dir command):")
|
||||
write_debug_info(result.stdout)
|
||||
except Exception as e:
|
||||
@@ -162,8 +160,8 @@ def main():
|
||||
except Exception as e:
|
||||
write_debug_info(f"Error with Path.iterdir: {str(e)}")
|
||||
|
||||
print("\nDebug information has been written to debug_output.txt")
|
||||
print("Please check that file to see what's actually in the directories")
|
||||
print(f"\nDebug information has been written to {log_file}")
|
||||
print("Please check that log to see what's actually in the directories")
|
||||
|
||||
# Continue with the rest of the script...
|
||||
print("\nChecking files for inconsistencies...")
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
=== Debug Output ===
|
||||
|
||||
Checking directories at 2025-08-16 01:57:13.833883
|
||||
Input dir: input
|
||||
Output dir: output
|
||||
|
||||
Directory existence check:
|
||||
Input directory exists: True
|
||||
Output directory exists: True
|
||||
|
||||
Trying 'dir' command:
|
||||
Error with dir command: [WinError 2] The system cannot find the file specified
|
||||
|
||||
Trying os.listdir():
|
||||
Input directory contents (os.listdir):
|
||||
Repo 2025.08.14 - 20.49.10.02.DVR.mp4 - Exists: True - Is file: True
|
||||
Repo 2025.08.14 - 20.58.54.03.DVR.mp4 - Exists: True - Is file: True
|
||||
Repo 2025.08.14 - 21.42.52.02.DVR.mp4 - Exists: True - Is file: True
|
||||
Repo 2025.08.14 - 21.58.34.03.DVR.mp4 - Exists: True - Is file: True
|
||||
Repo 2025.08.14 - 22.00.55.04.DVR.mp4 - Exists: True - Is file: True
|
||||
|
||||
Trying Path.iterdir():
|
||||
Input directory contents (Path.iterdir):
|
||||
Repo 2025.08.14 - 20.49.10.02.DVR.mp4 - Exists: True - Is file: True
|
||||
Repo 2025.08.14 - 20.58.54.03.DVR.mp4 - Exists: True - Is file: True
|
||||
Repo 2025.08.14 - 21.42.52.02.DVR.mp4 - Exists: True - Is file: True
|
||||
Repo 2025.08.14 - 21.58.34.03.DVR.mp4 - Exists: True - Is file: True
|
||||
Repo 2025.08.14 - 22.00.55.04.DVR.mp4 - Exists: True - Is file: True
|
||||
Found real file in input: Repo 2025.08.14 - 20.49.10.02.DVR.mp4
|
||||
Found real file in input: Repo 2025.08.14 - 20.58.54.03.DVR.mp4
|
||||
Found real file in input: Repo 2025.08.14 - 21.42.52.02.DVR.mp4
|
||||
Found real file in input: Repo 2025.08.14 - 21.58.34.03.DVR.mp4
|
||||
Found real file in input: Repo 2025.08.14 - 22.00.55.04.DVR.mp4
|
||||
Found real file in output: Repo 2025.08.14 - 20.49.10.02.DVR.mp4
|
||||
Found real file in output: Repo 2025.08.14 - 20.58.54.03.DVR.mp4
|
||||
Found real file in output: Repo 2025.08.14 - 21.42.52.02.DVR.mp4
|
||||
Found real file in output: Repo 2025.08.14 - 21.58.34.03.DVR.mp4
|
||||
Found real file in output: Repo 2025.08.14 - 22.00.55.04.DVR.mp4
|
||||
@@ -5,6 +5,7 @@ import json
|
||||
import logging
|
||||
from datetime import datetime
|
||||
import shutil
|
||||
import time
|
||||
|
||||
# ANSI color codes
|
||||
class Colors:
|
||||
@@ -30,7 +31,14 @@ def get_gpu_selection():
|
||||
log_dir = "logs"
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
log_file = os.path.join(log_dir, f"encode_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log")
|
||||
logging.basicConfig(filename=log_file, level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
||||
|
||||
# Configure logging with Windows-safe settings
|
||||
logging.basicConfig(
|
||||
filename=log_file,
|
||||
level=logging.INFO,
|
||||
format='%(asctime)s - %(levelname)s - %(message)s',
|
||||
filemode='w' # Explicitly set write mode
|
||||
)
|
||||
|
||||
def get_file_info(input_file):
|
||||
cmd = [
|
||||
@@ -106,7 +114,9 @@ def encode_dvr(input_file, output_dir, gpu):
|
||||
# FFmpeg command with NVIDIA HEVC encoder and maximum quality
|
||||
cmd = [
|
||||
'ffmpeg',
|
||||
'-v', 'verbose',
|
||||
'-v', 'info', # Lower verbosity to reduce noise
|
||||
'-stats', # Emit periodic stats
|
||||
'-stats_period', '1.0', # Update stats every 1s (more stable)
|
||||
'-i', str(input_path),
|
||||
'-c:v', 'hevc_nvenc',
|
||||
'-gpu', gpu,
|
||||
@@ -118,8 +128,8 @@ def encode_dvr(input_file, output_dir, gpu):
|
||||
'-aq-strength', '15',
|
||||
'-cq', '0',
|
||||
'-b:v', '10000k',
|
||||
'-maxrate', '10000k',
|
||||
'-bufsize', '20000k',
|
||||
'-maxrate', '5500k',
|
||||
'-bufsize', '11000k',
|
||||
'-c:a', 'copy',
|
||||
'-map', '0',
|
||||
]
|
||||
@@ -130,22 +140,31 @@ def encode_dvr(input_file, output_dir, gpu):
|
||||
cmd.append(str(output_path))
|
||||
|
||||
try:
|
||||
# Run FFmpeg and capture output
|
||||
# Run FFmpeg and capture combined output (avoid dual-pipe deadlocks on Windows)
|
||||
process = subprocess.Popen(
|
||||
cmd,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
universal_newlines=True
|
||||
stderr=subprocess.STDOUT,
|
||||
universal_newlines=True,
|
||||
bufsize=1
|
||||
)
|
||||
|
||||
# Log FFmpeg output in real-time
|
||||
while True:
|
||||
output = process.stderr.readline()
|
||||
if output == '' and process.poll() is not None:
|
||||
|
||||
# Stream output line-by-line from a single pipe
|
||||
for line in iter(process.stdout.readline, ''):
|
||||
if not line:
|
||||
break
|
||||
if output:
|
||||
logging.info(f"FFmpeg: {output.strip()}")
|
||||
print(f"{Colors.PURPLE}FFmpeg: {output.strip()}{Colors.ENDC}")
|
||||
text = line.strip()
|
||||
try:
|
||||
if text.startswith('frame=') or ' fps=' in text:
|
||||
logging.info(f"Progress: {text}")
|
||||
print(f"{Colors.PURPLE}Progress: {text}{Colors.ENDC}")
|
||||
else:
|
||||
logging.info(f"FFmpeg: {text}")
|
||||
print(f"{Colors.GREEN}FFmpeg: {text}{Colors.ENDC}")
|
||||
except (OSError, IOError):
|
||||
pass
|
||||
|
||||
process.wait()
|
||||
|
||||
if process.returncode == 0:
|
||||
# Get output file info
|
||||
|
||||
@@ -118,7 +118,7 @@ def encode_dvr(input_file, output_dir, gpu):
|
||||
'-aq-strength', '15',
|
||||
'-cq', '0',
|
||||
'-b:v', '0',
|
||||
'-maxrate', '10000k',
|
||||
'-maxrate', '5500k',
|
||||
'-c:a', 'copy',
|
||||
'-map', '0',
|
||||
]
|
||||
|
||||
6
repair_mp4.bat
Normal file
6
repair_mp4.bat
Normal file
@@ -0,0 +1,6 @@
|
||||
@echo off
|
||||
python repair_mp4.py
|
||||
pause
|
||||
|
||||
|
||||
|
||||
239
repair_mp4.py
Normal file
239
repair_mp4.py
Normal file
@@ -0,0 +1,239 @@
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime
|
||||
|
||||
# ANSI color codes
|
||||
class Colors:
|
||||
PURPLE = '\033[95m'
|
||||
BLUE = '\033[94m'
|
||||
GREEN = '\033[92m'
|
||||
YELLOW = '\033[93m'
|
||||
RED = '\033[91m'
|
||||
ENDC = '\033[0m'
|
||||
|
||||
# Set up logging
|
||||
log_dir = "logs"
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
log_file = os.path.join(log_dir, f"repair_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log")
|
||||
logging.basicConfig(filename=log_file, level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
||||
|
||||
def check_file_health(input_file):
|
||||
"""Check if MP4 file has issues using ffmpeg"""
|
||||
print(f"\n{Colors.BLUE}Analyzing: {input_file}{Colors.ENDC}")
|
||||
logging.info(f"Analyzing file: {input_file}")
|
||||
|
||||
cmd = [
|
||||
'ffmpeg',
|
||||
'-v', 'error',
|
||||
'-i', str(input_file),
|
||||
'-f', 'null',
|
||||
'-'
|
||||
]
|
||||
|
||||
result = subprocess.run(cmd, capture_output=True, text=True)
|
||||
|
||||
if result.stderr:
|
||||
print(f"{Colors.RED}Issues found:{Colors.ENDC}")
|
||||
for line in result.stderr.split('\n')[:10]: # Show first 10 errors
|
||||
if line.strip():
|
||||
print(f" {Colors.YELLOW}{line}{Colors.ENDC}")
|
||||
logging.warning(f"File has errors: {result.stderr[:500]}")
|
||||
return False
|
||||
else:
|
||||
print(f"{Colors.GREEN}No errors detected{Colors.ENDC}")
|
||||
logging.info("File appears healthy")
|
||||
return True
|
||||
|
||||
def get_file_info(input_file):
|
||||
"""Get basic file info"""
|
||||
cmd = [
|
||||
'ffprobe',
|
||||
'-v', 'error',
|
||||
'-show_entries', 'format=duration,size:stream=codec_name,width,height',
|
||||
'-of', 'json',
|
||||
input_file
|
||||
]
|
||||
result = subprocess.run(cmd, capture_output=True, text=True)
|
||||
try:
|
||||
return json.loads(result.stdout)
|
||||
except:
|
||||
return None
|
||||
|
||||
def repair_method_1_remux(input_file, output_file):
|
||||
"""Method 1: Simple remux (copy streams to new container)"""
|
||||
print(f"\n{Colors.BLUE}Trying Method 1: Remux (copy streams){Colors.ENDC}")
|
||||
logging.info("Attempting repair method 1: Remux")
|
||||
|
||||
cmd = [
|
||||
'ffmpeg',
|
||||
'-v', 'warning',
|
||||
'-i', str(input_file),
|
||||
'-c', 'copy',
|
||||
'-map', '0',
|
||||
'-y',
|
||||
str(output_file)
|
||||
]
|
||||
|
||||
try:
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
|
||||
if result.returncode == 0 and Path(output_file).exists():
|
||||
print(f"{Colors.GREEN}Method 1 successful!{Colors.ENDC}")
|
||||
logging.info("Method 1 successful")
|
||||
return True
|
||||
else:
|
||||
print(f"{Colors.RED}Method 1 failed{Colors.ENDC}")
|
||||
logging.warning(f"Method 1 failed: {result.stderr[:200]}")
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"{Colors.RED}Method 1 error: {e}{Colors.ENDC}")
|
||||
logging.error(f"Method 1 error: {e}")
|
||||
return False
|
||||
|
||||
def repair_method_2_error_concealment(input_file, output_file):
|
||||
"""Method 2: Remux with error concealment"""
|
||||
print(f"\n{Colors.BLUE}Trying Method 2: Error concealment{Colors.ENDC}")
|
||||
logging.info("Attempting repair method 2: Error concealment")
|
||||
|
||||
cmd = [
|
||||
'ffmpeg',
|
||||
'-v', 'warning',
|
||||
'-err_detect', 'ignore_err',
|
||||
'-i', str(input_file),
|
||||
'-c', 'copy',
|
||||
'-map', '0',
|
||||
'-fflags', '+genpts+igndts',
|
||||
'-y',
|
||||
str(output_file)
|
||||
]
|
||||
|
||||
try:
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
|
||||
if result.returncode == 0 and Path(output_file).exists():
|
||||
print(f"{Colors.GREEN}Method 2 successful!{Colors.ENDC}")
|
||||
logging.info("Method 2 successful")
|
||||
return True
|
||||
else:
|
||||
print(f"{Colors.RED}Method 2 failed{Colors.ENDC}")
|
||||
logging.warning(f"Method 2 failed: {result.stderr[:200]}")
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"{Colors.RED}Method 2 error: {e}{Colors.ENDC}")
|
||||
logging.error(f"Method 2 error: {e}")
|
||||
return False
|
||||
|
||||
def repair_method_3_force_keyframes(input_file, output_file):
|
||||
"""Method 3: Force keyframe processing"""
|
||||
print(f"\n{Colors.BLUE}Trying Method 3: Force keyframe processing{Colors.ENDC}")
|
||||
logging.info("Attempting repair method 3: Force keyframe processing")
|
||||
|
||||
cmd = [
|
||||
'ffmpeg',
|
||||
'-v', 'warning',
|
||||
'-fflags', '+discardcorrupt+genpts',
|
||||
'-i', str(input_file),
|
||||
'-c', 'copy',
|
||||
'-map', '0',
|
||||
'-avoid_negative_ts', 'make_zero',
|
||||
'-y',
|
||||
str(output_file)
|
||||
]
|
||||
|
||||
try:
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
|
||||
if result.returncode == 0 and Path(output_file).exists():
|
||||
print(f"{Colors.GREEN}Method 3 successful!{Colors.ENDC}")
|
||||
logging.info("Method 3 successful")
|
||||
return True
|
||||
else:
|
||||
print(f"{Colors.RED}Method 3 failed{Colors.ENDC}")
|
||||
logging.warning(f"Method 3 failed: {result.stderr[:200]}")
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"{Colors.RED}Method 3 error: {e}{Colors.ENDC}")
|
||||
logging.error(f"Method 3 error: {e}")
|
||||
return False
|
||||
|
||||
def repair_file(input_file, output_dir):
|
||||
"""Attempt to repair a damaged MP4 file"""
|
||||
input_path = Path(input_file)
|
||||
output_path = Path(output_dir) / f"{input_path.stem}_repaired{input_path.suffix}"
|
||||
|
||||
print(f"\n{Colors.PURPLE}{'='*60}{Colors.ENDC}")
|
||||
print(f"{Colors.PURPLE}Processing: {input_path.name}{Colors.ENDC}")
|
||||
print(f"{Colors.PURPLE}{'='*60}{Colors.ENDC}")
|
||||
|
||||
# Skip if already repaired
|
||||
if output_path.exists():
|
||||
print(f"{Colors.YELLOW}Already repaired: {output_path.name}{Colors.ENDC}")
|
||||
logging.info(f"Skipping {input_path} - already repaired")
|
||||
return
|
||||
|
||||
# Check file health first
|
||||
is_healthy = check_file_health(str(input_path))
|
||||
|
||||
if is_healthy:
|
||||
print(f"{Colors.GREEN}File appears healthy, no repair needed{Colors.ENDC}")
|
||||
logging.info("File is healthy, skipping")
|
||||
return
|
||||
|
||||
# Try repair methods in sequence
|
||||
methods = [
|
||||
repair_method_1_remux,
|
||||
repair_method_2_error_concealment,
|
||||
repair_method_3_force_keyframes
|
||||
]
|
||||
|
||||
for method in methods:
|
||||
if method(str(input_path), str(output_path)):
|
||||
# Verify the repaired file
|
||||
print(f"\n{Colors.BLUE}Verifying repaired file...{Colors.ENDC}")
|
||||
if check_file_health(str(output_path)):
|
||||
print(f"{Colors.GREEN}✓ Repair successful and verified!{Colors.ENDC}")
|
||||
logging.info(f"Successfully repaired: {output_path}")
|
||||
|
||||
# Show size comparison
|
||||
original_size = input_path.stat().st_size / (1024*1024)
|
||||
repaired_size = output_path.stat().st_size / (1024*1024)
|
||||
print(f"Original: {original_size:.2f} MB → Repaired: {repaired_size:.2f} MB")
|
||||
logging.info(f"Size: {original_size:.2f} MB → {repaired_size:.2f} MB")
|
||||
return
|
||||
else:
|
||||
print(f"{Colors.YELLOW}Repair completed but file still has issues{Colors.ENDC}")
|
||||
logging.warning("Repaired file still has issues")
|
||||
return
|
||||
|
||||
print(f"{Colors.RED}All repair methods failed{Colors.ENDC}")
|
||||
logging.error(f"Failed to repair: {input_path}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
input_dir = "input"
|
||||
output_dir = "output"
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
|
||||
# Get list of MP4 files
|
||||
files = [f for f in os.listdir(input_dir) if f.endswith(('.mp4', '.DVR.mp4'))]
|
||||
total_files = len(files)
|
||||
|
||||
if total_files == 0:
|
||||
print(f"{Colors.YELLOW}No MP4 files found in input directory{Colors.ENDC}")
|
||||
logging.info("No files to process")
|
||||
else:
|
||||
print(f"\n{Colors.BLUE}Found {total_files} MP4 files to check{Colors.ENDC}")
|
||||
logging.info(f"Found {total_files} files to process")
|
||||
|
||||
for i, file in enumerate(files, 1):
|
||||
input_file = os.path.join(input_dir, file)
|
||||
print(f"\n{Colors.BLUE}[{i}/{total_files}]{Colors.ENDC}")
|
||||
repair_file(input_file, output_dir)
|
||||
|
||||
print(f"\n{Colors.GREEN}{'='*60}{Colors.ENDC}")
|
||||
print(f"{Colors.GREEN}Repair process complete!{Colors.ENDC}")
|
||||
print(f"{Colors.GREEN}Check the output directory for repaired files{Colors.ENDC}")
|
||||
print(f"{Colors.GREEN}Log file: {log_file}{Colors.ENDC}")
|
||||
print(f"{Colors.GREEN}{'='*60}{Colors.ENDC}")
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user