Generate subtitles.
Generate subtitles.
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <iostream>
#include <string>
#include <string_view>
#include <vector>
namespace {
std::string formatTimestamp(double seconds)
{
auto const totalMilliseconds =
static_cast<std::int64_t>(std::llround(seconds * 1000.0));
auto const milliseconds = totalMilliseconds % 1000;
auto const totalSeconds = totalMilliseconds / 1000;
char buffer[32];
std::snprintf(buffer, sizeof(buffer), "%02lld:%02lld:%02lld.%03lld",
static_cast<long long>(totalSeconds / 3600),
static_cast<long long>((totalSeconds / 60) % 60),
static_cast<long long>(totalSeconds % 60),
static_cast<long long>(milliseconds));
return buffer;
}
std::string makeAssEvent(int readOrder, std::string_view text,
const char *alignment)
{
std::string event = std::to_string(readOrder);
event += ",0,Default,,0,0,0,,";
event += alignment;
event += text;
return event;
}
const std::string &assEvent,
int64_t pts, int durationMs,
{
if (ec && *ec)
return {};
frame.setStartDisplayTime(0);
frame.setEndDisplayTime(static_cast<uint32_t>(durationMs));
}
}
int main(int argc, char **argv)
{
if (argc < 3) {
std::cerr << "Usage: " << argv[0] << " <input video> <output.mkv|output.ass>\n";
return 1;
}
std::error_code ec;
if (ec) {
std::cerr << "Can't open input: " << ec.message() << '\n';
return 1;
}
if (ec) {
std::cerr << "Can't find streams: " << ec.message() << '\n';
return 1;
}
if (st.mediaType() == AVMEDIA_TYPE_VIDEO) {
vst = st;
break;
}
}
std::cerr << "Video stream not found\n";
return 1;
}
std::cerr << "Can't determine the video frame rate\n";
return 1;
}
double const frameDuration =
static_cast<double>(fps.
getDenominator())
? 0.0
if (codec.isNull()) {
std::cerr << "ASS encoder not found\n";
return 1;
}
if (ec) {
std::cerr << "Can't open the subtitle encoder: " << ec.message() << '\n';
return 1;
}
if (ec) {
std::cerr << "Can't open output: " << ec.message() << '\n';
return 1;
}
bool const subtitleOnly = formatName && std::string_view(formatName) == "ass";
if (!subtitleOnly) {
for (
auto &&ist : ictx.
streams()) {
if (ist.mediaType() != AVMEDIA_TYPE_VIDEO &&
ist.mediaType() != AVMEDIA_TYPE_AUDIO)
continue;
if (ec) {
std::cerr << "Can't add an output stream: " << ec.message() << '\n';
return 1;
}
if (ec) {
std::cerr << "Can't copy stream parameters: " << ec.message() << '\n';
return 1;
}
streamMap[ist.index()] =
static_cast<int>(ost.
index());
}
}
if (ec) {
std::cerr << "Can't add a subtitle stream: " << ec.message() << '\n';
return 1;
}
if (ec) {
std::cerr << "Can't copy codec parameters: " << ec.message() << '\n';
return 1;
}
if (ec) {
std::cerr << "Can't write the output header: " << ec.message() << '\n';
return 1;
}
int const durationMs = static_cast<int>(std::llround(frameDuration * 1000.0));
int readOrder = 0;
std::int64_t nextFrame = 0;
auto emitFrame = [&](std::int64_t frameIndex) {
double const timestamp =
startTime + static_cast<double>(frameIndex) * frameDuration;
auto const pts = static_cast<std::int64_t>(
std::llround(timestamp * 100.0));
auto number = encodeEvent(enc,
makeAssEvent(readOrder++,
"Frame " + std::to_string(frameIndex),
"{\\an1}"),
pts, durationMs, ec);
if (ec) {
std::cerr << "Can't encode the frame number: " << ec.message() << '\n';
return false;
}
auto stamp = encodeEvent(enc,
makeAssEvent(readOrder++,
formatTimestamp(timestamp),
"{\\an3}"),
pts, durationMs, ec);
if (ec) {
std::cerr << "Can't encode the timestamp: " << ec.message() << '\n';
return false;
}
number.setStreamIndex(sst.
index());
if (ec) {
std::cerr << "Can't write the frame number: " << ec.message() << '\n';
return false;
}
stamp.setStreamIndex(sst.
index());
if (ec) {
std::cerr << "Can't write the timestamp: " << ec.message() << '\n';
return false;
}
return true;
};
auto emitUntil = [&](double seconds) {
while (startTime + static_cast<double>(nextFrame) * frameDuration
<= seconds + 1e-9) {
if (!emitFrame(nextFrame))
return false;
++nextFrame;
}
return true;
};
double latestPts = -1.0;
latestPts = std::max(latestPts, pkt.
pts().
seconds());
if (!subtitleOnly) {
if (dstIndex >= 0) {
if (ec) {
std::cerr << "Can't copy a media packet: " << ec.message() << '\n';
return 1;
}
}
}
if (latestPts >= 0.0 && !emitUntil(latestPts))
return 1;
}
if (ec) {
std::cerr << "Read error: " << ec.message() << '\n';
return 1;
}
if (!emitUntil(latestPts))
return 1;
if (ec) {
std::cerr << "Can't write the output trailer: " << ec.message() << '\n';
return 1;
}
std::cout << "Wrote " << nextFrame << " frames at "
<< " fps to " << argv[2] << '\n';
return 0;
}
void open(OptionalErrorCode ec=throws())
Open the codec with the parameters set so far.
void setTimeBase(const Rational &value) noexcept
Set the time base.
void copyFrom(CodecParametersView src, OptionalErrorCode ec=throws())
Copy parameters into this view from another view.
Container context: the entry point for demuxing, muxing and seeking.
Definition formatcontext.h:153
StreamsView streams(OptionalErrorCode ec=throws()) const
All streams as a range, for range-based for and std algorithms.
OutputFormat outputFormat() const
The muxer in use.
void openInput(const std::string &uri, OptionalErrorCode ec=throws())
Open an input and probe its container.
Stream addStream(const Codec &codec, OptionalErrorCode ec=throws())
Add a stream for the given codec.
void writeTrailer(OptionalErrorCode ec=throws())
Write the container trailer and close the output.
void writeHeader(OptionalErrorCode ec=throws())
Write the container header.
void openOutput(const std::string &uri, OptionalErrorCode ec=throws())
Open an output.
void writePacket(OptionalErrorCode ec=throws())
Flush the muxer queue.
void findStreamInfo(OptionalErrorCode ec=throws())
Read the stream parameters of an opened input.
size_t streamsCount() const
Number of streams in the container.
Packet readPacket(OptionalErrorCode ec=throws())
Read the next packet from any stream.
Carries the caller's choice between exceptions and error codes.
Definition averror.h:96
Compressed data and its metadata.
Definition packet.h:110
Timestamp pts() const
Presentation timestamp.
int streamIndex() const
Index of the stream the packet belongs to.
void setStreamIndex(int idx)
Set the stream index.
Rational number: a numerator and a denominator.
Definition rational.h:49
int getDenominator() const noexcept
The denominator.
Definition rational.h:119
int getNumerator() const noexcept
The numerator.
Definition rational.h:113
One stream inside a container.
Definition stream.h:34
CodecParametersView codecParameters() const
Codec parameters of the stream.
void setFrameRate(const Rational &frameRate)
Set the declared frame rate.
Rational frameRate() const
Frame rate declared by the stream.
int index() const
Position of the stream in its container.
Rational averageFrameRate() const
Average frame rate of the stream.
bool isValid() const
Whether the view refers to a stream.
void setTimeBase(const Rational &timeBase)
Set the time base of the stream.
Timestamp startTime() const
Timestamp of the first frame in this stream.
void setAverageFrameRate(const Rational &frameRate)
Set the average frame rate.
void setDefaultSubtitleHeader(OptionalErrorCode ec=throws())
Sets the built-in ASS header accepted by every text subtitle encoder provided by FFmpeg.
Definition codeccontext.h:1940
Encodes subtitle frames into packets.
Definition codeccontext.h:2070
Packet encode(const SubtitleFrame &frame, OptionalErrorCode ec=throws())
Encodes one subtitle frame.
static SubtitleFrame fromAss(std::string_view ass, OptionalErrorCode ec=throws())
Build a frame from one ASS dialogue line.
The Timestamp class represents timestamp value and it timebase.
Definition timestamp.h:25
bool isNoPts() const noexcept
Whether the timestamp means "no timestamp".
bool isValid() const noexcept
Whether the timestamp is usable.
double seconds() const noexcept
The timestamp in seconds.
Codec contexts: opening, configuring, encoding and decoding.
Container format contexts: opening, demuxing, muxing and seeking.
Codec findEncodingCodec(AVCodecID id)
Find an encoder by codec identifier.
void init()
Initialize all subsystems the library needs.
Compressed packets and their side data.
Streams inside a container: parameters, time base and disposition.
Subtitle frames: text and ASS payloads, bitmap rectangles.