]> git.sesse.net Git - ffmpeg/blob - libavformat/rtpdec_jpeg.c
c77ecbfdef5893f231f15f9098cc896f2c16f929
[ffmpeg] / libavformat / rtpdec_jpeg.c
1 /*
2  * RTP JPEG-compressed Video Depacketizer, RFC 2435
3  * Copyright (c) 2012 Samuel Pitoiset
4  *
5  * This file is part of Libav.
6  *
7  * Libav 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  * Libav 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 Libav; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "avformat.h"
23 #include "rtpdec_formats.h"
24 #include "libavutil/intreadwrite.h"
25 #include "libavcodec/mjpeg.h"
26
27 /**
28  * RTP/JPEG specific private data.
29  */
30 struct PayloadContext {
31     AVIOContext *frame;         ///< current frame buffer
32     uint32_t    timestamp;      ///< current frame timestamp
33     int         hdr_size;       ///< size of the current frame header
34 };
35
36 static PayloadContext *jpeg_new_context(void)
37 {
38     return av_mallocz(sizeof(PayloadContext));
39 }
40
41 static inline void free_frame_if_needed(PayloadContext *jpeg)
42 {
43     if (jpeg->frame) {
44         uint8_t *p;
45         avio_close_dyn_buf(jpeg->frame, &p);
46         av_free(p);
47         jpeg->frame = NULL;
48     }
49 }
50
51 static void jpeg_free_context(PayloadContext *jpeg)
52 {
53     free_frame_if_needed(jpeg);
54     av_free(jpeg);
55 }
56
57 static void jpeg_create_huffman_table(PutBitContext *p, int table_class,
58                                       int table_id, const uint8_t *bits_table,
59                                       const uint8_t *value_table)
60 {
61     int i, n = 0;
62
63     put_bits(p, 8, 0);
64     put_bits(p, 4, table_class);
65     put_bits(p, 4, table_id);
66
67     for (i = 1; i <= 16; i++) {
68         n += bits_table[i];
69         put_bits(p, 8, bits_table[i]);
70     }
71
72     for (i = 0; i < n; i++) {
73         put_bits(p, 8, value_table[i]);
74     }
75 }
76
77 static int jpeg_create_header(uint8_t *buf, int size, uint32_t type, uint32_t w,
78                               uint32_t h, const uint8_t *qtable, int nb_qtable)
79 {
80     PutBitContext pbc;
81
82     init_put_bits(&pbc, buf, size);
83
84     /* Convert from blocks to pixels. */
85     w <<= 3;
86     h <<= 3;
87
88     /* SOI */
89     put_marker(&pbc, SOI);
90
91     /* JFIF header */
92     put_marker(&pbc, APP0);
93     put_bits(&pbc, 16, 16);
94     avpriv_put_string(&pbc, "JFIF", 1);
95     put_bits(&pbc, 16, 0x0201);
96     put_bits(&pbc, 8, 0);
97     put_bits(&pbc, 16, 1);
98     put_bits(&pbc, 16, 1);
99     put_bits(&pbc, 8, 0);
100     put_bits(&pbc, 8, 0);
101
102     /* DQT */
103     put_marker(&pbc, DQT);
104     if (nb_qtable == 2) {
105         put_bits(&pbc, 16, 2 + 2 * (1 + 64));
106     } else {
107         put_bits(&pbc, 16, 2 + 1 * (1 + 64));
108     }
109     put_bits(&pbc, 8, 0);
110
111     /* Each table is an array of 64 values given in zig-zag
112      * order, identical to the format used in a JFIF DQT
113      * marker segment. */
114     avpriv_copy_bits(&pbc, qtable, 64 * 8);
115
116     if (nb_qtable == 2) {
117         put_bits(&pbc, 8, 1);
118         avpriv_copy_bits(&pbc, qtable + 64, 64 * 8);
119     }
120
121     /* DHT */
122     put_marker(&pbc, DHT);
123
124     jpeg_create_huffman_table(&pbc, 0, 0, avpriv_mjpeg_bits_dc_luminance,
125                               avpriv_mjpeg_val_dc);
126     jpeg_create_huffman_table(&pbc, 0, 1, avpriv_mjpeg_bits_dc_chrominance,
127                               avpriv_mjpeg_val_dc);
128     jpeg_create_huffman_table(&pbc, 1, 0, avpriv_mjpeg_bits_ac_luminance,
129                               avpriv_mjpeg_val_ac_luminance);
130     jpeg_create_huffman_table(&pbc, 1, 1, avpriv_mjpeg_bits_ac_chrominance,
131                               avpriv_mjpeg_val_ac_chrominance);
132
133     /* SOF0 */
134     put_marker(&pbc, SOF0);
135     put_bits(&pbc, 16, 17);
136     put_bits(&pbc, 8, 8);
137     put_bits(&pbc, 8, h >> 8);
138     put_bits(&pbc, 8, h);
139     put_bits(&pbc, 8, w >> 8);
140     put_bits(&pbc, 8, w);
141     put_bits(&pbc, 8, 3);
142     put_bits(&pbc, 8, 1);
143     put_bits(&pbc, 8, type ? 34 : 33);
144     put_bits(&pbc, 8, 0);
145     put_bits(&pbc, 8, 2);
146     put_bits(&pbc, 8, 17);
147     put_bits(&pbc, 8, nb_qtable == 2 ? 1 : 0);
148     put_bits(&pbc, 8, 3);
149     put_bits(&pbc, 8, 17);
150     put_bits(&pbc, 8, nb_qtable == 2 ? 1 : 0);
151
152     /* SOS */
153     put_marker(&pbc, SOS);
154     put_bits(&pbc, 16, 12);
155     put_bits(&pbc, 8, 3);
156     put_bits(&pbc, 8, 1);
157     put_bits(&pbc, 8, 0);
158     put_bits(&pbc, 8, 2);
159     put_bits(&pbc, 8, 17);
160     put_bits(&pbc, 8, 3);
161     put_bits(&pbc, 8, 17);
162     put_bits(&pbc, 8, 0);
163     put_bits(&pbc, 8, 63);
164     put_bits(&pbc, 8, 0);
165
166     /* Fill the buffer. */
167     flush_put_bits(&pbc);
168
169     /* Return the length in bytes of the JPEG header. */
170     return put_bits_count(&pbc) / 8;
171 }
172
173 static int jpeg_parse_packet(AVFormatContext *ctx, PayloadContext *jpeg,
174                              AVStream *st, AVPacket *pkt, uint32_t *timestamp,
175                              const uint8_t *buf, int len, int flags)
176 {
177     uint8_t type, q, width, height;
178     const uint8_t *qtables = NULL;
179     uint16_t qtable_len;
180     uint32_t off;
181     int ret;
182
183     if (len < 8) {
184         av_log(ctx, AV_LOG_ERROR, "Too short RTP/JPEG packet.\n");
185         return AVERROR_INVALIDDATA;
186     }
187
188     /* Parse the main JPEG header. */
189     off    = AV_RB24(buf + 1);  /* fragment byte offset */
190     type   = AV_RB8(buf + 4);   /* id of jpeg decoder params */
191     q      = AV_RB8(buf + 5);   /* quantization factor (or table id) */
192     width  = AV_RB8(buf + 6);   /* frame width in 8 pixel blocks */
193     height = AV_RB8(buf + 7);   /* frame height in 8 pixel blocks */
194     buf += 8;
195     len -= 8;
196
197     /* Parse the restart marker header. */
198     if (type > 63) {
199         av_log(ctx, AV_LOG_ERROR,
200                "Unimplemented RTP/JPEG restart marker header.\n");
201         return AVERROR_PATCHWELCOME;
202     }
203
204     /* Parse the quantization table header. */
205     if (q > 127 && off == 0) {
206         uint8_t precision;
207
208         if (len < 4) {
209             av_log(ctx, AV_LOG_ERROR, "Too short RTP/JPEG packet.\n");
210             return AVERROR_INVALIDDATA;
211         }
212
213         /* The first byte is reserved for future use. */
214         precision  = AV_RB8(buf + 1);    /* size of coefficients */
215         qtable_len = AV_RB16(buf + 2);   /* length in bytes */
216         buf += 4;
217         len -= 4;
218
219         if (precision)
220             av_log(ctx, AV_LOG_WARNING, "Only 8-bit precision is supported.\n");
221
222         if (q == 255 && qtable_len == 0) {
223             av_log(ctx, AV_LOG_ERROR,
224                    "Invalid RTP/JPEG packet. Quantization tables not found.\n");
225             return AVERROR_INVALIDDATA;
226         }
227
228         if (qtable_len > 0) {
229             if (len < qtable_len) {
230                 av_log(ctx, AV_LOG_ERROR, "Too short RTP/JPEG packet.\n");
231                 return AVERROR_INVALIDDATA;
232             }
233             qtables = buf;
234             buf += qtable_len;
235             len -= qtable_len;
236         }
237     }
238
239     if (off == 0) {
240         /* Start of JPEG data packet. */
241         uint8_t hdr[1024];
242
243         /* Skip the current frame in case of the end packet
244          * has been lost somewhere. */
245         free_frame_if_needed(jpeg);
246
247         if ((ret = avio_open_dyn_buf(&jpeg->frame)) < 0)
248             return ret;
249         jpeg->timestamp = *timestamp;
250
251         if (!qtables) {
252             av_log(ctx, AV_LOG_ERROR,
253                    "Unimplemented default quantization tables.\n");
254             return AVERROR_PATCHWELCOME;
255         }
256
257         /* Generate a frame and scan headers that can be prepended to the
258          * RTP/JPEG data payload to produce a JPEG compressed image in
259          * interchange format. */
260         jpeg->hdr_size = jpeg_create_header(hdr, sizeof(hdr), type, width,
261                                             height, qtables,
262                                             qtable_len > 64 ? 2 : 1);
263
264         /* Copy JPEG header to frame buffer. */
265         avio_write(jpeg->frame, hdr, jpeg->hdr_size);
266     }
267
268     if (!jpeg->frame) {
269         av_log(ctx, AV_LOG_ERROR,
270                "Received packet without a start chunk; dropping frame.\n");
271         return AVERROR(EAGAIN);
272     }
273
274     if (jpeg->timestamp != *timestamp) {
275         /* Skip the current frame if timestamp is incorrect.
276          * A start packet has been lost somewhere. */
277         free_frame_if_needed(jpeg);
278         av_log(ctx, AV_LOG_ERROR, "RTP timestamps don't match.\n");
279         return AVERROR_INVALIDDATA;
280     }
281
282     if (off != avio_tell(jpeg->frame) - jpeg->hdr_size) {
283         av_log(ctx, AV_LOG_ERROR,
284                "Missing packets; dropping frame.\n");
285         return AVERROR(EAGAIN);
286     }
287
288     /* Copy data to frame buffer. */
289     avio_write(jpeg->frame, buf, len);
290
291     if (flags & RTP_FLAG_MARKER) {
292         /* End of JPEG data packet. */
293         PutBitContext pbc;
294         uint8_t buf[2];
295
296         /* Put EOI marker. */
297         init_put_bits(&pbc, buf, sizeof(buf));
298         put_marker(&pbc, EOI);
299         flush_put_bits(&pbc);
300         avio_write(jpeg->frame, buf, sizeof(buf));
301
302         /* Prepare the JPEG packet. */
303         av_init_packet(pkt);
304         pkt->size = avio_close_dyn_buf(jpeg->frame, &pkt->data);
305         if (pkt->size < 0) {
306             av_log(ctx, AV_LOG_ERROR,
307                    "Error occured when getting frame buffer.\n");
308             jpeg->frame = NULL;
309             return pkt->size;
310         }
311         pkt->stream_index = st->index;
312         pkt->destruct     = av_destruct_packet;
313
314         /* Re-init the frame buffer. */
315         jpeg->frame = NULL;
316
317         return 0;
318     }
319
320     return AVERROR(EAGAIN);
321 }
322
323 RTPDynamicProtocolHandler ff_jpeg_dynamic_handler = {
324     .enc_name          = "JPEG",
325     .codec_type        = AVMEDIA_TYPE_VIDEO,
326     .codec_id          = AV_CODEC_ID_MJPEG,
327     .alloc             = jpeg_new_context,
328     .free              = jpeg_free_context,
329     .parse_packet      = jpeg_parse_packet,
330     .static_payload_id = 26,
331 };