libavformat/mpjpegdec.c
9b56ac74
 /*
  * Multipart JPEG format
  * Copyright (c) 2015 Luca Barbato
  *
8985e7c5
  * This file is part of FFmpeg.
9b56ac74
  *
8985e7c5
  * FFmpeg is free software; you can redistribute it and/or
9b56ac74
  * 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.
  *
8985e7c5
  * FFmpeg is distributed in the hope that it will be useful,
9b56ac74
  * 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
8985e7c5
  * License along with FFmpeg; if not, write to the Free Software
9b56ac74
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
 #include "libavutil/avstring.h"
259c71c1
 #include "libavutil/opt.h"
9b56ac74
 
 #include "avformat.h"
 #include "internal.h"
79103f21
 #include "avio_internal.h"
9b56ac74
 
79103f21
 
 
 typedef struct MPJPEGDemuxContext {
259c71c1
     const AVClass *class;
79103f21
     char       *boundary;
     char       *searchstr;
     int         searchstr_len;
259c71c1
     int         strict_mime_boundary;
79103f21
 } MPJPEGDemuxContext;
 
 
 static void trim_right(char *p)
9b56ac74
 {
9ac5beaa
     char *end;
 
79103f21
     if (!p || !*p)
         return;
 
9ac5beaa
     end = p + strlen(p);
79103f21
     while (end > p && av_isspace(*(end-1)))
         *(--end) = '\0';
 }
9b56ac74
 
79103f21
 static int get_line(AVIOContext *pb, char *line, int line_size)
 {
     ff_get_line(pb, line, line_size);
9b56ac74
 
     if (pb->error)
         return pb->error;
 
     if (pb->eof_reached)
         return AVERROR_EOF;
 
79103f21
     trim_right(line);
9b56ac74
     return 0;
 }
 
1de21215
 
 
9b56ac74
 static int split_tag_value(char **tag, char **value, char *line)
 {
     char *p = line;
53e8bef2
     int  foundData = 0;
9b56ac74
 
53e8bef2
     *tag = NULL;
     *value = NULL;
 
 
     while (*p != '\0' && *p != ':') {
         if (!av_isspace(*p)) {
             foundData = 1;
         }
9b56ac74
         p++;
53e8bef2
     }
9b56ac74
     if (*p != ':')
53e8bef2
         return foundData ? AVERROR_INVALIDDATA : 0;
9b56ac74
 
     *p   = '\0';
     *tag = line;
1de21215
     trim_right(*tag);
9b56ac74
 
     p++;
 
     while (av_isspace(*p))
         p++;
 
     *value = p;
1de21215
     trim_right(*value);
9b56ac74
 
     return 0;
 }
 
79103f21
 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;
 }
0572bd1a
 
9b56ac74
 static int mpjpeg_read_probe(AVProbeData *p)
 {
     AVIOContext *pb;
     int ret = 0;
79103f21
     int size = 0;
9b56ac74
 
1382add5
     if (p->buf_size < 2 || p->buf[0] != '-' || p->buf[1] != '-')
         return 0;
 
9b56ac74
     pb = avio_alloc_context(p->buf, p->buf_size, 0, NULL, NULL, NULL, NULL);
     if (!pb)
c52c78cc
         return 0;
9b56ac74
 
79103f21
     ret = (parse_multipart_header(pb, &size, "--", NULL) > 0) ? AVPROBE_SCORE_MAX : 0;
402b18af
 
9b56ac74
     av_free(pb);
 
     return ret;
 }
 
 static int mpjpeg_read_header(AVFormatContext *s)
 {
     AVStream *st;
79103f21
     char boundary[70 + 2 + 1] = {0};
9b56ac74
     int64_t pos = avio_tell(s->pb);
     int ret;
 
79103f21
     do {
         ret = get_line(s->pb, boundary, sizeof(boundary));
         if (ret < 0)
             return ret;
     } while (!boundary[0]);
9b56ac74
 
     if (strncmp(boundary, "--", 2))
         return AVERROR_INVALIDDATA;
 
     st = avformat_new_stream(s, NULL);
8a26ae5f
     if (!st)
         return AVERROR(ENOMEM);
9b56ac74
 
     st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
     st->codec->codec_id   = AV_CODEC_ID_MJPEG;
 
     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;
 }
 
79103f21
 static int parse_multipart_header(AVIOContext *pb,
                             int* size,
                             const char* expected_boundary,
                             void *log_ctx)
9b56ac74
 {
     char line[128];
     int found_content_type = 0;
79103f21
     int ret;
 
     *size = -1;
9b56ac74
 
18f9308e
     // get the CRLF as empty string
0572bd1a
     ret = get_line(pb, line, sizeof(line));
9b56ac74
     if (ret < 0)
         return ret;
 
18f9308e
     /* some implementation do not provide the required
      * initial CRLF (see rfc1341 7.2.1)
      */
79103f21
     while (!line[0]) {
b95b8e5a
         ret = get_line(pb, line, sizeof(line));
18f9308e
         if (ret < 0)
             return ret;
     }
 
79103f21
     if (!av_strstart(line, expected_boundary, NULL)) {
405abdba
         if (log_ctx)
79103f21
         av_log(log_ctx,
             AV_LOG_ERROR,
             "Expected boundary '%s' not found, instead found a line of %zu bytes\n",
             expected_boundary,
             strlen(line));
 
9b56ac74
         return AVERROR_INVALIDDATA;
79103f21
     }
9b56ac74
 
0572bd1a
     while (!pb->eof_reached) {
9b56ac74
         char *tag, *value;
 
0572bd1a
         ret = get_line(pb, line, sizeof(line));
276ab7c1
         if (ret < 0) {
c8370a17
             if (ret == AVERROR_EOF)
276ab7c1
                 break;
9b56ac74
             return ret;
276ab7c1
         }
9b56ac74
 
         if (line[0] == '\0')
             break;
 
         ret = split_tag_value(&tag, &value, line);
         if (ret < 0)
             return ret;
53e8bef2
         if (value==NULL || tag==NULL)
             break;
9b56ac74
 
         if (!av_strcasecmp(tag, "Content-type")) {
             if (av_strcasecmp(value, "image/jpeg")) {
405abdba
                 if (log_ctx)
79103f21
                 av_log(log_ctx, AV_LOG_ERROR,
0572bd1a
                            "Unexpected %s : %s\n",
                            tag, value);
9b56ac74
                 return AVERROR_INVALIDDATA;
             } else
                 found_content_type = 1;
         } else if (!av_strcasecmp(tag, "Content-Length")) {
79103f21
             *size = parse_content_length(value);
             if ( *size < 0 )
405abdba
                 if (log_ctx)
79103f21
                 av_log(log_ctx, AV_LOG_WARNING,
                            "Invalid Content-Length value : %s\n",
                            value);
9b56ac74
         }
     }
 
79103f21
     return found_content_type ? 0 : AVERROR_INVALIDDATA;
9b56ac74
 }
 
79103f21
 
259c71c1
 static char* mpjpeg_get_boundary(AVIOContext* pb)
 {
     uint8_t *mime_type = NULL;
9696a01f
     const char *start;
     const char *end;
259c71c1
     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, ';');
7fd1c85e
         if (!start)
             break;
 
         start = start+1;
259c71c1
 
         while (av_isspace(*start))
             start++;
 
         if (!av_stristart(start, "boundary=", &start)) {
             end = strchr(start, ';');
             if (end)
                 len = end - start - 1;
             else
                 len = strlen(start);
09b8e97a
 
             /* some endpoints may enclose the boundary
               in Content-Type in quotes */
             if ( len>2 && *start == '"' && start[len-1] == '"' ) {
                 start++;
                 len -= 2;
             }
259c71c1
             res = av_strndup(start, len);
             break;
         }
     }
 
     av_freep(&mime_type);
     return res;
 }
 
 
9b56ac74
 static int mpjpeg_read_packet(AVFormatContext *s, AVPacket *pkt)
 {
79103f21
     int size;
9b56ac74
     int ret;
 
79103f21
     MPJPEGDemuxContext *mpjpeg = s->priv_data;
     if (mpjpeg->boundary == NULL) {
259c71c1
         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--");
         }
79103f21
         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);
 
9b56ac74
 
     if (ret < 0)
         return ret;
 
79103f21
     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 */
9ac5beaa
             char *start;
 
79103f21
             len = ret + remaining;
9ac5beaa
             start = pkt->data + pkt->size - len;
79103f21
             do {
                 if (!memcmp(start, mpjpeg->searchstr, mpjpeg->searchstr_len)) {
                     // got the boundary! rewind the stream
ddda2cc4
                     avio_seek(s->pb, -len, SEEK_CUR);
                     pkt->size -= len;
79103f21
                     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;
9b56ac74
 }
 
259c71c1
 #define OFFSET(x) offsetof(MPJPEGDemuxContext, x)
 
 #define DEC AV_OPT_FLAG_DECODING_PARAM
 const AVOption mpjpeg_options[] = {
43ecec0f
     { "strict_mime_boundary",  "require MIME boundaries match", OFFSET(strict_mime_boundary), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, DEC },
259c71c1
     { NULL }
 };
 
 
 static const AVClass mpjpeg_demuxer_class = {
     .class_name     = "MPJPEG demuxer",
     .item_name      = av_default_item_name,
     .option         = mpjpeg_options,
     .version        = LIBAVUTIL_VERSION_INT,
 };
 
9b56ac74
 AVInputFormat ff_mpjpeg_demuxer = {
     .name              = "mpjpeg",
     .long_name         = NULL_IF_CONFIG_SMALL("MIME multipart JPEG"),
     .mime_type         = "multipart/x-mixed-replace",
     .extensions        = "mjpg",
79103f21
     .priv_data_size    = sizeof(MPJPEGDemuxContext),
9b56ac74
     .read_probe        = mpjpeg_read_probe,
     .read_header       = mpjpeg_read_header,
     .read_packet       = mpjpeg_read_packet,
259c71c1
     .read_close        = mpjpeg_read_close,
     .priv_class        = &mpjpeg_demuxer_class
9b56ac74
 };
259c71c1