Skip to content

About

Convert bitmap subtitles into SubRip format using the macOS Vision framework

Topics

Resources

Contributing

Stars

43 stars

Watchers

2 watching

Forks

Repository files navigation

macSubtitleOCR

License CodeQL Test Lint

Overview

macSubtitleOCR converts bitmap subtitles into the SubRip subtitle format (SRT) using the macOS Vision framework to perform OCR. Currently PGS and VobSub subtitles are supported.

For more details on OCR accuracy, refer to the Accuracy section below.

Release and Nightly builds are provided for arm64, as two tarballs:

  • macSubtitleOCR-<version>.tar.xz has the internal decoder only
  • macSubtitleOCR-ffmpeg-<version>.tar.xz also has the FFmpeg decoder (--ffmpeg-decoder)

The FFmpeg build is self-contained: a minimal FFmpeg is linked into the binary, so it does not need Homebrew or any FFmpeg installed. That FFmpeg reads PGS, VobSub, DVB and XSUB subtitles, in Matroska (.mkv, .mks), MPEG-TS (.ts, .m2ts), MPEG-PS, MP4/MOV and AVI files, PGS .sup files and VobSub .idx/.sub pairs. It is FFmpeg under the LGPL 2.1, built from upstream source by Scripts/build-ffmpeg.sh; the tarball has its license and a NOTICE-FFmpeg.txt giving the FFmpeg version, how it was configured and how to rebuild against another FFmpeg.

macSubtitleOCR --version prints the version a binary was built as (dev for a local build), with (FFmpeg) for a build with the FFmpeg decoder.

To install a download, check its signature, unpack it and clear the quarantine flag macOS sets on downloaded files:

curl -fsSL https://github.com/ecdye.gpg | gpg --import
gpg --verify macSubtitleOCR-<version>.tar.xz.asc macSubtitleOCR-<version>.tar.xz
tar -xJf macSubtitleOCR-<version>.tar.xz
xattr -c macSubtitleOCR
sudo mv macSubtitleOCR /usr/local/bin/

Releases are signed with the key whose fingerprint is 7F79 4EEE 6F48 FC74 EE32 C02A 19D2 33C1 47C7 1648; check that gpg --verify reports it. The binaries are not notarized, so without the xattr step, which clears that flag, macOS refuses to open them ("macSubtitleOCR" cannot be opened because the developer cannot be verified). Any directory on your PATH works in place of /usr/local/bin.

Unfortunately, GitHub Actions doesn't provide a runner I can build x86_64 binaries on, sorry. However, you should be able to compile for x86_64 on your own machine by following the directions in the Building the Project section below.

Features

  • Export raw JSON output from Vision for further analysis
  • Save .png images of subtitles for manual correction of OCR output
  • Optional support for FFmpeg in case of any issues with internal decoder

Supported Formats

  • PGS (.mkv, .mks, .sup)
  • VobSub (.mkv, .mks, .sub, .idx), with the .sub and .idx side by side
  • DVB subtitles (.ts, .mkv) and other bitmap formats FFmpeg can decode, with the FFmpeg decoder (--ffmpeg-decoder)

The format is told by the file extension, in any case (.SUP reads the same as .sup).

Output Files

Each subtitle track is written to track_N.srt (and track_N.json with --json) in the output directory, with either decoder:

  • .mkv, .mks: N is the Matroska track number, as mkvinfo shows it (mkvmerge and mkvextract count from 0 instead, so their track ID is N - 1)
  • .sub, .idx: N is the stream's index: in the .idx
  • .sup: N is 0
  • Other formats, read only by the FFmpeg decoder: N is the FFmpeg stream index

--track N processes only track N, numbered as above; the other tracks are not decoded or recognized at all. It takes a comma-separated list and may be repeated (--track 2,4 or --track 2 --track 4). A number the input has no track for fails the run, listing the tracks it has. With --forced-only, a selected track with no forced subtitles writes no files, as any such track does.

A track that has no subtitles, or none that any text is recognized in, fails: neither its SRT nor its JSON is written. The other tracks are still written, and the run then exits with a non-zero status, as it does when any track fails. A Matroska track with no blocks at all is passed over without failing, unless --track selects it.

--output-name NAME writes NAME.srt (and NAME.json with --json) in the output directory instead of track_N. It takes a file name, not a path, and a trailing .srt is dropped, so --output-name movie.en.srt writes movie.en.srt. It needs exactly one track to be processed: the input's only track, or the one --track selects.

macSubtitleOCR movie.mkv subs --track 3 --output-name movie.en.srt

A caption that fades in or out is often stored as one subtitle per step of the fade, each reading the same. In the SRT, consecutive subtitles with the same text (whitespace aside) are merged into one cue when each starts within a frame of the previous one's end, both have a known end, and both are forced or neither is. The JSON and the --save-images PNGs still have one entry per subtitle bitmap, numbered as before merging.

A cue ends when the stream says it does, or five seconds after it starts if the stream gives no end, and no later than the next cue that starts after it. An end at or before the cue's start is taken for no end, so no cue is written with no length; cues that start together end together.

--save-images writes each subtitle bitmap to images/NAME/subtitle_I.png in the output directory, where NAME is the name of the track's SRT without .srt (track_N, or the --output-name) and I is the number its JSON entry has.

The output directory, and any directory above it, is created when the first file is written into it, so a run that writes nothing creates nothing. A track that writes no files, because it failed or has no forced subtitles with --forced-only, does not touch the files an earlier run wrote for it; each is named in a warning, as is an earlier run's JSON beside an SRT written without --json. They are not removed, since --output-name can name a file that is not this tool's.

Languages

--languages (-l, default en) takes a comma-separated list of languages, as ISO 639-1 (en), ISO 639-2 (eng, fre or fra) or BCP 47 (en-US, zh-Hant, pt-BR) codes. Each is passed to Vision as the identifier Vision uses for that language, so en, eng and en-GB all become en-US, and zh and chi become zh-Hans. A language Vision cannot recognize on this Mac is left out with a warning; if none is left, English is used. Fast mode (--fast-mode, an experimental option that --help does not list) recognizes only English, French, Italian, German, Spanish and Portuguese, so other languages are left out with a warning there too.

A track's language, when the file gives one, is mapped in the same way and put ahead of the languages from --languages, since Vision gives the first language priority; an MKV track with no language is English. The correction of a lone l to I is made only when that first language is English.

Forced Subtitles

Forced subtitles are the ones a player shows even with subtitles turned off, such as translations of signs or of dialogue in another language. With --forced-only, only those are recognized, with either decoder, and a track with none writes no files. A subtitle is forced when:

  • PGS: an object of its display set has the forced flag. With --forced-only, a display set showing forced and other objects together is recognized with only its forced objects, and one showing none takes the caption before it off the screen, as FFmpeg's forced_subs_only shows them
  • VobSub: its subpicture has the forced display command
  • .mkv, .mks: its track has FlagForced set, which makes every subtitle of the track forced, whatever its own flags

With --json, each forced subtitle's entry has "forced": true; other entries have no forced key.

With --forced-only, a VobSub track read by the internal decoder keeps the numbers its subtitles have without it, in its JSON and --save-images PNGs. The PGS decoders, and the FFmpeg decoder for VobSub, read only the forced subtitles in the first place, so theirs are numbered among the forced subtitles alone.

Progress

While tracks are recognized, a line on standard error shows how many subtitles of each are done, such as Track 2: 340/1598 (21%), redrawn in place at most ten times a second. When a track's files are written, its final count is left on a line of its own; warnings are written above the line, never into it.

Progress is shown only when standard error is an interactive terminal, TERM is not dumb and CI is not set, so nothing is added when standard error is redirected to a file or a pipe, or in CI logs. --no-progress turns it off on a terminal too, and --progress shows it even when standard error is not a terminal. Progress never changes the output files.

Building the Project

Important

macSubtitleOCR requires Swift 6.2 or later (Xcode 26 or later) to compile

To make and install the project, follow the directions below:

Build Internal Decoder Only

To build macSubtitleOCR, follow these steps:

git clone https://github.com/ecdye/macSubtitleOCR
cd macSubtitleOCR
swift build --configuration release

Build With FFmpeg Decoder

To build with FFmpeg support, follow these steps:

brew install ffmpeg
git clone https://github.com/ecdye/macSubtitleOCR
cd macSubtitleOCR
USE_FFMPEG=1 swift build --configuration release

This links Homebrew's FFmpeg dynamically, so the binary needs that FFmpeg, at the same major version, wherever it runs. To link a minimal FFmpeg statically instead, as the release builds do, build it with the script (it downloads the FFmpeg source and takes about a minute) and point PKG_CONFIG_PATH at it; Homebrew's FFmpeg is not needed then:

Scripts/build-ffmpeg.sh
PKG_CONFIG_PATH="$PWD/.ffmpeg/install/lib/pkgconfig" USE_FFMPEG=1 swift build --configuration release

Running Tests

swift test
USE_FFMPEG=1 swift test --build-path .build-ffmpeg

The FFmpeg build (USE_FFMPEG=1, which needs brew install ffmpeg) runs every test of the other build, plus those of the FFmpeg decoder and decoderComparison, which compares the two decoders. A separate build path keeps the two builds from rebuilding each other.

internalDecoder and ffmpegDecoder run the command over the bundled Sintel samples and compare what it writes with Tests/Resources/sintel.srt and sintel.json. The SRT must be at least 85% similar and the JSON at least 95%, as Vision reads the same image slightly differently from one machine or macOS release to the next. internalDecoderMatchesBaseline and decoderComparison hold the internal decoder to the scores recorded in Tests/Resources/decoder-baseline.json; Tests/Resources/README.md explains them, how to regenerate the baseline, and how to measure your own samples.

Some tests depend on the machine they run on:

  • recognizesAntiAliasedFrames and frameTooSmallToRecognizeIsEnlarged hold Vision to exact readings that not every Mac reproduces, such as the virtualized runners CI uses, where they are skipped
  • A test that needs mkvmerge is skipped when it is not installed
  • The benchmarks run only when PGS_RLE_BENCHMARK, SUBTITLE_IMAGE_BENCHMARK or VOBSUB_BENCHMARK is set

Accuracy

In general, Vision produces a highly accurate output for almost all subtitles. If you find an edge case with degraded performance, open an issue so it can be investigated.

DVD (VobSub) subtitle bitmaps store alternating rows in two separate fields, independently of whether the video is interlaced. The internal decoder reads each field from its recorded offset and interleaves the rows, including the extra first-field row in odd-height bitmaps. This avoids horizontal striping from misaligned fields; no video deinterlacing is needed for subtitle extraction. VobSub packets extracted directly from MKV also include their header bytes in the packet lengths, so short packets retain all their pixel and control data.

In tests comparing Vision's output with Tesseract, Vision consistently gave better results, particularly with tricky cases like properly recognizing I.

While some tools, like SubtitleEdit, may use binary image compare for marginally better accuracy, Vision offers more flexibility with built-in language support.

Note

A --save-images PNG holds the same pixels the run recognized, but it does not always recognize the same. The file records the image as having straight alpha where the run described it as premultiplied, and Vision answers differently for the two even though they resolve to identical pixels. A saved image is therefore reliable for seeing what was extracted, and not for deciding what Vision should have read from it.

Contribution and TODO

For information on how to contribute to the project, please refer to CONTRIBUTING.md.

If you're interested in working on specific features or improvements, check out issues tagged as enhancements.

References

About

Convert bitmap subtitles into SubRip format using the macOS Vision framework

Topics

Resources

Contributing

Stars

43 stars

Watchers

2 watching

Forks

Releases

Used by

Contributors

Languages