### Install matroska-subtitles using npm Source: https://github.com/mathiasvr/matroska-subtitles/blob/master/README.md This command installs the matroska-subtitles package using npm, making it available for use in your Node.js project. Ensure you have Node.js and npm installed. ```shell npm install matroska-subtitles ``` -------------------------------- ### Basic subtitle parsing example in Node.js Source: https://github.com/mathiasvr/matroska-subtitles/blob/master/README.md This JavaScript code demonstrates the basic usage of the SubtitleParser from the matroska-subtitles library. It sets up event listeners for 'tracks' and 'subtitle' events and pipes a readable stream of an MKV file into the parser. ```javascript const fs = require('fs') const { SubtitleParser } = require('matroska-subtitles') const parser = new SubtitleParser() // first an array of subtitle track information is emitted parser.once('tracks', (tracks) => console.log(tracks)) // afterwards each subtitle is emitted parser.on('subtitle', (subtitle, trackNumber) => console.log('Track ' + trackNumber + ':', subtitle)) fs.createReadStream('Sintel.2010.720p.mkv').pipe(parser) ``` -------------------------------- ### Parse Matroska Subtitles from HTTP Stream (JavaScript) Source: https://github.com/mathiasvr/matroska-subtitles/blob/master/examples/web/index.html This snippet demonstrates parsing subtitle tracks from a Matroska file using the MatroskaSubtitles library. It initializes a SubtitleParser, listens for 'tracks', 'subtitle', and 'file' events, and pipes an HTTP stream to the parser. Dependencies include the 'matroska-subtitles' library and an HTTP stream source. ```javascript const MatroskaSubtitles = require('matroska-subtitles') const httpStream = require('http') // Assuming http module is available console.log(MatroskaSubtitles) const parser = new MatroskaSubtitles.SubtitleParser() // first an array of subtitle track information is emitted parser.once('tracks', (tracks) => console.log(tracks)) // afterwards each subtitle is emitted parser.on('subtitle', (subtitle, trackNumber) => console.log('Track ' + trackNumber + ':', subtitle)) parser.on('file', file => console.log('file:', file)) httpStream.get('../../tests/matroska-test-files/test_files/test5.mkv', res => { res.pipe(parser) }) ``` -------------------------------- ### Structure Subtitle Tracks and Subtitles with SubtitleParser (Node.js) Source: https://context7.com/mathiasvr/matroska-subtitles/llms.txt This example shows how to build a structured collection of subtitle tracks and their associated subtitles using the `SubtitleParser`. It utilizes the 'tracks' event to initialize a map and the 'subtitle' event to populate subtitle entries for each track. Relies on 'fs' and 'matroska-subtitles'. ```javascript const { SubtitleParser } = require('matroska-subtitles') const fs = require('fs') const tracks = new Map() const parser = new SubtitleParser() // Build a structured collection of tracks and their subtitles parser.once('tracks', (subtitleTracks) => { subtitleTracks.forEach((track) => { // Track object properties: // - number: Track identifier (integer) // - language: ISO 639-2 language code or undefined (string) // - type: 'utf8' for SRT, 'ass' or 'ssa' for SubStation formats // - name: Optional display name (string) // - header: SSA/ASS script header for styling (string) tracks.set(track.number, { language: track.language, type: track.type, name: track.name, subtitles: [] }) }) parser.on('subtitle', (subtitle, trackNumber) => { tracks.get(trackNumber).subtitles.push(subtitle) }) }) parser.on('finish', () => { tracks.forEach((track, number) => { console.log(`Track ${number} (${track.language}): ${track.subtitles.length} subtitles`) }) }) fs.createReadStream('movie.mkv').pipe(parser) ``` -------------------------------- ### Implement Seeking in MKV Files with SubtitleStream (Node.js) Source: https://context7.com/mathiasvr/matroska-subtitles/llms.txt This example shows how to use the SubtitleStream class for random access within MKV files, enabling seeking functionality. It initializes a stream, preserves track metadata, and reinitializes the stream for a new offset, allowing subtitle parsing from a specific point in the file. Dependencies include 'fs', 'dev-null', and 'matroska-subtitles'. ```javascript const fs = require('fs') const devnull = require('dev-null') const { SubtitleStream } = require('matroska-subtitles') const filePath = 'movie.mkv' // Initial stream instance must start at offset 0 to read track metadata let subtitleStream = new SubtitleStream() subtitleStream.once('tracks', (tracks) => { console.log('Found tracks:', tracks) // Seek offset in bytes (obtained from video player or index) const seekOffset = 25882901 // Create new SubtitleStream inheriting metadata from previous instance // This automatically ends the previous stream subtitleStream = new SubtitleStream(subtitleStream) subtitleStream.on('subtitle', (subtitle, trackNumber) => { console.log('Track ' + trackNumber + ':', subtitle) }) // Open new read stream starting at seek position fs.createReadStream(filePath, { start: seekOffset }) .pipe(subtitleStream) .pipe(devnull()) // Passthrough requires a destination }) // Start initial parsing from beginning of file const fileStream = fs.createReadStream(filePath) fileStream.pipe(subtitleStream).pipe(devnull()) ``` -------------------------------- ### Format Subtitle Event Data with SubtitleParser (Node.js) Source: https://context7.com/mathiasvr/matroska-subtitles/llms.txt Illustrates how to process the 'subtitle' event from `SubtitleParser` to format and display subtitle text with calculated start and end times. It handles both basic SRT subtitle objects and extended SSA/ASS subtitle objects, including styling properties. Requires 'fs' and 'matroska-subtitles'. ```javascript const { SubtitleParser } = require('matroska-subtitles') const fs = require('fs') const parser = new SubtitleParser() parser.on('subtitle', (subtitle, trackNumber) => { // Basic subtitle object (SRT format): // { // text: 'Subtitle text content', // time: 12500, // start time in milliseconds // duration: 2000 // duration in milliseconds // } // Extended subtitle object (SSA/ASS format): // { // text: 'Subtitle text with {\b1}formatting{\b0}', // time: 12500, // duration: 2000, // layer: '0', // rendering layer // style: 'Default', // style name from header // name: 'Actor', // actor/character name // marginL: '0000', // left margin override // marginR: '0000', // right margin override // marginV: '0000', // vertical margin override // effect: '' // transition effect // } const startTime = new Date(subtitle.time).toISOString().substr(11, 12) const endTime = new Date(subtitle.time + subtitle.duration).toISOString().substr(11, 12) console.log(`[${startTime} --> ${endTime}] ${subtitle.text}`) }) fs.createReadStream('anime.mkv').pipe(parser) ``` -------------------------------- ### Extract All Subtitles from MKV to SRT (Node.js) Source: https://context7.com/mathiasvr/matroska-subtitles/llms.txt This Node.js example extracts all subtitle tracks from an MKV file, groups them by language, and saves each track as a separate SRT file. It utilizes the 'matroska-subtitles' library for parsing and 'fs' for file operations. The output SRT files are named based on the track number and language code. ```javascript const fs = require('fs') const { SubtitleParser } = require('matroska-subtitles') function formatSrtTime(ms) { const hours = Math.floor(ms / 3600000) const minutes = Math.floor((ms % 3600000) / 60000) const seconds = Math.floor((ms % 60000) / 1000) const milliseconds = ms % 1000 return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')},${String(milliseconds).padStart(3, '0')}` } function extractSubtitles(inputFile, outputDir) { const trackData = new Map() const parser = new SubtitleParser() parser.once('tracks', (tracks) => { console.log(`Found ${tracks.length} subtitle track(s)`) tracks.forEach(track => { trackData.set(track.number, { info: track, subtitles: [] }) }) parser.on('subtitle', (subtitle, trackNumber) => { trackData.get(trackNumber).subtitles.push(subtitle) }) }) parser.on('finish', () => { if (!fs.existsSync(outputDir)) { fs.mkdirSync(outputDir, { recursive: true }) } trackData.forEach((data, trackNum) => { const lang = data.info.language || 'und' const outputFile = `${outputDir}/subtitles_track${trackNum}_${lang}.srt` let srtContent = '' data.subtitles.forEach((sub, index) => { const startTime = formatSrtTime(sub.time) const endTime = formatSrtTime(sub.time + sub.duration) srtContent += `${index + 1}\n${startTime} --> ${endTime}\n${sub.text}\n\n` }) fs.writeFileSync(outputFile, srtContent) console.log(`Saved: ${outputFile} (${data.subtitles.length} entries)`) }) }) fs.createReadStream(inputFile).pipe(parser) } // Usage extractSubtitles('movie.mkv', './output') ``` -------------------------------- ### Individual subtitle event format Source: https://github.com/mathiasvr/matroska-subtitles/blob/master/README.md This JavaScript object represents the format of the 'subtitle' event emitted by the SubtitleParser. It contains the subtitle text, its start time in milliseconds, and its duration in milliseconds. ```javascript { text: 'This blade has a dark past.', time: 107250, // ms duration: 1970 // ms } ``` -------------------------------- ### Browser Usage of Matroska Subtitles via CDN Source: https://context7.com/mathiasvr/matroska-subtitles/llms.txt This HTML snippet demonstrates how to use the matroska-subtitles library in a web browser by including it via a CDN. It exposes global `MatroskaSubtitles` object for `SubtitleParser` and `SubtitleStream`. It requires a streaming HTTP library like `stream-http` for fetching video data. The example shows how to parse subtitles and display them on the page. ```html MKV Subtitle Extraction
``` -------------------------------- ### Initializing SubtitleStream for random access Source: https://github.com/mathiasvr/matroska-subtitles/blob/master/README.md This JavaScript code demonstrates the initialization of the SubtitleStream class for random access within MKV streams. It shows how to create a new stream, potentially from an existing one, to seek to different positions. ```javascript const { SubtitleStream } = require('matroska-subtitles') let subtitleStream = new SubtitleStream() subtitleStream.once('tracks', (tracks) => { // close the old subtitle stream and open a new at a different stream offset subtitleStream = new SubtitleStream(subtitleStream) }) ``` -------------------------------- ### Parse Subtitles from MKV Stream with SubtitleParser (Node.js) Source: https://context7.com/mathiasvr/matroska-subtitles/llms.txt Demonstrates how to use the `SubtitleParser` class to extract subtitle tracks and individual subtitle entries from an MKV file stream. It listens for 'tracks' and 'subtitle' events to process the parsed data. Requires the 'fs' and 'matroska-subtitles' modules. ```javascript const fs = require('fs') const { SubtitleParser } = require('matroska-subtitles') const parser = new SubtitleParser() // Emitted once with array of all subtitle tracks found parser.once('tracks', (tracks) => { console.log(tracks) // Output: // [ // { number: 3, language: 'eng', type: 'utf8', name: 'English(US)' }, // { number: 4, language: 'jpn', type: 'ass', header: '[Script Info]\r\n...' } // ] }) // Emitted for each subtitle entry parser.on('subtitle', (subtitle, trackNumber) => { console.log('Track ' + trackNumber + ':', subtitle) // Output: // Track 3: { // text: 'This blade has a dark past.', // time: 107250, // start time in milliseconds // duration: 1970 // duration in milliseconds // } }) // Handle stream completion parser.on('finish', () => { console.log('Parsing complete') }) // Pipe MKV file stream to parser fs.createReadStream('video.mkv').pipe(parser) ``` -------------------------------- ### Extract Embedded Attachments from MKV Files (Node.js) Source: https://context7.com/mathiasvr/matroska-subtitles/llms.txt This snippet demonstrates how to use the SubtitleParser to extract embedded files, such as fonts, from an MKV file. It listens for the 'file' event, checks the mimetype, and saves font files to a specified directory. Dependencies include 'fs', 'path', and 'matroska-subtitles'. ```javascript const fs = require('fs') const path = require('path') const { SubtitleParser } = require('matroska-subtitles') const parser = new SubtitleParser() const outputDir = './extracted-fonts' // Create output directory if (!fs.existsSync(outputDir)) { fs.mkdirSync(outputDir, { recursive: true }) } // Extract embedded files (fonts, images, etc.) parser.on('file', (file) => { // File object structure: // { // filename: 'Arial.ttf', // mimetype: 'application/x-truetype-font', // data: Buffer() [Uint8Array] // } console.log(`Found embedded file: ${file.filename} (${file.mimetype})`) // Save font files to disk if (file.mimetype.includes('font')) { const outputPath = path.join(outputDir, file.filename) fs.writeFileSync(outputPath, file.data) console.log(`Saved: ${outputPath}`) } }) parser.on('finish', () => { console.log('Extraction complete') }) fs.createReadStream('styled-subtitles.mkv').pipe(parser) ``` -------------------------------- ### Include matroska-subtitles via CDN in HTML Source: https://github.com/mathiasvr/matroska-subtitles/blob/master/README.md This HTML script tag includes the minified version of the matroska-subtitles library directly from a CDN. This is useful for front-end projects or when not using a module bundler. ```html ``` -------------------------------- ### Subtitle track information format Source: https://github.com/mathiasvr/matroska-subtitles/blob/master/README.md This JavaScript object array represents the format of the 'tracks' event emitted by the SubtitleParser. Each object details a subtitle track, including its number, language, type, and an optional header or name. ```javascript [ { number: 3, language: 'eng', type: 'utf8', name: 'English(US)' }, { number: 4, language: 'ass', header: '[Script Info]\r\n...' } ] ``` -------------------------------- ### Extracting embedded files with SubtitleParser Source: https://github.com/mathiasvr/matroska-subtitles/blob/master/README.md This JavaScript code snippet shows how to listen for the 'file' event emitted by the SubtitleParser. This event is used to retrieve embedded files from the MKV, such as subtitle fonts. ```javascript parser.on('file', file => console.log('file:', file)) ``` -------------------------------- ### Embedded file data format Source: https://github.com/mathiasvr/matroska-subtitles/blob/master/README.md This JavaScript object represents the structure of the 'file' event data emitted by the SubtitleParser. It includes the filename, MIME type, and the file data as a Buffer (Uint8Array). ```javascript { filename: 'Arial.ttf', mimetype: 'application/x-truetype-font', data: Buffer() [Uint8Array] } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.