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