]> git.sesse.net Git - ffmpeg/blob - libavcodec/parser.c
avcodec: v4l2_m2m: fix races around freeing data on close
[ffmpeg] / libavcodec / parser.c
1 /*
2  * Audio and Video frame extraction
3  * Copyright (c) 2003 Fabrice Bellard
4  * Copyright (c) 2003 Michael Niedermayer
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 #include <inttypes.h>
24 #include <stdint.h>
25 #include <string.h>
26
27 #include "libavutil/avassert.h"
28 #include "libavutil/internal.h"
29 #include "libavutil/mem.h"
30 #include "libavutil/thread.h"
31
32 #include "internal.h"
33 #include "parser.h"
34
35 static AVCodecParser *av_first_parser = NULL;
36
37 AVCodecParser *av_parser_next(const AVCodecParser *p)
38 {
39     if (p)
40         return p->next;
41     else
42         return av_first_parser;
43 }
44
45 static AVMutex parser_register_mutex = AV_MUTEX_INITIALIZER;
46
47 void av_register_codec_parser(AVCodecParser *parser)
48 {
49     ff_mutex_lock(&parser_register_mutex);
50     parser->next = av_first_parser;
51     av_first_parser = parser;
52     ff_mutex_unlock(&parser_register_mutex);
53 }
54
55 AVCodecParserContext *av_parser_init(int codec_id)
56 {
57     AVCodecParserContext *s = NULL;
58     AVCodecParser *parser;
59     int ret;
60
61     if (codec_id == AV_CODEC_ID_NONE)
62         return NULL;
63
64     for (parser = av_first_parser; parser; parser = parser->next) {
65         if (parser->codec_ids[0] == codec_id ||
66             parser->codec_ids[1] == codec_id ||
67             parser->codec_ids[2] == codec_id ||
68             parser->codec_ids[3] == codec_id ||
69             parser->codec_ids[4] == codec_id)
70             goto found;
71     }
72     return NULL;
73
74 found:
75     s = av_mallocz(sizeof(AVCodecParserContext));
76     if (!s)
77         goto err_out;
78     s->parser = parser;
79     s->priv_data = av_mallocz(parser->priv_data_size);
80     if (!s->priv_data)
81         goto err_out;
82     s->fetch_timestamp=1;
83     s->pict_type = AV_PICTURE_TYPE_I;
84     if (parser->parser_init) {
85         ret = parser->parser_init(s);
86         if (ret != 0)
87             goto err_out;
88     }
89     s->key_frame            = -1;
90 #if FF_API_CONVERGENCE_DURATION
91 FF_DISABLE_DEPRECATION_WARNINGS
92     s->convergence_duration = 0;
93 FF_ENABLE_DEPRECATION_WARNINGS
94 #endif
95     s->dts_sync_point       = INT_MIN;
96     s->dts_ref_dts_delta    = INT_MIN;
97     s->pts_dts_delta        = INT_MIN;
98     s->format               = -1;
99
100     return s;
101
102 err_out:
103     if (s)
104         av_freep(&s->priv_data);
105     av_free(s);
106     return NULL;
107 }
108
109 void ff_fetch_timestamp(AVCodecParserContext *s, int off, int remove, int fuzzy)
110 {
111     int i;
112
113     if (!fuzzy) {
114         s->dts    =
115         s->pts    = AV_NOPTS_VALUE;
116         s->pos    = -1;
117         s->offset = 0;
118     }
119     for (i = 0; i < AV_PARSER_PTS_NB; i++) {
120         if (s->cur_offset + off >= s->cur_frame_offset[i] &&
121             (s->frame_offset < s->cur_frame_offset[i] ||
122              (!s->frame_offset && !s->next_frame_offset)) && // first field/frame
123             // check disabled since MPEG-TS does not send complete PES packets
124             /*s->next_frame_offset + off <*/  s->cur_frame_end[i]){
125
126             if (!fuzzy || s->cur_frame_dts[i] != AV_NOPTS_VALUE) {
127                 s->dts    = s->cur_frame_dts[i];
128                 s->pts    = s->cur_frame_pts[i];
129                 s->pos    = s->cur_frame_pos[i];
130                 s->offset = s->next_frame_offset - s->cur_frame_offset[i];
131             }
132             if (remove)
133                 s->cur_frame_offset[i] = INT64_MAX;
134             if (s->cur_offset + off < s->cur_frame_end[i])
135                 break;
136         }
137     }
138 }
139
140 int av_parser_parse2(AVCodecParserContext *s, AVCodecContext *avctx,
141                      uint8_t **poutbuf, int *poutbuf_size,
142                      const uint8_t *buf, int buf_size,
143                      int64_t pts, int64_t dts, int64_t pos)
144 {
145     int index, i;
146     uint8_t dummy_buf[AV_INPUT_BUFFER_PADDING_SIZE];
147
148     av_assert1(avctx->codec_id != AV_CODEC_ID_NONE);
149
150     /* Parsers only work for the specified codec ids. */
151     av_assert1(avctx->codec_id == s->parser->codec_ids[0] ||
152                avctx->codec_id == s->parser->codec_ids[1] ||
153                avctx->codec_id == s->parser->codec_ids[2] ||
154                avctx->codec_id == s->parser->codec_ids[3] ||
155                avctx->codec_id == s->parser->codec_ids[4]);
156
157     if (!(s->flags & PARSER_FLAG_FETCHED_OFFSET)) {
158         s->next_frame_offset =
159         s->cur_offset        = pos;
160         s->flags            |= PARSER_FLAG_FETCHED_OFFSET;
161     }
162
163     if (buf_size == 0) {
164         /* padding is always necessary even if EOF, so we add it here */
165         memset(dummy_buf, 0, sizeof(dummy_buf));
166         buf = dummy_buf;
167     } else if (s->cur_offset + buf_size != s->cur_frame_end[s->cur_frame_start_index]) { /* skip remainder packets */
168         /* add a new packet descriptor */
169         i = (s->cur_frame_start_index + 1) & (AV_PARSER_PTS_NB - 1);
170         s->cur_frame_start_index = i;
171         s->cur_frame_offset[i]   = s->cur_offset;
172         s->cur_frame_end[i]      = s->cur_offset + buf_size;
173         s->cur_frame_pts[i]      = pts;
174         s->cur_frame_dts[i]      = dts;
175         s->cur_frame_pos[i]      = pos;
176     }
177
178     if (s->fetch_timestamp) {
179         s->fetch_timestamp = 0;
180         s->last_pts        = s->pts;
181         s->last_dts        = s->dts;
182         s->last_pos        = s->pos;
183         ff_fetch_timestamp(s, 0, 0, 0);
184     }
185     /* WARNING: the returned index can be negative */
186     index = s->parser->parser_parse(s, avctx, (const uint8_t **) poutbuf,
187                                     poutbuf_size, buf, buf_size);
188     av_assert0(index > -0x20000000); // The API does not allow returning AVERROR codes
189 #define FILL(name) if(s->name > 0 && avctx->name <= 0) avctx->name = s->name
190     if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
191         FILL(field_order);
192     }
193
194     /* update the file pointer */
195     if (*poutbuf_size) {
196         /* fill the data for the current frame */
197         s->frame_offset = s->next_frame_offset;
198
199         /* offset of the next frame */
200         s->next_frame_offset = s->cur_offset + index;
201         s->fetch_timestamp   = 1;
202     }
203     if (index < 0)
204         index = 0;
205     s->cur_offset += index;
206     return index;
207 }
208
209 int av_parser_change(AVCodecParserContext *s, AVCodecContext *avctx,
210                      uint8_t **poutbuf, int *poutbuf_size,
211                      const uint8_t *buf, int buf_size, int keyframe)
212 {
213     if (s && s->parser->split) {
214         if (avctx->flags  & AV_CODEC_FLAG_GLOBAL_HEADER ||
215             avctx->flags2 & AV_CODEC_FLAG2_LOCAL_HEADER) {
216             int i = s->parser->split(avctx, buf, buf_size);
217             buf      += i;
218             buf_size -= i;
219         }
220     }
221
222     /* cast to avoid warning about discarding qualifiers */
223     *poutbuf      = (uint8_t *) buf;
224     *poutbuf_size = buf_size;
225     if (avctx->extradata) {
226         if (keyframe && (avctx->flags2 & AV_CODEC_FLAG2_LOCAL_HEADER)) {
227             int size = buf_size + avctx->extradata_size;
228
229             *poutbuf_size = size;
230             *poutbuf      = av_malloc(size + AV_INPUT_BUFFER_PADDING_SIZE);
231             if (!*poutbuf)
232                 return AVERROR(ENOMEM);
233
234             memcpy(*poutbuf, avctx->extradata, avctx->extradata_size);
235             memcpy(*poutbuf + avctx->extradata_size, buf,
236                    buf_size + AV_INPUT_BUFFER_PADDING_SIZE);
237             return 1;
238         }
239     }
240
241     return 0;
242 }
243
244 void av_parser_close(AVCodecParserContext *s)
245 {
246     if (s) {
247         if (s->parser->parser_close)
248             s->parser->parser_close(s);
249         av_freep(&s->priv_data);
250         av_free(s);
251     }
252 }
253
254 int ff_combine_frame(ParseContext *pc, int next,
255                      const uint8_t **buf, int *buf_size)
256 {
257     if (pc->overread) {
258         ff_dlog(NULL, "overread %d, state:%"PRIX32" next:%d index:%d o_index:%d\n",
259                 pc->overread, pc->state, next, pc->index, pc->overread_index);
260         ff_dlog(NULL, "%X %X %X %X\n",
261                 (*buf)[0], (*buf)[1], (*buf)[2], (*buf)[3]);
262     }
263
264     /* Copy overread bytes from last frame into buffer. */
265     for (; pc->overread > 0; pc->overread--)
266         pc->buffer[pc->index++] = pc->buffer[pc->overread_index++];
267
268     /* flush remaining if EOF */
269     if (!*buf_size && next == END_NOT_FOUND)
270         next = 0;
271
272     pc->last_index = pc->index;
273
274     /* copy into buffer end return */
275     if (next == END_NOT_FOUND) {
276         void *new_buffer = av_fast_realloc(pc->buffer, &pc->buffer_size,
277                                            *buf_size + pc->index +
278                                            AV_INPUT_BUFFER_PADDING_SIZE);
279
280         if (!new_buffer) {
281             av_log(NULL, AV_LOG_ERROR, "Failed to reallocate parser buffer to %d\n", *buf_size + pc->index + AV_INPUT_BUFFER_PADDING_SIZE);
282             pc->index = 0;
283             return AVERROR(ENOMEM);
284         }
285         pc->buffer = new_buffer;
286         memcpy(&pc->buffer[pc->index], *buf, *buf_size);
287         pc->index += *buf_size;
288         return -1;
289     }
290
291     av_assert0(next >= 0 || pc->buffer);
292
293     *buf_size          =
294     pc->overread_index = pc->index + next;
295
296     /* append to buffer */
297     if (pc->index) {
298         void *new_buffer = av_fast_realloc(pc->buffer, &pc->buffer_size,
299                                            next + pc->index +
300                                            AV_INPUT_BUFFER_PADDING_SIZE);
301         if (!new_buffer) {
302             av_log(NULL, AV_LOG_ERROR, "Failed to reallocate parser buffer to %d\n", next + pc->index + AV_INPUT_BUFFER_PADDING_SIZE);
303             pc->overread_index =
304             pc->index = 0;
305             return AVERROR(ENOMEM);
306         }
307         pc->buffer = new_buffer;
308         if (next > -AV_INPUT_BUFFER_PADDING_SIZE)
309             memcpy(&pc->buffer[pc->index], *buf,
310                    next + AV_INPUT_BUFFER_PADDING_SIZE);
311         pc->index = 0;
312         *buf      = pc->buffer;
313     }
314
315     /* store overread bytes */
316     for (; next < 0; next++) {
317         pc->state   = pc->state   << 8 | pc->buffer[pc->last_index + next];
318         pc->state64 = pc->state64 << 8 | pc->buffer[pc->last_index + next];
319         pc->overread++;
320     }
321
322     if (pc->overread) {
323         ff_dlog(NULL, "overread %d, state:%"PRIX32" next:%d index:%d o_index:%d\n",
324                 pc->overread, pc->state, next, pc->index, pc->overread_index);
325         ff_dlog(NULL, "%X %X %X %X\n",
326                 (*buf)[0], (*buf)[1], (*buf)[2], (*buf)[3]);
327     }
328
329     return 0;
330 }
331
332 void ff_parse_close(AVCodecParserContext *s)
333 {
334     ParseContext *pc = s->priv_data;
335
336     av_freep(&pc->buffer);
337 }
338
339 int ff_mpeg4video_split(AVCodecContext *avctx, const uint8_t *buf, int buf_size)
340 {
341     uint32_t state = -1;
342     const uint8_t *ptr = buf, *end = buf + buf_size;
343
344     while (ptr < end) {
345         ptr = avpriv_find_start_code(ptr, end, &state);
346         if (state == 0x1B3 || state == 0x1B6)
347             return ptr - 4 - buf;
348     }
349
350     return 0;
351 }