]> git.sesse.net Git - ffmpeg/blob - libavformat/mpjpegdec.c
Merge commit 'f0b769c16daafa64720dcba7fa81a9f5255e1d29'
[ffmpeg] / libavformat / mpjpegdec.c
1 /*
2  * Multipart JPEG format
3  * Copyright (c) 2015 Luca Barbato
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 "libavutil/avstring.h"
23 #include "libavutil/opt.h"
24
25 #include "avformat.h"
26 #include "internal.h"
27 #include "avio_internal.h"
28
29
30
31 typedef struct MPJPEGDemuxContext {
32     const AVClass *class;
33     char       *boundary;
34     char       *searchstr;
35     int         searchstr_len;
36     int         strict_mime_boundary;
37 } MPJPEGDemuxContext;
38
39
40 static void trim_right(char *p)
41 {
42     char *end;
43
44     if (!p || !*p)
45         return;
46
47     end = p + strlen(p);
48     while (end > p && av_isspace(*(end-1)))
49         *(--end) = '\0';
50 }
51
52 static int get_line(AVIOContext *pb, char *line, int line_size)
53 {
54     ff_get_line(pb, line, line_size);
55
56     if (pb->error)
57         return pb->error;
58
59     if (pb->eof_reached)
60         return AVERROR_EOF;
61
62     trim_right(line);
63     return 0;
64 }
65
66
67
68 static int split_tag_value(char **tag, char **value, char *line)
69 {
70     char *p = line;
71     int  foundData = 0;
72
73     *tag = NULL;
74     *value = NULL;
75
76
77     while (*p != '\0' && *p != ':') {
78         if (!av_isspace(*p)) {
79             foundData = 1;
80         }
81         p++;
82     }
83     if (*p != ':')
84         return foundData ? AVERROR_INVALIDDATA : 0;
85
86     *p   = '\0';
87     *tag = line;
88     trim_right(*tag);
89
90     p++;
91
92     while (av_isspace(*p))
93         p++;
94
95     *value = p;
96     trim_right(*value);
97
98     return 0;
99 }
100
101 static int parse_multipart_header(AVIOContext *pb,
102                                     int* size,
103                                     const char* expected_boundary,
104                                     void *log_ctx);
105
106 static int mpjpeg_read_close(AVFormatContext *s)
107 {
108     MPJPEGDemuxContext *mpjpeg = s->priv_data;
109     av_freep(&mpjpeg->boundary);
110     av_freep(&mpjpeg->searchstr);
111     return 0;
112 }
113
114 static int mpjpeg_read_probe(AVProbeData *p)
115 {
116     AVIOContext *pb;
117     int ret = 0;
118     int size = 0;
119
120     if (p->buf_size < 2 || p->buf[0] != '-' || p->buf[1] != '-')
121         return 0;
122
123     pb = avio_alloc_context(p->buf, p->buf_size, 0, NULL, NULL, NULL, NULL);
124     if (!pb)
125         return 0;
126
127     ret = (parse_multipart_header(pb, &size, "--", NULL) > 0) ? AVPROBE_SCORE_MAX : 0;
128
129     av_free(pb);
130
131     return ret;
132 }
133
134 static int mpjpeg_read_header(AVFormatContext *s)
135 {
136     AVStream *st;
137     char boundary[70 + 2 + 1] = {0};
138     int64_t pos = avio_tell(s->pb);
139     int ret;
140
141     do {
142         ret = get_line(s->pb, boundary, sizeof(boundary));
143         if (ret < 0)
144             return ret;
145     } while (!boundary[0]);
146
147     if (strncmp(boundary, "--", 2))
148         return AVERROR_INVALIDDATA;
149
150     st = avformat_new_stream(s, NULL);
151     if (!st)
152         return AVERROR(ENOMEM);
153
154     st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
155     st->codec->codec_id   = AV_CODEC_ID_MJPEG;
156
157     avpriv_set_pts_info(st, 60, 1, 25);
158
159     avio_seek(s->pb, pos, SEEK_SET);
160
161     return 0;
162 }
163
164 static int parse_content_length(const char *value)
165 {
166     long int val = strtol(value, NULL, 10);
167
168     if (val == LONG_MIN || val == LONG_MAX)
169         return AVERROR(errno);
170     if (val > INT_MAX)
171         return AVERROR(ERANGE);
172     return val;
173 }
174
175 static int parse_multipart_header(AVIOContext *pb,
176                             int* size,
177                             const char* expected_boundary,
178                             void *log_ctx)
179 {
180     char line[128];
181     int found_content_type = 0;
182     int ret;
183
184     *size = -1;
185
186     // get the CRLF as empty string
187     ret = get_line(pb, line, sizeof(line));
188     if (ret < 0)
189         return ret;
190
191     /* some implementation do not provide the required
192      * initial CRLF (see rfc1341 7.2.1)
193      */
194     while (!line[0]) {
195         ret = get_line(pb, line, sizeof(line));
196         if (ret < 0)
197             return ret;
198     }
199
200     if (!av_strstart(line, expected_boundary, NULL)) {
201         av_log(log_ctx,
202             AV_LOG_ERROR,
203             "Expected boundary '%s' not found, instead found a line of %zu bytes\n",
204             expected_boundary,
205             strlen(line));
206
207         return AVERROR_INVALIDDATA;
208     }
209
210     while (!pb->eof_reached) {
211         char *tag, *value;
212
213         ret = get_line(pb, line, sizeof(line));
214         if (ret < 0) {
215             if (ret == AVERROR_EOF)
216                 break;
217             return ret;
218         }
219
220         if (line[0] == '\0')
221             break;
222
223         ret = split_tag_value(&tag, &value, line);
224         if (ret < 0)
225             return ret;
226         if (value==NULL || tag==NULL)
227             break;
228
229         if (!av_strcasecmp(tag, "Content-type")) {
230             if (av_strcasecmp(value, "image/jpeg")) {
231                 av_log(log_ctx, AV_LOG_ERROR,
232                            "Unexpected %s : %s\n",
233                            tag, value);
234                 return AVERROR_INVALIDDATA;
235             } else
236                 found_content_type = 1;
237         } else if (!av_strcasecmp(tag, "Content-Length")) {
238             *size = parse_content_length(value);
239             if ( *size < 0 )
240                 av_log(log_ctx, AV_LOG_WARNING,
241                            "Invalid Content-Length value : %s\n",
242                            value);
243         }
244     }
245
246     return found_content_type ? 0 : AVERROR_INVALIDDATA;
247 }
248
249
250 static char* mpjpeg_get_boundary(AVIOContext* pb)
251 {
252     uint8_t *mime_type = NULL;
253     const char *start;
254     const char *end;
255     uint8_t *res = NULL;
256     int     len;
257
258     /* get MIME type, and skip to the first parameter */
259     av_opt_get(pb, "mime_type", AV_OPT_SEARCH_CHILDREN, &mime_type);
260     start = mime_type;
261     while (start != NULL && *start != '\0') {
262         start = strchr(start, ';');
263         if (!start)
264             break;
265
266         start = start+1;
267
268         while (av_isspace(*start))
269             start++;
270
271         if (!av_stristart(start, "boundary=", &start)) {
272             end = strchr(start, ';');
273             if (end)
274                 len = end - start - 1;
275             else
276                 len = strlen(start);
277             res = av_strndup(start, len);
278             break;
279         }
280     }
281
282     av_freep(&mime_type);
283     return res;
284 }
285
286
287 static int mpjpeg_read_packet(AVFormatContext *s, AVPacket *pkt)
288 {
289     int size;
290     int ret;
291
292     MPJPEGDemuxContext *mpjpeg = s->priv_data;
293     if (mpjpeg->boundary == NULL) {
294         uint8_t* boundary = NULL;
295         if (mpjpeg->strict_mime_boundary) {
296             boundary = mpjpeg_get_boundary(s->pb);
297         }
298         if (boundary != NULL) {
299             mpjpeg->boundary = boundary;
300             mpjpeg->searchstr = av_asprintf( "\r\n%s\r\n", boundary );
301         } else {
302             mpjpeg->boundary = av_strdup("--");
303             mpjpeg->searchstr = av_strdup("\r\n--");
304         }
305         if (!mpjpeg->boundary || !mpjpeg->searchstr) {
306             av_freep(&mpjpeg->boundary);
307             av_freep(&mpjpeg->searchstr);
308             return AVERROR(ENOMEM);
309         }
310         mpjpeg->searchstr_len = strlen(mpjpeg->searchstr);
311     }
312
313     ret = parse_multipart_header(s->pb, &size, mpjpeg->boundary, s);
314
315
316     if (ret < 0)
317         return ret;
318
319     if (size > 0) {
320         /* size has been provided to us in MIME header */
321         ret = av_get_packet(s->pb, pkt, size);
322     } else {
323         /* no size was given -- we read until the next boundary or end-of-file */
324         int remaining = 0, len;
325
326         const int read_chunk = 2048;
327         av_init_packet(pkt);
328         pkt->data = NULL;
329         pkt->size = 0;
330         pkt->pos  = avio_tell(s->pb);
331
332         /* we may need to return as much as all we've read back to the buffer */
333         ffio_ensure_seekback(s->pb, read_chunk);
334
335         while ((ret = av_append_packet(s->pb, pkt, read_chunk - remaining)) >= 0) {
336             /* scan the new data */
337             char *start;
338
339             len = ret + remaining;
340             start = pkt->data + pkt->size - len;
341             do {
342                 if (!memcmp(start, mpjpeg->searchstr, mpjpeg->searchstr_len)) {
343                     // got the boundary! rewind the stream
344                     avio_seek(s->pb, -(len-2), SEEK_CUR);
345                     pkt->size -= (len-2);
346                     return pkt->size;
347                 }
348                 len--;
349                 start++;
350             } while (len >= mpjpeg->searchstr_len);
351             remaining = len;
352         }
353
354         /* error or EOF occurred */
355         if (ret == AVERROR_EOF) {
356             ret = pkt->size > 0 ? pkt->size : AVERROR_EOF;
357         } else {
358             av_packet_unref(pkt);
359         }
360     }
361
362     return ret;
363 }
364
365 #define OFFSET(x) offsetof(MPJPEGDemuxContext, x)
366
367 #define DEC AV_OPT_FLAG_DECODING_PARAM
368 const AVOption mpjpeg_options[] = {
369     { "strict_mime_boundary",  "require MIME boundaries match", OFFSET(strict_mime_boundary), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, DEC },
370     { NULL }
371 };
372
373
374 static const AVClass mpjpeg_demuxer_class = {
375     .class_name     = "MPJPEG demuxer",
376     .item_name      = av_default_item_name,
377     .option         = mpjpeg_options,
378     .version        = LIBAVUTIL_VERSION_INT,
379 };
380
381 AVInputFormat ff_mpjpeg_demuxer = {
382     .name              = "mpjpeg",
383     .long_name         = NULL_IF_CONFIG_SMALL("MIME multipart JPEG"),
384     .mime_type         = "multipart/x-mixed-replace",
385     .extensions        = "mjpg",
386     .priv_data_size    = sizeof(MPJPEGDemuxContext),
387     .read_probe        = mpjpeg_read_probe,
388     .read_header       = mpjpeg_read_header,
389     .read_packet       = mpjpeg_read_packet,
390     .read_close        = mpjpeg_read_close,
391     .priv_class        = &mpjpeg_demuxer_class
392 };
393
394