Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

I have several different .mkv files made from DVDs which have integrated chapters in the…

  1. User

    I have several different .mkv files made from DVDs which have integrated chapters in the form of a chapters.xml file. I want to extract them and convert them from 25fps to 24fps. How can I do all .mkv files at once? Doesn't matter if script is python, batch or powershell, as long as it can run on Windows 10.

  2. Assistant

    To process all .mkv files at once, you can use a batch script along with Python to automate the extraction, adjustment, and reintegration of chapters. Here's how you can do it:

    Requirements:

    • Install MKVToolNix which includes mkvextract, mkvmerge, and mkvpropedit tools.
    • Ensure Python is installed on your system.

    Steps:

    1. Create a Batch Script: Create a new text file and save it with a .bat extension, e.g., adjust_chapters.bat. Copy the following script into it:

      @echo off
      
      for %%f in (*.mkv) do (
          echo Processing %%f
          set "basename=%%~nf"
          mkvextract chapters "%%f" "%basename%_chapters.xml"
          
          python adjust_chapters_xml.py "%basename%_chapters.xml" "%basename%_adjusted_chapters.xml"
          
          mkvpropedit "%%f" --chapters "%basename%_adjusted_chapters.xml"
      
          rem Optionally, delete temporary files
          rem del "%basename%_chapters.xml" "%basename%_adjusted_chapters.xml"
      )
      

      This script loops over all .mkv files in the current directory, extracts their chapters to an XML file, adjusts the timestamps, and replaces the chapters in the original .mkv files.

    2. Create the Python Script: Create another text file, save it as adjust_chapters_xml.py, and copy the following Python code into it:

      import sys
      import xml.etree.ElementTree as ET
      
      def adjust_timecode(timecode_str):
          h, m, s = timecode_str.strip().split(':')
          s_parts = s.split('.')
          seconds = int(s_parts[0])
          if len(s_parts) > 1:
              fraction_str = s_parts[1]  # May be up to 9 digits
              # Pad or trim to 9 digits (nanoseconds)
              fraction_str = (fraction_str + '0'*9)[:9]
              fraction_ns = int(fraction_str)
          else:
              fraction_ns = 0
          total_ns = ((int(h)*3600 + int(m)*60 + seconds) * int(1e9)) + fraction_ns
          # Adjust timecode
          adjusted_ns = int(total_ns * (25 / 24))
          # Convert adjusted_ns back to timecode string
          h_new = adjusted_ns // (3600 * int(1e9))
          adjusted_ns %= 3600 * int(1e9)
          m_new = adjusted_ns // (60 * int(1e9))
          adjusted_ns %= 60 * int(1e9)
          s_new = adjusted_ns // int(1e9)
          ns_new = adjusted_ns % int(1e9)
          # Remove trailing zeros in ns_new
          fraction_new_str = f"{ns_new:09d}".rstrip('0')
          if fraction_new_str == '':
              fraction_new_str = '0'
          timecode_new = f"{int(h_new):02d}:{int(m_new):02d}:{int(s_new):02d}.{fraction_new_str}"
          return timecode_new
      
      if len(sys.argv) != 3:
          print("Usage: adjust_chapters_xml.py inputfile outputfile")
          sys.exit(1)
      
      inputfile = sys.argv[1]
      outputfile = sys.argv[2]
      
      tree = ET.parse(inputfile)
      root = tree.getroot()
      
      for elem in root.iter('ChapterTimeStart'):
          timecode = elem.text
          adjusted_timecode = adjust_timecode(timecode)
          elem.text = adjusted_timecode
      
      tree.write(outputfile, encoding='utf-8', xml_declaration=True)
      

      This script reads the chapters.xml file, adjusts each <ChapterTimeStart> timestamp by multiplying it by 25/24 to convert from 25fps to 24fps, and writes the adjusted chapters to a new XML file.

    3. Run the Batch Script: Place both scripts in the directory containing your .mkv files and double-click the adjust_chapters.bat script to run it. It will process all the .mkv files in the directory.

    4. Optional Cleanup: The batch script includes commented lines (rem del ...) to delete the temporary chapters files after processing. You can uncomment these lines by removing the rem prefix if you want the script to delete the temporary files automatically.

    Explanation of the Process:

    • Extract Chapters: The batch script uses mkvextract to extract the chapters from each .mkv file into an XML file named <basename>_chapters.xml.

    • Adjust Timestamps: The Python script adjust_chapters_xml.py reads the extracted XML file, adjusts each timestamp by multiplying it by 25/24 (which accounts for the frame rate change from 25fps to 24fps), and writes the adjusted timestamps to a new XML file named <basename>_adjusted_chapters.xml.

    • Replace Chapters: The batch script then replaces the chapters in the original .mkv file with the adjusted chapters using mkvpropedit.

    Important Notes:

    • Backup Original Files: Since this process modifies the original .mkv files, it's highly recommended to back up your files before running the script to prevent any accidental data loss.

    • Accuracy: The Python script handles timestamps with nanosecond precision to ensure accurate adjustments.

    • Dependencies: Make sure that the mkvextract, mkvpropedit, and Python are accessible from the command line. You may need to add MKVToolNix and Python to your system's PATH environment variable.

    Example Usage:

    1. Place adjust_chapters.bat and adjust_chapters_xml.py in the directory with your .mkv files.

    2. Open Command Prompt and navigate to the directory containing the files.

    3. Run the batch script:

      adjust_chapters.bat
      

      or simply double-click the adjust_chapters.bat file.

    All your .mkv files in the directory will have their chapters adjusted from 25fps to 24fps.


    This method automates the process using batch scripting and Python, allowing you to adjust the chapters in multiple .mkv files efficiently.