FFmpeg
Loading...
Searching...
No Matches
subtitles.c
Go to the documentation of this file.
1/*
2 * Copyright (c) 2012-2013 Clément Bœsch <u pkh me>
3 *
4 * This file is part of FFmpeg.
5 *
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20
21#include "avformat.h"
22#include "subtitles.h"
23#include "avio_internal.h"
24#include "libavutil/avassert.h"
25#include "libavutil/avstring.h"
26#include "libavutil/mem.h"
27
29{
30 int i;
31 r->pb = pb;
32 r->buf_pos = r->buf_len = 0;
33 r->type = FF_UTF_8;
34 for (i = 0; i < 2; i++)
35 r->buf[r->buf_len++] = avio_r8(r->pb);
36 if (strncmp("\xFF\xFE", r->buf, 2) == 0) {
37 r->type = FF_UTF16LE;
38 r->buf_pos += 2;
39 } else if (strncmp("\xFE\xFF", r->buf, 2) == 0) {
40 r->type = FF_UTF16BE;
41 r->buf_pos += 2;
42 } else {
43 r->buf[r->buf_len++] = avio_r8(r->pb);
44 if (strncmp("\xEF\xBB\xBF", r->buf, 3) == 0) {
45 // UTF8
46 r->buf_pos += 3;
47 }
48 }
49 if (s && (r->type == FF_UTF16LE || r->type == FF_UTF16BE))
51 "UTF16 is automatically converted to UTF8, do not specify a character encoding\n");
52}
53
54void ff_text_init_buf(FFTextReader *r, const void *buf, size_t size)
55{
56 ffio_init_read_context(&r->buf_pb, buf, size);
57 ff_text_init_avio(NULL, r, &r->buf_pb.pub);
58}
59
61{
62 return avio_tell(r->pb) - r->buf_len + r->buf_pos;
63}
64
66{
67 uint32_t val;
68 uint8_t tmp;
69 if (r->buf_pos < r->buf_len)
70 return r->buf[r->buf_pos++];
71 if (r->type == FF_UTF16LE) {
72 GET_UTF16(val, avio_rl16(r->pb), return 0;)
73 } else if (r->type == FF_UTF16BE) {
74 GET_UTF16(val, avio_rb16(r->pb), return 0;)
75 } else {
76 return avio_r8(r->pb);
77 }
78 if (!val)
79 return 0;
80 r->buf_pos = 0;
81 r->buf_len = 0;
82 PUT_UTF8(val, tmp, r->buf[r->buf_len++] = tmp;)
83 return r->buf[r->buf_pos++]; // buf_len is at least 1
84}
85
86void ff_text_read(FFTextReader *r, char *buf, size_t size)
87{
88 for ( ; size > 0; size--)
89 *buf++ = ff_text_r8(r);
90}
91
93{
94 return r->buf_pos >= r->buf_len && avio_feof(r->pb);
95}
96
98{
99 int c;
100 if (r->buf_pos < r->buf_len)
101 return r->buf[r->buf_pos];
102 c = ff_text_r8(r);
103 if (!avio_feof(r->pb)) {
104 r->buf_pos = 0;
105 r->buf_len = 1;
106 r->buf[0] = c;
107 }
108 return c;
109}
110
112 const uint8_t *event, size_t len, int merge)
113{
114 AVPacket **subs, *sub;
115
116 av_assert1(event || len == 0);
117
118 if (merge && q->nb_subs > 0) {
119 /* merge with previous event */
120
121 int old_len;
122 sub = q->subs[q->nb_subs - 1];
123 old_len = sub->size;
124 if (event) {
125 if (av_grow_packet(sub, len) < 0)
126 return NULL;
127 memcpy(sub->data + old_len, event, len);
128 }
129 } else {
130 /* new event */
131
132 if (q->nb_subs >= INT_MAX/sizeof(*q->subs) - 1)
133 return NULL;
134 subs = av_fast_realloc(q->subs, &q->allocated_size,
135 (q->nb_subs + 1) * sizeof(*q->subs));
136 if (!subs)
137 return NULL;
138 q->subs = subs;
139 sub = av_packet_alloc();
140 if (!sub)
141 return NULL;
142 if (event) {
143 if (av_new_packet(sub, len) < 0) {
144 av_packet_free(&sub);
145 return NULL;
146 }
147 memcpy(sub->data, event, len);
148 }
149 sub->flags |= AV_PKT_FLAG_KEY;
150 sub->pts = sub->dts = 0;
151 subs[q->nb_subs++] = sub;
152 }
153 return sub;
154}
155
157 const AVBPrint *event, int merge)
158{
159 if (!av_bprint_is_complete(event))
160 return NULL;
161 return ff_subtitles_queue_insert(q, event->str, event->len, merge);
162}
163
164static int cmp_pkt_sub_ts_pos(const void *a, const void *b)
165{
166 const AVPacket *s1 = *(const AVPacket **)a;
167 const AVPacket *s2 = *(const AVPacket **)b;
168 if (s1->pts == s2->pts)
169 return FFDIFFSIGN(s1->pos, s2->pos);
170 return FFDIFFSIGN(s1->pts , s2->pts);
171}
172
173static int cmp_pkt_sub_pos_ts(const void *a, const void *b)
174{
175 const AVPacket *s1 = *(const AVPacket **)a;
176 const AVPacket *s2 = *(const AVPacket **)b;
177 if (s1->pos == s2->pos) {
178 if (s1->pts == s2->pts)
179 return 0;
180 return s1->pts > s2->pts ? 1 : -1;
181 }
182 return s1->pos > s2->pos ? 1 : -1;
183}
184
185static void drop_dups(void *log_ctx, FFDemuxSubtitlesQueue *q)
186{
187 int i, drop = 0;
188
189 for (i = 1; i < q->nb_subs; i++) {
190 const int last_id = i - 1 - drop;
191 const AVPacket *last = q->subs[last_id];
192
193 if (q->subs[i]->pts == last->pts &&
194 q->subs[i]->duration == last->duration &&
195 q->subs[i]->stream_index == last->stream_index &&
196 !strcmp(q->subs[i]->data, last->data)) {
197
198 av_packet_free(&q->subs[i]);
199 drop++;
200 } else if (drop) {
201 q->subs[last_id + 1] = q->subs[i];
202 q->subs[i] = NULL;
203 }
204 }
205
206 if (drop) {
207 q->nb_subs -= drop;
208 av_log(log_ctx, AV_LOG_WARNING, "Dropping %d duplicated subtitle events\n", drop);
209 }
210}
211
213{
214 int i;
215
216 if (!q->nb_subs)
217 return;
218
219 qsort(q->subs, q->nb_subs, sizeof(*q->subs),
222 for (i = 0; i < q->nb_subs; i++)
223 if (q->subs[i]->duration < 0 && i < q->nb_subs - 1 && q->subs[i + 1]->pts - (uint64_t)q->subs[i]->pts <= INT64_MAX)
224 q->subs[i]->duration = q->subs[i + 1]->pts - q->subs[i]->pts;
225
226 if (!q->keep_duplicates)
227 drop_dups(log_ctx, q);
228}
229
231{
232 AVPacket *sub;
233 int ret;
234
235 if (q->current_sub_idx == q->nb_subs)
236 return AVERROR_EOF;
237 sub = q->subs[q->current_sub_idx];
238 if ((ret = av_packet_ref(pkt, sub)) < 0) {
239 return ret;
240 }
241
242 pkt->dts = pkt->pts;
243 q->current_sub_idx++;
244 return 0;
245}
246
248{
249 int s1 = 0, s2 = q->nb_subs - 1;
250
251 if (s2 < s1)
252 return AVERROR(ERANGE);
253
254 for (;;) {
255 int mid;
256
257 if (s1 == s2)
258 return s1;
259 if (s1 == s2 - 1)
260 return q->subs[s1]->pts <= q->subs[s2]->pts ? s1 : s2;
261 mid = (s1 + s2) / 2;
262 if (q->subs[mid]->pts <= ts)
263 s1 = mid;
264 else
265 s2 = mid;
266 }
267}
268
270 int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
271{
272 if (flags & AVSEEK_FLAG_BYTE) {
273 return AVERROR(ENOSYS);
274 } else if (flags & AVSEEK_FLAG_FRAME) {
275 if (ts < 0 || ts >= q->nb_subs)
276 return AVERROR(ERANGE);
277 q->current_sub_idx = ts;
278 } else {
279 int i, idx = search_sub_ts(q, ts);
280 int64_t ts_selected;
281
282 if (idx < 0)
283 return idx;
284 for (i = idx; i < q->nb_subs && q->subs[i]->pts < min_ts; i++)
285 if (stream_index == -1 || q->subs[i]->stream_index == stream_index)
286 idx = i;
287 for (i = idx; i > 0 && q->subs[i]->pts > max_ts; i--)
288 if (stream_index == -1 || q->subs[i]->stream_index == stream_index)
289 idx = i;
290
291 ts_selected = q->subs[idx]->pts;
292 if (ts_selected < min_ts || ts_selected > max_ts)
293 return AVERROR(ERANGE);
294
295 /* look back in the latest subtitles for overlapping subtitles */
296 for (i = idx - 1; i >= 0; i--) {
297 int64_t pts = q->subs[i]->pts;
298 if (q->subs[i]->duration <= 0 ||
299 (stream_index != -1 && q->subs[i]->stream_index != stream_index))
300 continue;
301 if (pts >= min_ts && pts > ts_selected - q->subs[i]->duration)
302 idx = i;
303 else
304 break;
305 }
306
307 /* If the queue is used to store multiple subtitles streams (like with
308 * VobSub) and the stream index is not specified, we need to make sure
309 * to focus on the smallest file position offset for a same timestamp;
310 * queue is ordered by pts and then filepos, so we can take the first
311 * entry for a given timestamp. */
312 if (stream_index == -1)
313 while (idx > 0 && q->subs[idx - 1]->pts == q->subs[idx]->pts)
314 idx--;
315
316 q->current_sub_idx = idx;
317 }
318 return 0;
319}
320
322{
323 int i;
324
325 for (i = 0; i < q->nb_subs; i++)
326 av_packet_free(&q->subs[i]);
327 av_freep(&q->subs);
328 q->nb_subs = q->allocated_size = q->current_sub_idx = 0;
329}
330
336
338 int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
339{
340 FFDemuxSubtitlesQueue *q = s->priv_data;
341 return ff_subtitles_queue_seek(q, s, stream_index,
342 min_ts, ts, max_ts, flags);
343}
344
346{
347 FFDemuxSubtitlesQueue *q = s->priv_data;
349 return 0;
350}
351
352int ff_smil_extract_next_text_chunk(FFTextReader *tr, AVBPrint *buf, char *c)
353{
354 int i = 0;
355 char end_chr;
356
357 if (!*c) // cached char?
358 *c = ff_text_r8(tr);
359 if (!*c)
360 return 0;
361
362 end_chr = *c == '<' ? '>' : '<';
363 do {
364 av_bprint_chars(buf, *c, 1);
365 *c = ff_text_r8(tr);
366 if (i == INT_MAX)
367 return AVERROR_INVALIDDATA;
368 i++;
369 } while (*c != end_chr && *c);
370 if (end_chr == '>') {
371 av_bprint_chars(buf, '>', 1);
372 *c = 0;
373 }
374 return av_bprint_is_complete(buf) ? i : AVERROR(ENOMEM);
375}
376
377const char *ff_smil_get_attr_ptr(const char *s, const char *attr)
378{
379 int in_quotes = 0;
380 const size_t len = strlen(attr);
381
382 while (*s) {
383 while (*s) {
384 if (!in_quotes && av_isspace(*s))
385 break;
386 in_quotes ^= *s == '"'; // XXX: support escaping?
387 s++;
388 }
389 while (av_isspace(*s))
390 s++;
391 if (!av_strncasecmp(s, attr, len) && s[len] == '=')
392 return s + len + 1 + (s[len + 1] == '"');
393 }
394 return NULL;
395}
396
397static inline int is_eol(char c)
398{
399 return c == '\r' || c == '\n';
400}
401
403{
404 char eol_buf[5], last_was_cr = 0;
405 int n = 0, i = 0, nb_eol = 0;
406
407 av_bprint_clear(buf);
408
409 for (;;) {
410 char c = ff_text_r8(tr);
411
412 if (!c)
413 break;
414
415 /* ignore all initial line breaks */
416 if (n == 0 && is_eol(c))
417 continue;
418
419 /* line break buffering: we don't want to add the trailing \r\n */
420 if (is_eol(c)) {
421 nb_eol += c == '\n' || last_was_cr;
422 if (nb_eol == 2)
423 break;
424 eol_buf[i++] = c;
425 if (i == sizeof(eol_buf) - 1)
426 break;
427 last_was_cr = c == '\r';
428 continue;
429 }
430
431 /* only one line break followed by data: we flush the line breaks
432 * buffer */
433 if (i) {
434 eol_buf[i] = 0;
435 av_bprintf(buf, "%s", eol_buf);
436 i = nb_eol = 0;
437 }
438
439 av_bprint_chars(buf, c, 1);
440 n++;
441 }
442 return av_bprint_is_complete(buf) ? 0 : AVERROR(ENOMEM);
443}
444
446{
447 FFTextReader tr;
448 tr.buf_pos = tr.buf_len = 0;
449 tr.type = 0;
450 tr.pb = pb;
451 return ff_subtitles_read_text_chunk(&tr, buf);
452}
453
454ptrdiff_t ff_subtitles_read_line(FFTextReader *tr, char *buf, size_t size)
455{
456 size_t cur = 0;
457 if (!size)
458 return 0;
459 buf[0] = '\0';
460 while (cur + 1 < size) {
461 unsigned char c = ff_text_r8(tr);
462 if (!c)
463 return ff_text_eof(tr) ? cur : AVERROR_INVALIDDATA;
464 if (c == '\r' || c == '\n')
465 break;
466 buf[cur++] = c;
467 buf[cur] = '\0';
468 }
469 while (ff_text_peek_r8(tr) == '\r')
470 ff_text_r8(tr);
471 if (ff_text_peek_r8(tr) == '\n')
472 ff_text_r8(tr);
473 return cur;
474}
static double val(void *priv, double ch)
Definition aeval.c:77
simple assert() macros that are a bit more flexible than ISO C assert().
#define av_assert1(cond)
assert() equivalent, that does not lie in speed critical code.
Definition avassert.h:58
Main libavformat public API header.
#define AVSEEK_FLAG_BYTE
seeking based on position in bytes
Definition avformat.h:2617
#define AVSEEK_FLAG_FRAME
seeking based on frame number
Definition avformat.h:2619
unsigned int avio_rb16(AVIOContext *s)
Definition aviobuf.c:749
int avio_feof(AVIOContext *s)
Similar to feof() but also returns nonzero on read errors.
Definition aviobuf.c:349
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition avio.h:494
unsigned int avio_rl16(AVIOContext *s)
Definition aviobuf.c:717
int avio_r8(AVIOContext *s)
Definition aviobuf.c:606
void ffio_init_read_context(FFIOContext *s, const uint8_t *buffer, int buffer_size)
Wrap a buffer in an AVIOContext for reading.
Definition aviobuf.c:99
void av_bprintf(AVBPrint *buf, const char *fmt,...)
Definition bprint.c:122
#define flags(name, subs,...)
Definition cbs_h264.c:74
#define i(width, name, range_min, range_max)
Definition cbs_h264.c:63
#define s(width, name)
Definition cbs_vp9.c:198
#define GET_UTF16(val, GET_16BIT, ERROR)
Convert a UTF-16 character (2 or 4 bytes) to its 32-bit UCS-4 encoded form.
Definition common.h:502
#define PUT_UTF8(val, tmp, PUT_BYTE)
Convert a 32-bit Unicode character to its UTF-8 encoded form (up to 4 bytes long).
Definition common.h:530
#define NULL
Definition coverity.c:32
long long int64_t
Definition coverity.c:34
static AVPacket * pkt
void av_packet_free(AVPacket **pkt)
Free the packet, if the packet is reference counted, it will be unreferenced first.
Definition packet.c:74
int av_grow_packet(AVPacket *pkt, int grow_by)
Increase packet size, correctly zeroing padding.
Definition packet.c:121
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition packet.h:650
AVPacket * av_packet_alloc(void)
Allocate an AVPacket and set its fields to default values.
Definition packet.c:63
int av_packet_ref(AVPacket *dst, const AVPacket *src)
Setup a new reference to the data described by a given packet.
Definition packet.c:442
int av_new_packet(AVPacket *pkt, int size)
Allocate the payload of a packet and initialize its fields with default values.
Definition packet.c:98
static int av_bprint_is_complete(const AVBPrint *buf)
Test if the print buffer is complete (not truncated).
Definition bprint.h:218
void av_bprint_chars(AVBPrint *buf, char c, unsigned n)
Append char c n times to a print buffer.
Definition bprint.c:130
void av_bprint_clear(AVBPrint *buf)
Reset the string to "" but keep internal allocated data.
Definition bprint.c:227
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition error.h:61
#define AVERROR_EOF
End of file.
Definition error.h:57
#define AVERROR(e)
Definition error.h:45
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition log.h:216
#define AV_LOG_INFO
Standard information.
Definition log.h:221
void * av_fast_realloc(void *ptr, unsigned int *size, size_t min_size)
Reallocate the given buffer if it is not large enough, otherwise do nothing.
Definition mem.c:495
static av_const int av_isspace(int c)
Locale-independent conversion of ASCII isspace.
Definition avstring.h:218
int av_strncasecmp(const char *a, const char *b, size_t n)
Locale-independent case-insensitive compare.
Definition avstring.c:218
int a
#define r
Definition input.c:42
#define b
Definition input.c:43
static void merge(GetBitContext *gb, uint8_t *dst, uint8_t *src, int size)
Merge two consequent lists of equal size depending on bits read.
Definition bink.c:220
#define FFDIFFSIGN(x, y)
Comparator.
Definition macros.h:45
Memory handling functions.
Format I/O context.
Definition avformat.h:1333
Bytestream IO Context.
Definition avio.h:160
This structure stores compressed data.
Definition packet.h:580
int stream_index
Definition packet.h:605
int flags
A combination of AV_PKT_FLAG values.
Definition packet.h:609
int size
Definition packet.h:604
int64_t duration
Duration of this packet in AVStream->time_base units, 0 if unknown.
Definition packet.h:621
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition packet.h:596
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed.
Definition packet.h:602
uint8_t * data
Definition packet.h:603
int64_t pos
byte position in stream, -1 if unknown
Definition packet.h:623
int nb_subs
number of subtitles packets
Definition subtitles.h:105
AVPacket ** subs
array of subtitles packets
Definition subtitles.h:104
int allocated_size
allocated size for subs
Definition subtitles.h:106
int current_sub_idx
current position for the read packet callback
Definition subtitles.h:107
enum sub_sort sort
sort method to use when finalizing subtitles
Definition subtitles.h:108
int keep_duplicates
set to 1 to keep duplicated subtitle events
Definition subtitles.h:109
AVIOContext * pb
Definition subtitles.h:43
ptrdiff_t ff_subtitles_read_line(FFTextReader *tr, char *buf, size_t size)
Read a line of text.
Definition subtitles.c:454
int64_t ff_text_pos(FFTextReader *r)
Return the byte position of the next byte returned by ff_text_r8().
Definition subtitles.c:60
int ff_subtitles_read_packet(AVFormatContext *s, AVPacket *pkt)
Definition subtitles.c:331
int ff_subtitles_queue_seek(FFDemuxSubtitlesQueue *q, AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
Update current_sub_idx to emulate a seek.
Definition subtitles.c:269
AVPacket * ff_subtitles_queue_insert(FFDemuxSubtitlesQueue *q, const uint8_t *event, size_t len, int merge)
Insert a new subtitle event.
Definition subtitles.c:111
void ff_text_read(FFTextReader *r, char *buf, size_t size)
Read the given number of bytes (in UTF-8).
Definition subtitles.c:86
int ff_subtitles_read_seek(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
Definition subtitles.c:337
int ff_subtitles_read_close(AVFormatContext *s)
Definition subtitles.c:345
const char * ff_smil_get_attr_ptr(const char *s, const char *attr)
SMIL helper to point on the value of an attribute in the given tag.
Definition subtitles.c:377
int ff_subtitles_read_text_chunk(FFTextReader *tr, AVBPrint *buf)
Read a subtitles chunk from FFTextReader.
Definition subtitles.c:402
static int cmp_pkt_sub_ts_pos(const void *a, const void *b)
Definition subtitles.c:164
int ff_text_eof(FFTextReader *r)
Return non-zero if EOF was reached.
Definition subtitles.c:92
static int is_eol(char c)
Definition subtitles.c:397
void ff_text_init_buf(FFTextReader *r, const void *buf, size_t size)
Similar to ff_text_init_avio(), but sets it up to read from a bounded buffer.
Definition subtitles.c:54
int ff_subtitles_read_chunk(AVIOContext *pb, AVBPrint *buf)
Same as ff_subtitles_read_text_chunk(), but read from an AVIOContext.
Definition subtitles.c:445
static void drop_dups(void *log_ctx, FFDemuxSubtitlesQueue *q)
Definition subtitles.c:185
static int search_sub_ts(const FFDemuxSubtitlesQueue *q, int64_t ts)
Definition subtitles.c:247
void ff_text_init_avio(void *s, FFTextReader *r, AVIOContext *pb)
Initialize the FFTextReader from the given AVIOContext.
Definition subtitles.c:28
int ff_text_r8(FFTextReader *r)
Return the next byte.
Definition subtitles.c:65
int ff_smil_extract_next_text_chunk(FFTextReader *tr, AVBPrint *buf, char *c)
SMIL helper to load next chunk ("<...>" or untagged content) in buf.
Definition subtitles.c:352
static int cmp_pkt_sub_pos_ts(const void *a, const void *b)
Definition subtitles.c:173
int ff_subtitles_queue_read_packet(FFDemuxSubtitlesQueue *q, AVPacket *pkt)
Generic read_packet() callback for subtitles demuxers using this queue system.
Definition subtitles.c:230
int ff_text_peek_r8(FFTextReader *r)
Like ff_text_r8(), but don't remove the byte from the buffer.
Definition subtitles.c:97
AVPacket * ff_subtitles_queue_insert_bprint(FFDemuxSubtitlesQueue *q, const AVBPrint *event, int merge)
Same as ff_subtitles_queue_insert but takes an AVBPrint input.
Definition subtitles.c:156
void ff_subtitles_queue_finalize(void *log_ctx, FFDemuxSubtitlesQueue *q)
Set missing durations, sort subtitles by PTS (and then byte position), and drop duplicated events.
Definition subtitles.c:212
void ff_subtitles_queue_clean(FFDemuxSubtitlesQueue *q)
Remove and destroy all the subtitles packets.
Definition subtitles.c:321
@ FF_UTF16LE
Definition subtitles.h:37
@ FF_UTF_8
Definition subtitles.h:36
@ FF_UTF16BE
Definition subtitles.h:38
@ SUB_SORT_TS_POS
sort by timestamps, then position
Definition subtitles.h:31
#define av_freep(p)
#define av_log(a,...)
static uint8_t tmp[40]
Definition aes_ctr.c:52
static int64_t pts
int size
int len
static double c[64]