I have several different .mkv files with chapters.xml files integrated that I need to extract and convert them from 25fps to 24fps. How can I do that with a script? Have no preferences for which script, it can be powershell, python, batch, anything, just as long as I can run it on Windows 10.
Assistant
To automate the process of extracting chapters from multiple .mkv files, converting the chapter timestamps from 25fps to 24fps, and remuxing the files with the adjusted chapters, you can use a Python script along with the MKVToolNix suite (which includes mkvextract and mkvmerge).
Prerequisites:
Install MKVToolNix: Download and install MKVToolNix for Windows from the official website. During installation, make sure to add MKVToolNix to your system's PATH so that mkvextract and mkvmerge can be called from the command line.
Install Python 3: If you don't have Python installed, download and install it from python.org. Make sure to check the option to add Python to your PATH during installation.
Python Script:
Save the following script as adjust_chapters.py:
python
import os
import subprocess
from xml.dom import minidom
def adjust_timestamp(time_str, factor):
# Convert time_str 'HH:MM:SS.nnnnnnnnn' to seconds
hh, mm, ss = time_str.split(':')
ss_split = ss.split('.')
ss_int = ss_split[0]
ns = ss_split[1] if len(ss_split) > 1 else '0'
total_seconds = int(hh)*3600 + int(mm)*60 + int(ss_int) + int(ns)/1e9
adjusted_seconds = total_seconds * factor
# Now convert adjusted_seconds back to time string
adjusted_total_ns = int(round(adjusted_seconds * 1e9))
adjusted_hh = adjusted_total_ns // (3600 * 1e9)
adjusted_mm = (adjusted_total_ns % (3600 * 1e9)) // (60 * 1e9)
adjusted_ss = (adjusted_total_ns % (60 * 1e9)) // 1e9
adjusted_ns = adjusted_total_ns % 1e9
adjusted_time_str = "{:02d}:{:02d}:{:02d}.{:09d}".format(
int(adjusted_hh), int(adjusted_mm), int(adjusted_ss), int(adjusted_ns))
return adjusted_time_str
def process_chapters_xml(xmlfile, factor):
# Read and parse XML
xmldoc = minidom.parse(xmlfile)
# For each ChapterTimeStart and ChapterTimeEnd, adjust the time
chapter_times = xmldoc.getElementsByTagName('ChapterTimeStart') + xmldoc.getElementsByTagName('ChapterTimeEnd')
for time_node in chapter_times:
old_time = time_node.firstChild.nodeValue
new_time = adjust_timestamp(old_time, factor)
time_node.firstChild.nodeValue = new_time
# Save the modified xml
with open(xmlfile, 'w', encoding='utf-8') as f:
xmldoc.writexml(f, encoding='utf-8')
return
def main():
import sys
directory = sys.argv[1] if len(sys.argv) > 1 else '.'
factor = 25 / 24
for filename in os.listdir(directory):
if filename.lower().endswith('.mkv'):
mkvfile = os.path.join(directory, filename)
base_name = os.path.splitext(filename)[0]
chapters_xml = os.path.join(directory, base_name + '_chapters.xml')
# Extract chapters
try:
result = subprocess.run(['mkvextract', 'chapters', mkvfile, '--simple'], capture_output=True, text=True)
if result.returncode != 0:
print(f"Error extracting chapters from {filename}: {result.stderr}")
continue
with open(chapters_xml, 'w', encoding='utf-8') as f:
f.write(result.stdout)
except Exception as e:
print(f"Error extracting chapters from {filename}: {e}")
continue
# Process chapters.xml
process_chapters_xml(chapters_xml, factor)
# Now remux the mkv file with the new chapters
mkvfile_new = os.path.join(directory, base_name + '_24fps.mkv')
cmd_merge = ['mkvmerge', '-o', mkvfile_new, '--chapters', chapters_xml, mkvfile]
try:
result = subprocess.run(cmd_merge, check=True, capture_output=True, text=True)
if result.returncode != 0:
print(f"Error remuxing {filename}: {result.stderr}")
continue
except Exception as e:
print(f"Error remuxing {filename}: {e}")
continue
print(f"Processed {filename}, output file is {mkvfile_new}")
return
if __name__ == '__main__':
main()
Explanation of the Script:
adjust_timestamp: This function converts a time string from the format HH:MM:SS.nnnnnnnnn to total seconds, adjusts it by the specified factor (25/24), and then converts it back to the time string format.
process_chapters_xml: This function parses the chapters.xml file, finds all chapter timestamps, adjusts them using adjust_timestamp, and then writes the changes back to the XML file.
main: The main function iterates over all .mkv files in the specified directory, extracts the chapters, adjusts the timestamps, and remuxes the MKV file with the new chapters.
Running the Script:
Open Command Prompt:
Press Win + R, type cmd, and press Enter.
Navigate to the Directory:
Use the cd command to navigate to the directory containing your .mkv files and the adjust_chapters.py script. For example:
code
cd C:\path\to\your\directory
Run the Script:
To process files in the current directory:
code
python adjust_chapters.py
To process files in a specific directory:
code
python adjust_chapters.py "C:\path\to\mkv\files"
Important Notes:
MKVToolNix in PATH: Ensure that the mkvextract and mkvmerge commands are accessible from the command line. If they are not, you will need to provide the full path to these executables in the script.
File Names: The script creates new MKV files with _24fps appended to the original file name. For example, example.mkv will produce example_24fps.mkv.
Backups: The original .mkv files are not modified or deleted. However, always make sure to have backups of your important files before running batch operations.
Error Handling: The script includes basic error handling to report issues with extracting chapters or remuxing files. Check the command prompt output for any error messages.
Assistance with XML Namespaces (if needed):
If your chapters.xml files include XML namespaces, you may need to adjust the process_chapters_xml function to handle them correctly.
Script Adjustments for Namespaces:
If the ChapterTimeStart and ChapterTimeEnd elements are within a namespace, the tags will include the namespace URI. You can adjust the way you access these elements using the element.getElementsByTagNameNS method or use XPath with namespace awareness.
Final Remarks:
This script provides an automated way to process multiple .mkv files, adjust the chapter timestamps from 25fps to 24fps, and remux the files with the new chapters. It's written in Python for ease of use and clarity, and it should run smoothly on Windows 10 provided the prerequisites are met.
Feel free to modify the script to suit your specific needs, such as adjusting the output file naming convention or adding additional logging and error handling.