mpjpegdec.c 10.3 KB
Newer Older
1 2 3 4
/*
 * Multipart JPEG format
 * Copyright (c) 2015 Luca Barbato
 *
5
 * This file is part of FFmpeg.
6
 *
7
 * FFmpeg is free software; you can redistribute it and/or
8 9 10 11
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
12
 * FFmpeg is distributed in the hope that it will be useful,
13 14 15 16 17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * 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 20 21 22
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include "libavutil/avstring.h"
23
#include "libavutil/opt.h"
24 25 26

#include "avformat.h"
#include "internal.h"
27
#include "avio_internal.h"
28

29 30 31


typedef struct MPJPEGDemuxContext {
32
    const AVClass *class;
33 34 35
    char       *boundary;
    char       *searchstr;
    int         searchstr_len;
36
    int         strict_mime_boundary;
37 38 39 40
} MPJPEGDemuxContext;


static void trim_right(char *p)
41
{
42 43
    char *end;

44 45 46
    if (!p || !*p)
        return;

47
    end = p + strlen(p);
48 49 50
    while (end > p && av_isspace(*(end-1)))
        *(--end) = '\0';
}
51

52 53 54
static int get_line(AVIOContext *pb, char *line, int line_size)
{
    ff_get_line(pb, line, line_size);
55 56 57 58 59 60 61

    if (pb->error)
        return pb->error;

    if (pb->eof_reached)
        return AVERROR_EOF;

62
    trim_right(line);
63 64 65
    return 0;
}

66 67


68 69 70
static int split_tag_value(char **tag, char **value, char *line)
{
    char *p = line;
71
    int  foundData = 0;
72

73 74 75 76 77 78 79 80
    *tag = NULL;
    *value = NULL;


    while (*p != '\0' && *p != ':') {
        if (!av_isspace(*p)) {
            foundData = 1;
        }
81
        p++;
82
    }
83
    if (*p != ':')
84
        return foundData ? AVERROR_INVALIDDATA : 0;
85 86 87

    *p   = '\0';
    *tag = line;
88
    trim_right(*tag);
89 90 91 92 93 94 95

    p++;

    while (av_isspace(*p))
        p++;

    *value = p;
96
    trim_right(*value);
97 98 99 100

    return 0;
}

101 102 103 104 105 106 107 108 109 110 111 112
static int parse_multipart_header(AVIOContext *pb,
                                    int* size,
                                    const char* expected_boundary,
                                    void *log_ctx);

static int mpjpeg_read_close(AVFormatContext *s)
{
    MPJPEGDemuxContext *mpjpeg = s->priv_data;
    av_freep(&mpjpeg->boundary);
    av_freep(&mpjpeg->searchstr);
    return 0;
}
113

114 115 116 117
static int mpjpeg_read_probe(AVProbeData *p)
{
    AVIOContext *pb;
    int ret = 0;
118
    int size = 0;
119

120 121 122
    if (p->buf_size < 2 || p->buf[0] != '-' || p->buf[1] != '-')
        return 0;

123 124
    pb = avio_alloc_context(p->buf, p->buf_size, 0, NULL, NULL, NULL, NULL);
    if (!pb)
125
        return 0;
126

127
    ret = (parse_multipart_header(pb, &size, "--", NULL) >= 0) ? AVPROBE_SCORE_MAX : 0;
128

129
    avio_context_free(&pb);
130 131 132 133 134 135 136

    return ret;
}

static int mpjpeg_read_header(AVFormatContext *s)
{
    AVStream *st;
137
    char boundary[70 + 2 + 1] = {0};
138 139 140
    int64_t pos = avio_tell(s->pb);
    int ret;

141 142 143 144 145
    do {
        ret = get_line(s->pb, boundary, sizeof(boundary));
        if (ret < 0)
            return ret;
    } while (!boundary[0]);
146 147 148 149 150

    if (strncmp(boundary, "--", 2))
        return AVERROR_INVALIDDATA;

    st = avformat_new_stream(s, NULL);
151 152
    if (!st)
        return AVERROR(ENOMEM);
153

154 155
    st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
    st->codecpar->codec_id   = AV_CODEC_ID_MJPEG;
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174

    avpriv_set_pts_info(st, 60, 1, 25);

    avio_seek(s->pb, pos, SEEK_SET);

    return 0;
}

static int parse_content_length(const char *value)
{
    long int val = strtol(value, NULL, 10);

    if (val == LONG_MIN || val == LONG_MAX)
        return AVERROR(errno);
    if (val > INT_MAX)
        return AVERROR(ERANGE);
    return val;
}

175 176 177 178
static int parse_multipart_header(AVIOContext *pb,
                            int* size,
                            const char* expected_boundary,
                            void *log_ctx)
179 180 181
{
    char line[128];
    int found_content_type = 0;
182 183 184
    int ret;

    *size = -1;
185

186
    // get the CRLF as empty string
187
    ret = get_line(pb, line, sizeof(line));
188 189 190
    if (ret < 0)
        return ret;

191 192 193
    /* some implementation do not provide the required
     * initial CRLF (see rfc1341 7.2.1)
     */
194
    while (!line[0]) {
195
        ret = get_line(pb, line, sizeof(line));
196 197 198 199
        if (ret < 0)
            return ret;
    }

200
    if (!av_strstart(line, expected_boundary, NULL)) {
201
        if (log_ctx)
202 203
        av_log(log_ctx,
            AV_LOG_ERROR,
204
            "Expected boundary '%s' not found, instead found a line of %"SIZE_SPECIFIER" bytes\n",
205 206 207
            expected_boundary,
            strlen(line));

208
        return AVERROR_INVALIDDATA;
209
    }
210

211
    while (!pb->eof_reached) {
212 213
        char *tag, *value;

214
        ret = get_line(pb, line, sizeof(line));
215
        if (ret < 0) {
216
            if (ret == AVERROR_EOF)
217
                break;
218
            return ret;
219
        }
220 221 222 223 224 225 226

        if (line[0] == '\0')
            break;

        ret = split_tag_value(&tag, &value, line);
        if (ret < 0)
            return ret;
227 228
        if (value==NULL || tag==NULL)
            break;
229 230 231

        if (!av_strcasecmp(tag, "Content-type")) {
            if (av_strcasecmp(value, "image/jpeg")) {
232
                if (log_ctx)
233
                av_log(log_ctx, AV_LOG_ERROR,
234 235
                           "Unexpected %s : %s\n",
                           tag, value);
236 237 238 239
                return AVERROR_INVALIDDATA;
            } else
                found_content_type = 1;
        } else if (!av_strcasecmp(tag, "Content-Length")) {
240 241
            *size = parse_content_length(value);
            if ( *size < 0 )
242
                if (log_ctx)
243 244 245
                av_log(log_ctx, AV_LOG_WARNING,
                           "Invalid Content-Length value : %s\n",
                           value);
246 247 248
        }
    }

249
    return found_content_type ? 0 : AVERROR_INVALIDDATA;
250 251
}

252

253 254 255
static char* mpjpeg_get_boundary(AVIOContext* pb)
{
    uint8_t *mime_type = NULL;
256 257
    const char *start;
    const char *end;
258 259 260 261 262 263 264 265
    uint8_t *res = NULL;
    int     len;

    /* get MIME type, and skip to the first parameter */
    av_opt_get(pb, "mime_type", AV_OPT_SEARCH_CHILDREN, &mime_type);
    start = mime_type;
    while (start != NULL && *start != '\0') {
        start = strchr(start, ';');
266 267 268 269
        if (!start)
            break;

        start = start+1;
270 271 272 273 274 275 276 277 278 279

        while (av_isspace(*start))
            start++;

        if (!av_stristart(start, "boundary=", &start)) {
            end = strchr(start, ';');
            if (end)
                len = end - start - 1;
            else
                len = strlen(start);
280 281 282 283 284 285 286

            /* some endpoints may enclose the boundary
              in Content-Type in quotes */
            if ( len>2 && *start == '"' && start[len-1] == '"' ) {
                start++;
                len -= 2;
            }
287 288 289 290 291 292 293 294 295 296
            res = av_strndup(start, len);
            break;
        }
    }

    av_freep(&mime_type);
    return res;
}


297 298
static int mpjpeg_read_packet(AVFormatContext *s, AVPacket *pkt)
{
299
    int size;
300 301
    int ret;

302 303
    MPJPEGDemuxContext *mpjpeg = s->priv_data;
    if (mpjpeg->boundary == NULL) {
304 305 306 307 308 309 310 311 312 313 314
        uint8_t* boundary = NULL;
        if (mpjpeg->strict_mime_boundary) {
            boundary = mpjpeg_get_boundary(s->pb);
        }
        if (boundary != NULL) {
            mpjpeg->boundary = boundary;
            mpjpeg->searchstr = av_asprintf( "\r\n%s\r\n", boundary );
        } else {
            mpjpeg->boundary = av_strdup("--");
            mpjpeg->searchstr = av_strdup("\r\n--");
        }
315 316 317 318 319 320 321 322 323 324
        if (!mpjpeg->boundary || !mpjpeg->searchstr) {
            av_freep(&mpjpeg->boundary);
            av_freep(&mpjpeg->searchstr);
            return AVERROR(ENOMEM);
        }
        mpjpeg->searchstr_len = strlen(mpjpeg->searchstr);
    }

    ret = parse_multipart_header(s->pb, &size, mpjpeg->boundary, s);

325 326 327 328

    if (ret < 0)
        return ret;

329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
    if (size > 0) {
        /* size has been provided to us in MIME header */
        ret = av_get_packet(s->pb, pkt, size);
    } else {
        /* no size was given -- we read until the next boundary or end-of-file */
        int remaining = 0, len;

        const int read_chunk = 2048;
        av_init_packet(pkt);
        pkt->data = NULL;
        pkt->size = 0;
        pkt->pos  = avio_tell(s->pb);

        /* we may need to return as much as all we've read back to the buffer */
        ffio_ensure_seekback(s->pb, read_chunk);

        while ((ret = av_append_packet(s->pb, pkt, read_chunk - remaining)) >= 0) {
            /* scan the new data */
347 348
            char *start;

349
            len = ret + remaining;
350
            start = pkt->data + pkt->size - len;
351 352 353
            do {
                if (!memcmp(start, mpjpeg->searchstr, mpjpeg->searchstr_len)) {
                    // got the boundary! rewind the stream
354 355
                    avio_seek(s->pb, -len, SEEK_CUR);
                    pkt->size -= len;
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
                    return pkt->size;
                }
                len--;
                start++;
            } while (len >= mpjpeg->searchstr_len);
            remaining = len;
        }

        /* error or EOF occurred */
        if (ret == AVERROR_EOF) {
            ret = pkt->size > 0 ? pkt->size : AVERROR_EOF;
        } else {
            av_packet_unref(pkt);
        }
    }

    return ret;
373 374
}

375 376 377 378
#define OFFSET(x) offsetof(MPJPEGDemuxContext, x)

#define DEC AV_OPT_FLAG_DECODING_PARAM
const AVOption mpjpeg_options[] = {
379
    { "strict_mime_boundary",  "require MIME boundaries match", OFFSET(strict_mime_boundary), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, DEC },
380 381 382 383 384 385 386 387 388 389 390
    { NULL }
};


static const AVClass mpjpeg_demuxer_class = {
    .class_name     = "MPJPEG demuxer",
    .item_name      = av_default_item_name,
    .option         = mpjpeg_options,
    .version        = LIBAVUTIL_VERSION_INT,
};

391 392 393 394 395
AVInputFormat ff_mpjpeg_demuxer = {
    .name              = "mpjpeg",
    .long_name         = NULL_IF_CONFIG_SMALL("MIME multipart JPEG"),
    .mime_type         = "multipart/x-mixed-replace",
    .extensions        = "mjpg",
396
    .priv_data_size    = sizeof(MPJPEGDemuxContext),
397 398 399
    .read_probe        = mpjpeg_read_probe,
    .read_header       = mpjpeg_read_header,
    .read_packet       = mpjpeg_read_packet,
400
    .read_close        = mpjpeg_read_close,
401 402
    .priv_class        = &mpjpeg_demuxer_class,
    .flags             = AVFMT_NOTIMESTAMPS,
403
};
404 405