]> git.sesse.net Git - ffmpeg/blob - libavcodec/ttmlenc.c
avcodec: Remove deprecated ASS with inline timing
[ffmpeg] / libavcodec / ttmlenc.c
1 /*
2  * TTML subtitle encoder
3  * Copyright (c) 2020 24i
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * TTML subtitle encoder
25  * @see https://www.w3.org/TR/ttml1/
26  * @see https://www.w3.org/TR/ttml2/
27  * @see https://www.w3.org/TR/ttml-imsc/rec
28  */
29
30 #include "avcodec.h"
31 #include "internal.h"
32 #include "libavutil/avstring.h"
33 #include "libavutil/bprint.h"
34 #include "libavutil/internal.h"
35 #include "ass_split.h"
36 #include "ass.h"
37 #include "ttmlenc.h"
38
39 typedef struct {
40     AVCodecContext *avctx;
41     ASSSplitContext *ass_ctx;
42     AVBPrint buffer;
43 } TTMLContext;
44
45 static void ttml_text_cb(void *priv, const char *text, int len)
46 {
47     TTMLContext *s = priv;
48     AVBPrint cur_line = { 0 };
49     AVBPrint *buffer = &s->buffer;
50
51     av_bprint_init(&cur_line, len, AV_BPRINT_SIZE_UNLIMITED);
52
53     av_bprint_append_data(&cur_line, text, len);
54     if (!av_bprint_is_complete(&cur_line)) {
55         av_log(s->avctx, AV_LOG_ERROR,
56                "Failed to move the current subtitle dialog to AVBPrint!\n");
57         av_bprint_finalize(&cur_line, NULL);
58         return;
59     }
60
61
62     av_bprint_escape(buffer, cur_line.str, NULL, AV_ESCAPE_MODE_XML,
63                      0);
64
65     av_bprint_finalize(&cur_line, NULL);
66 }
67
68 static void ttml_new_line_cb(void *priv, int forced)
69 {
70     TTMLContext *s = priv;
71
72     av_bprintf(&s->buffer, "<br/>");
73 }
74
75 static const ASSCodesCallbacks ttml_callbacks = {
76     .text             = ttml_text_cb,
77     .new_line         = ttml_new_line_cb,
78 };
79
80 static int ttml_encode_frame(AVCodecContext *avctx, uint8_t *buf,
81                              int bufsize, const AVSubtitle *sub)
82 {
83     TTMLContext *s = avctx->priv_data;
84     ASSDialog *dialog;
85     int i;
86
87     av_bprint_clear(&s->buffer);
88
89     for (i=0; i<sub->num_rects; i++) {
90         const char *ass = sub->rects[i]->ass;
91
92         if (sub->rects[i]->type != SUBTITLE_ASS) {
93             av_log(avctx, AV_LOG_ERROR, "Only SUBTITLE_ASS type supported.\n");
94             return AVERROR(EINVAL);
95         }
96
97             dialog = ff_ass_split_dialog2(s->ass_ctx, ass);
98             if (!dialog)
99                 return AVERROR(ENOMEM);
100
101             if (dialog->style) {
102                 av_bprintf(&s->buffer, "<span region=\"");
103                 av_bprint_escape(&s->buffer, dialog->style, NULL,
104                                  AV_ESCAPE_MODE_XML,
105                                  AV_ESCAPE_FLAG_XML_DOUBLE_QUOTES);
106                 av_bprintf(&s->buffer, "\">");
107             }
108
109             {
110                 int ret = ff_ass_split_override_codes(&ttml_callbacks, s,
111                                                       dialog->text);
112                 int log_level = (ret != AVERROR_INVALIDDATA ||
113                                  avctx->err_recognition & AV_EF_EXPLODE) ?
114                                 AV_LOG_ERROR : AV_LOG_WARNING;
115
116                 if (ret < 0) {
117                     av_log(avctx, log_level,
118                            "Splitting received ASS dialog text %s failed: %s\n",
119                            dialog->text,
120                            av_err2str(ret));
121
122                     if (log_level == AV_LOG_ERROR) {
123                         ff_ass_free_dialog(&dialog);
124                         return ret;
125                     }
126                 }
127
128                 if (dialog->style)
129                     av_bprintf(&s->buffer, "</span>");
130
131                 ff_ass_free_dialog(&dialog);
132             }
133     }
134
135     if (!av_bprint_is_complete(&s->buffer))
136         return AVERROR(ENOMEM);
137     if (!s->buffer.len)
138         return 0;
139
140     // force null-termination, so in case our destination buffer is
141     // too small, the return value is larger than bufsize minus null.
142     if (av_strlcpy(buf, s->buffer.str, bufsize) > bufsize - 1) {
143         av_log(avctx, AV_LOG_ERROR, "Buffer too small for TTML event.\n");
144         return AVERROR_BUFFER_TOO_SMALL;
145     }
146
147     return s->buffer.len;
148 }
149
150 static av_cold int ttml_encode_close(AVCodecContext *avctx)
151 {
152     TTMLContext *s = avctx->priv_data;
153
154     ff_ass_split_free(s->ass_ctx);
155
156     av_bprint_finalize(&s->buffer, NULL);
157
158     return 0;
159 }
160
161 static const char *ttml_get_display_alignment(int alignment)
162 {
163     switch (alignment) {
164     case 1:
165     case 2:
166     case 3:
167         return "after";
168     case 4:
169     case 5:
170     case 6:
171         return "center";
172     case 7:
173     case 8:
174     case 9:
175         return "before";
176     default:
177         return NULL;
178     }
179 }
180
181 static const char *ttml_get_text_alignment(int alignment)
182 {
183     switch (alignment) {
184     case 1:
185     case 4:
186     case 7:
187         return "left";
188     case 2:
189     case 5:
190     case 8:
191         return "center";
192     case 3:
193     case 6:
194     case 9:
195         return "right";
196     default:
197         return NULL;
198     }
199 }
200
201 static void ttml_get_origin(ASSScriptInfo script_info, ASSStyle style,
202                            int *origin_left, int *origin_top)
203 {
204     *origin_left = av_rescale(style.margin_l, 100, script_info.play_res_x);
205     *origin_top  =
206         av_rescale((style.alignment >= 7) ? style.margin_v : 0,
207                    100, script_info.play_res_y);
208 }
209
210 static void ttml_get_extent(ASSScriptInfo script_info, ASSStyle style,
211                            int *width, int *height)
212 {
213     *width  = av_rescale(script_info.play_res_x - style.margin_r,
214                          100, script_info.play_res_x);
215     *height = av_rescale((style.alignment <= 3) ?
216                          script_info.play_res_y - style.margin_v :
217                          script_info.play_res_y,
218                          100, script_info.play_res_y);
219 }
220
221 static int ttml_write_region(AVCodecContext *avctx, AVBPrint *buf,
222                              ASSScriptInfo script_info, ASSStyle style)
223 {
224     const char *display_alignment = NULL;
225     const char *text_alignment = NULL;
226     int origin_left = 0;
227     int origin_top  = 0;
228     int width = 0;
229     int height = 0;
230
231     if (!style.name) {
232         av_log(avctx, AV_LOG_ERROR, "Subtitle style name not set!\n");
233         return AVERROR_INVALIDDATA;
234     }
235
236     if (style.font_size < 0) {
237         av_log(avctx, AV_LOG_ERROR, "Invalid font size for TTML: %d!\n",
238                style.font_size);
239         return AVERROR_INVALIDDATA;
240     }
241
242     if (style.margin_l < 0 || style.margin_r < 0 || style.margin_v < 0) {
243         av_log(avctx, AV_LOG_ERROR,
244                "One or more negative margin values in subtitle style: "
245                "left: %d, right: %d, vertical: %d!\n",
246                style.margin_l, style.margin_r, style.margin_v);
247         return AVERROR_INVALIDDATA;
248     }
249
250     display_alignment = ttml_get_display_alignment(style.alignment);
251     text_alignment = ttml_get_text_alignment(style.alignment);
252     if (!display_alignment || !text_alignment) {
253         av_log(avctx, AV_LOG_ERROR,
254                "Failed to convert ASS style alignment %d of style %s to "
255                "TTML display and text alignment!\n",
256                style.alignment,
257                style.name);
258         return AVERROR_INVALIDDATA;
259     }
260
261     ttml_get_origin(script_info, style, &origin_left, &origin_top);
262     ttml_get_extent(script_info, style, &width, &height);
263
264     av_bprintf(buf, "      <region xml:id=\"");
265     av_bprint_escape(buf, style.name, NULL, AV_ESCAPE_MODE_XML,
266                      AV_ESCAPE_FLAG_XML_DOUBLE_QUOTES);
267     av_bprintf(buf, "\"\n");
268
269     av_bprintf(buf, "        tts:origin=\"%d%% %d%%\"\n",
270                origin_left, origin_top);
271     av_bprintf(buf, "        tts:extent=\"%d%% %d%%\"\n",
272                width, height);
273
274     av_bprintf(buf, "        tts:displayAlign=\"");
275     av_bprint_escape(buf, display_alignment, NULL, AV_ESCAPE_MODE_XML,
276                      AV_ESCAPE_FLAG_XML_DOUBLE_QUOTES);
277     av_bprintf(buf, "\"\n");
278
279     av_bprintf(buf, "        tts:textAlign=\"");
280     av_bprint_escape(buf, text_alignment, NULL, AV_ESCAPE_MODE_XML,
281                      AV_ESCAPE_FLAG_XML_DOUBLE_QUOTES);
282     av_bprintf(buf, "\"\n");
283
284     // if we set cell resolution to our script reference resolution,
285     // then a single line is a single "point" on our canvas. Thus, by setting
286     // our font size to font size in cells, we should gain a similar enough
287     // scale without resorting to explicit pixel based font sizing, which is
288     // frowned upon in the TTML community.
289     av_bprintf(buf, "        tts:fontSize=\"%dc\"\n",
290                style.font_size);
291
292     if (style.font_name) {
293         av_bprintf(buf, "        tts:fontFamily=\"");
294         av_bprint_escape(buf, style.font_name, NULL, AV_ESCAPE_MODE_XML,
295                          AV_ESCAPE_FLAG_XML_DOUBLE_QUOTES);
296         av_bprintf(buf, "\"\n");
297     }
298
299     av_bprintf(buf, "        tts:overflow=\"visible\" />\n");
300
301     return 0;
302 }
303
304 static int ttml_write_header_content(AVCodecContext *avctx)
305 {
306     TTMLContext *s = avctx->priv_data;
307     ASS *ass = (ASS *)s->ass_ctx;
308     ASSScriptInfo script_info = ass->script_info;
309     const size_t base_extradata_size = TTMLENC_EXTRADATA_SIGNATURE_SIZE + 1 +
310                                        AV_INPUT_BUFFER_PADDING_SIZE;
311     size_t additional_extradata_size = 0;
312
313     if (script_info.play_res_x <= 0 || script_info.play_res_y <= 0) {
314         av_log(avctx, AV_LOG_ERROR,
315                "Invalid subtitle reference resolution %dx%d!\n",
316                script_info.play_res_x, script_info.play_res_y);
317         return AVERROR_INVALIDDATA;
318     }
319
320     // write the first string in extradata, attributes in the base "tt" element.
321     av_bprintf(&s->buffer, ttml_default_namespacing);
322     // the cell resolution is in character cells, so not exactly 1:1 against
323     // a pixel based resolution, but as the tts:extent in the root
324     // "tt" element is frowned upon (and disallowed in the EBU-TT profile),
325     // we mimic the reference resolution by setting it as the cell resolution.
326     av_bprintf(&s->buffer, "  ttp:cellResolution=\"%d %d\"\n",
327                script_info.play_res_x, script_info.play_res_y);
328     av_bprint_chars(&s->buffer, '\0', 1);
329
330     // write the second string in extradata, head element containing the styles
331     av_bprintf(&s->buffer, "  <head>\n");
332     av_bprintf(&s->buffer, "    <layout>\n");
333
334     for (int i = 0; i < ass->styles_count; i++) {
335         int ret = ttml_write_region(avctx, &s->buffer, script_info,
336                                     ass->styles[i]);
337         if (ret < 0)
338             return ret;
339     }
340
341     av_bprintf(&s->buffer, "    </layout>\n");
342     av_bprintf(&s->buffer, "  </head>\n");
343     av_bprint_chars(&s->buffer, '\0', 1);
344
345     if (!av_bprint_is_complete(&s->buffer)) {
346         return AVERROR(ENOMEM);
347     }
348
349     additional_extradata_size = s->buffer.len;
350
351     if (!(avctx->extradata =
352             av_mallocz(base_extradata_size + additional_extradata_size))) {
353         return AVERROR(ENOMEM);
354     }
355
356     avctx->extradata_size =
357         TTMLENC_EXTRADATA_SIGNATURE_SIZE + additional_extradata_size;
358     memcpy(avctx->extradata, TTMLENC_EXTRADATA_SIGNATURE,
359            TTMLENC_EXTRADATA_SIGNATURE_SIZE);
360
361     if (additional_extradata_size)
362         memcpy(avctx->extradata + TTMLENC_EXTRADATA_SIGNATURE_SIZE,
363                s->buffer.str, additional_extradata_size);
364
365     av_bprint_clear(&s->buffer);
366
367     return 0;
368 }
369
370 static av_cold int ttml_encode_init(AVCodecContext *avctx)
371 {
372     TTMLContext *s = avctx->priv_data;
373     int ret = AVERROR_BUG;
374     s->avctx   = avctx;
375
376     av_bprint_init(&s->buffer, 0, AV_BPRINT_SIZE_UNLIMITED);
377
378     if (!(s->ass_ctx = ff_ass_split(avctx->subtitle_header))) {
379         return AVERROR_INVALIDDATA;
380     }
381
382     if ((ret = ttml_write_header_content(avctx)) < 0) {
383         return ret;
384     }
385
386     return 0;
387 }
388
389 AVCodec ff_ttml_encoder = {
390     .name           = "ttml",
391     .long_name      = NULL_IF_CONFIG_SMALL("TTML subtitle"),
392     .type           = AVMEDIA_TYPE_SUBTITLE,
393     .id             = AV_CODEC_ID_TTML,
394     .priv_data_size = sizeof(TTMLContext),
395     .init           = ttml_encode_init,
396     .encode_sub     = ttml_encode_frame,
397     .close          = ttml_encode_close,
398     .capabilities   = FF_CODEC_CAP_INIT_CLEANUP,
399 };