1/*
2 * SubRip subtitle encoder
3 * Copyright (c) 2010  Aurelien Jacobs <aurel@gnuage.org>
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#include <stdarg.h>
23#include "avcodec.h"
24#include "libavutil/avstring.h"
25#include "libavutil/bprint.h"
26#include "ass_split.h"
27#include "ass.h"
28
29
30#define SRT_STACK_SIZE 64
31
32typedef struct {
33    AVCodecContext *avctx;
34    ASSSplitContext *ass_ctx;
35    AVBPrint buffer;
36    unsigned timestamp_end;
37    int count;
38    char stack[SRT_STACK_SIZE];
39    int stack_ptr;
40    int alignment_applied;
41} SRTContext;
42
43
44#ifdef __GNUC__
45__attribute__ ((__format__ (__printf__, 2, 3)))
46#endif
47static void srt_print(SRTContext *s, const char *str, ...)
48{
49    va_list vargs;
50    va_start(vargs, str);
51    av_vbprintf(&s->buffer, str, vargs);
52    va_end(vargs);
53}
54
55static int srt_stack_push(SRTContext *s, const char c)
56{
57    if (s->stack_ptr >= SRT_STACK_SIZE)
58        return -1;
59    s->stack[s->stack_ptr++] = c;
60    return 0;
61}
62
63static char srt_stack_pop(SRTContext *s)
64{
65    if (s->stack_ptr <= 0)
66        return 0;
67    return s->stack[--s->stack_ptr];
68}
69
70static int srt_stack_find(SRTContext *s, const char c)
71{
72    int i;
73    for (i = s->stack_ptr-1; i >= 0; i--)
74        if (s->stack[i] == c)
75            break;
76    return i;
77}
78
79static void srt_close_tag(SRTContext *s, char tag)
80{
81    srt_print(s, "</%c%s>", tag, tag == 'f' ? "ont" : "");
82}
83
84static void srt_stack_push_pop(SRTContext *s, const char c, int close)
85{
86    if (close) {
87        int i = c ? srt_stack_find(s, c) : 0;
88        if (i < 0)
89            return;
90        while (s->stack_ptr != i)
91            srt_close_tag(s, srt_stack_pop(s));
92    } else if (srt_stack_push(s, c) < 0)
93        av_log(s->avctx, AV_LOG_ERROR, "tag stack overflow\n");
94}
95
96static void srt_style_apply(SRTContext *s, const char *style)
97{
98    ASSStyle *st = ff_ass_style_get(s->ass_ctx, style);
99    if (st) {
100        int c = st->primary_color & 0xFFFFFF;
101        if (st->font_name && strcmp(st->font_name, ASS_DEFAULT_FONT) ||
102            st->font_size != ASS_DEFAULT_FONT_SIZE ||
103            c != ASS_DEFAULT_COLOR) {
104            srt_print(s, "<font");
105            if (st->font_name && strcmp(st->font_name, ASS_DEFAULT_FONT))
106                srt_print(s, " face=\"%s\"", st->font_name);
107            if (st->font_size != ASS_DEFAULT_FONT_SIZE)
108                srt_print(s, " size=\"%d\"", st->font_size);
109            if (c != ASS_DEFAULT_COLOR)
110                srt_print(s, " color=\"#%06x\"",
111                          (c & 0xFF0000) >> 16 | c & 0xFF00 | (c & 0xFF) << 16);
112            srt_print(s, ">");
113            srt_stack_push(s, 'f');
114        }
115        if (st->bold != ASS_DEFAULT_BOLD) {
116            srt_print(s, "<b>");
117            srt_stack_push(s, 'b');
118        }
119        if (st->italic != ASS_DEFAULT_ITALIC) {
120            srt_print(s, "<i>");
121            srt_stack_push(s, 'i');
122        }
123        if (st->underline != ASS_DEFAULT_UNDERLINE) {
124            srt_print(s, "<u>");
125            srt_stack_push(s, 'u');
126        }
127        if (st->alignment != ASS_DEFAULT_ALIGNMENT) {
128            srt_print(s, "{\\an%d}", st->alignment);
129            s->alignment_applied = 1;
130        }
131    }
132}
133
134
135static av_cold int srt_encode_init(AVCodecContext *avctx)
136{
137    SRTContext *s = avctx->priv_data;
138    s->avctx = avctx;
139    s->ass_ctx = ff_ass_split(avctx->subtitle_header);
140    av_bprint_init(&s->buffer, 0, AV_BPRINT_SIZE_UNLIMITED);
141    return s->ass_ctx ? 0 : AVERROR_INVALIDDATA;
142}
143
144static void srt_text_cb(void *priv, const char *text, int len)
145{
146    SRTContext *s = priv;
147    av_bprint_append_data(&s->buffer, text, len);
148}
149
150static void srt_new_line_cb(void *priv, int forced)
151{
152    srt_print(priv, "\r\n");
153}
154
155static void srt_style_cb(void *priv, char style, int close)
156{
157    srt_stack_push_pop(priv, style, close);
158    if (!close)
159        srt_print(priv, "<%c>", style);
160}
161
162static void srt_color_cb(void *priv, unsigned int color, unsigned int color_id)
163{
164    if (color_id > 1)
165        return;
166    srt_stack_push_pop(priv, 'f', color == 0xFFFFFFFF);
167    if (color != 0xFFFFFFFF)
168        srt_print(priv, "<font color=\"#%06x\">",
169              (color & 0xFF0000) >> 16 | color & 0xFF00 | (color & 0xFF) << 16);
170}
171
172static void srt_font_name_cb(void *priv, const char *name)
173{
174    srt_stack_push_pop(priv, 'f', !name);
175    if (name)
176        srt_print(priv, "<font face=\"%s\">", name);
177}
178
179static void srt_font_size_cb(void *priv, int size)
180{
181    srt_stack_push_pop(priv, 'f', size < 0);
182    if (size >= 0)
183        srt_print(priv, "<font size=\"%d\">", size);
184}
185
186static void srt_alignment_cb(void *priv, int alignment)
187{
188    SRTContext *s = priv;
189    if (!s->alignment_applied && alignment >= 0) {
190        srt_print(s, "{\\an%d}", alignment);
191        s->alignment_applied = 1;
192    }
193}
194
195static void srt_cancel_overrides_cb(void *priv, const char *style)
196{
197    srt_stack_push_pop(priv, 0, 1);
198    srt_style_apply(priv, style);
199}
200
201static void srt_move_cb(void *priv, int x1, int y1, int x2, int y2,
202                        int t1, int t2)
203{
204    SRTContext *s = priv;
205
206    if (s->avctx->codec->id == AV_CODEC_ID_SRT) {
207    char buffer[32];
208    int len = snprintf(buffer, sizeof(buffer),
209                       "  X1:%03u X2:%03u Y1:%03u Y2:%03u", x1, x2, y1, y2);
210    unsigned char *dummy;
211    unsigned room;
212
213    av_bprint_get_buffer(&s->buffer, len, &dummy, &room);
214    if (room >= len) {
215        memmove(s->buffer.str + s->timestamp_end + len,
216                s->buffer.str + s->timestamp_end,
217                s->buffer.len - s->timestamp_end + 1);
218        memcpy(s->buffer.str + s->timestamp_end, buffer, len);
219    }
220    /* Increment even if av_bprint_get_buffer() did not return enough room:
221       the bprint structure will be treated as truncated. */
222    s->buffer.len += len;
223    }
224}
225
226static void srt_end_cb(void *priv)
227{
228    SRTContext *s = priv;
229
230    srt_stack_push_pop(priv, 0, 1);
231    if (s->avctx->codec->id == AV_CODEC_ID_SRT)
232        srt_print(priv, "\r\n\r\n");
233}
234
235static const ASSCodesCallbacks srt_callbacks = {
236    .text             = srt_text_cb,
237    .new_line         = srt_new_line_cb,
238    .style            = srt_style_cb,
239    .color            = srt_color_cb,
240    .font_name        = srt_font_name_cb,
241    .font_size        = srt_font_size_cb,
242    .alignment        = srt_alignment_cb,
243    .cancel_overrides = srt_cancel_overrides_cb,
244    .move             = srt_move_cb,
245    .end              = srt_end_cb,
246};
247
248static int srt_encode_frame(AVCodecContext *avctx,
249                            unsigned char *buf, int bufsize, const AVSubtitle *sub)
250{
251    SRTContext *s = avctx->priv_data;
252    ASSDialog *dialog;
253    int i, num;
254
255    av_bprint_clear(&s->buffer);
256
257    for (i=0; i<sub->num_rects; i++) {
258
259        if (sub->rects[i]->type != SUBTITLE_ASS) {
260            av_log(avctx, AV_LOG_ERROR, "Only SUBTITLE_ASS type supported.\n");
261            return AVERROR(ENOSYS);
262        }
263
264        dialog = ff_ass_split_dialog(s->ass_ctx, sub->rects[i]->ass, 0, &num);
265        for (; dialog && num--; dialog++) {
266            if (avctx->codec->id == AV_CODEC_ID_SRT) {
267                int sh, sm, ss, sc = 10 * dialog->start;
268                int eh, em, es, ec = 10 * dialog->end;
269                sh = sc/3600000;  sc -= 3600000*sh;
270                sm = sc/  60000;  sc -=   60000*sm;
271                ss = sc/   1000;  sc -=    1000*ss;
272                eh = ec/3600000;  ec -= 3600000*eh;
273                em = ec/  60000;  ec -=   60000*em;
274                es = ec/   1000;  ec -=    1000*es;
275                srt_print(s,"%d\r\n%02d:%02d:%02d,%03d --> %02d:%02d:%02d,%03d\r\n",
276                          ++s->count, sh, sm, ss, sc, eh, em, es, ec);
277                s->timestamp_end = s->buffer.len - 2;
278            }
279            s->alignment_applied = 0;
280            srt_style_apply(s, dialog->style);
281            ff_ass_split_override_codes(&srt_callbacks, s, dialog->text);
282        }
283    }
284
285    if (!av_bprint_is_complete(&s->buffer))
286        return AVERROR(ENOMEM);
287    if (!s->buffer.len)
288        return 0;
289
290    if (s->buffer.len > bufsize) {
291        av_log(avctx, AV_LOG_ERROR, "Buffer too small for ASS event.\n");
292        return -1;
293    }
294    memcpy(buf, s->buffer.str, s->buffer.len);
295
296    return s->buffer.len;
297}
298
299static int srt_encode_close(AVCodecContext *avctx)
300{
301    SRTContext *s = avctx->priv_data;
302    ff_ass_split_free(s->ass_ctx);
303    av_bprint_finalize(&s->buffer, NULL);
304    return 0;
305}
306
307#if CONFIG_SRT_ENCODER
308/* deprecated encoder */
309AVCodec ff_srt_encoder = {
310    .name           = "srt",
311    .long_name      = NULL_IF_CONFIG_SMALL("SubRip subtitle with embedded timing"),
312    .type           = AVMEDIA_TYPE_SUBTITLE,
313    .id             = AV_CODEC_ID_SRT,
314    .priv_data_size = sizeof(SRTContext),
315    .init           = srt_encode_init,
316    .encode_sub     = srt_encode_frame,
317    .close          = srt_encode_close,
318};
319#endif
320
321#if CONFIG_SUBRIP_ENCODER
322AVCodec ff_subrip_encoder = {
323    .name           = "subrip",
324    .long_name      = NULL_IF_CONFIG_SMALL("SubRip subtitle"),
325    .type           = AVMEDIA_TYPE_SUBTITLE,
326    .id             = AV_CODEC_ID_SUBRIP,
327    .priv_data_size = sizeof(SRTContext),
328    .init           = srt_encode_init,
329    .encode_sub     = srt_encode_frame,
330    .close          = srt_encode_close,
331};
332#endif
333