]> git.sesse.net Git - ffmpeg/blob - libavformat/nuv.c
Merge commit '7e01d48cfd168c3dfc663f03a3b6a98e0ecba328'
[ffmpeg] / libavformat / nuv.c
1 /*
2  * NuppelVideo demuxer.
3  * Copyright (c) 2006 Reimar Doeffinger
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/channel_layout.h"
23 #include "libavutil/imgutils.h"
24 #include "libavutil/intreadwrite.h"
25 #include "libavutil/intfloat.h"
26 #include "avformat.h"
27 #include "internal.h"
28 #include "riff.h"
29
30 static const AVCodecTag nuv_audio_tags[] = {
31     { AV_CODEC_ID_PCM_S16LE, MKTAG('R', 'A', 'W', 'A') },
32     { AV_CODEC_ID_MP3,       MKTAG('L', 'A', 'M', 'E') },
33     { AV_CODEC_ID_NONE,      0 },
34 };
35
36 typedef struct NUVContext {
37     int v_id;
38     int a_id;
39     int rtjpg_video;
40 } NUVContext;
41
42 typedef enum {
43     NUV_VIDEO     = 'V',
44     NUV_EXTRADATA = 'D',
45     NUV_AUDIO     = 'A',
46     NUV_SEEKP     = 'R',
47     NUV_MYTHEXT   = 'X'
48 } nuv_frametype;
49
50 static int nuv_probe(AVProbeData *p)
51 {
52     if (!memcmp(p->buf, "NuppelVideo", 12))
53         return AVPROBE_SCORE_MAX;
54     if (!memcmp(p->buf, "MythTVVideo", 12))
55         return AVPROBE_SCORE_MAX;
56     return 0;
57 }
58
59 /// little macro to sanitize packet size
60 #define PKTSIZE(s) (s &  0xffffff)
61
62 /**
63  * @brief read until we found all data needed for decoding
64  * @param vst video stream of which to change parameters
65  * @param ast video stream of which to change parameters
66  * @param myth set if this is a MythTVVideo format file
67  * @return 0 or AVERROR code
68  */
69 static int get_codec_data(AVIOContext *pb, AVStream *vst,
70                           AVStream *ast, int myth)
71 {
72     nuv_frametype frametype;
73
74     if (!vst && !myth)
75         return 1; // no codec data needed
76     while (!avio_feof(pb)) {
77         int size, subtype;
78
79         frametype = avio_r8(pb);
80         switch (frametype) {
81         case NUV_EXTRADATA:
82             subtype = avio_r8(pb);
83             avio_skip(pb, 6);
84             size = PKTSIZE(avio_rl32(pb));
85             if (vst && subtype == 'R') {
86                 if (vst->codecpar->extradata) {
87                     av_freep(&vst->codecpar->extradata);
88                     vst->codecpar->extradata_size = 0;
89                 }
90                 if (ff_get_extradata(vst->codecpar, pb, size) < 0)
91                     return AVERROR(ENOMEM);
92                 size = 0;
93                 if (!myth)
94                     return 0;
95             }
96             break;
97         case NUV_MYTHEXT:
98             avio_skip(pb, 7);
99             size = PKTSIZE(avio_rl32(pb));
100             if (size != 128 * 4)
101                 break;
102             avio_rl32(pb); // version
103             if (vst) {
104                 vst->codecpar->codec_tag = avio_rl32(pb);
105                 vst->codecpar->codec_id =
106                     ff_codec_get_id(ff_codec_bmp_tags, vst->codecpar->codec_tag);
107                 if (vst->codecpar->codec_tag == MKTAG('R', 'J', 'P', 'G'))
108                     vst->codecpar->codec_id = AV_CODEC_ID_NUV;
109             } else
110                 avio_skip(pb, 4);
111
112             if (ast) {
113                 int id;
114
115                 ast->codecpar->codec_tag             = avio_rl32(pb);
116                 ast->codecpar->sample_rate           = avio_rl32(pb);
117                 ast->codecpar->bits_per_coded_sample = avio_rl32(pb);
118                 ast->codecpar->channels              = avio_rl32(pb);
119                 ast->codecpar->channel_layout        = 0;
120
121                 id = ff_wav_codec_get_id(ast->codecpar->codec_tag,
122                                          ast->codecpar->bits_per_coded_sample);
123                 if (id == AV_CODEC_ID_NONE) {
124                     id = ff_codec_get_id(nuv_audio_tags, ast->codecpar->codec_tag);
125                     if (id == AV_CODEC_ID_PCM_S16LE)
126                         id = ff_get_pcm_codec_id(ast->codecpar->bits_per_coded_sample,
127                                                  0, 0, ~1);
128                 }
129                 ast->codecpar->codec_id = id;
130
131                 ast->need_parsing = AVSTREAM_PARSE_FULL;
132             } else
133                 avio_skip(pb, 4 * 4);
134
135             size -= 6 * 4;
136             avio_skip(pb, size);
137             return 0;
138         case NUV_SEEKP:
139             size = 11;
140             break;
141         default:
142             avio_skip(pb, 7);
143             size = PKTSIZE(avio_rl32(pb));
144             break;
145         }
146         avio_skip(pb, size);
147     }
148
149     return 0;
150 }
151
152 static int nuv_header(AVFormatContext *s)
153 {
154     NUVContext *ctx = s->priv_data;
155     AVIOContext *pb = s->pb;
156     char id_string[12];
157     double aspect, fps;
158     int is_mythtv, width, height, v_packs, a_packs, ret;
159     AVStream *vst = NULL, *ast = NULL;
160
161     avio_read(pb, id_string, 12);
162     is_mythtv = !memcmp(id_string, "MythTVVideo", 12);
163     avio_skip(pb, 5);       // version string
164     avio_skip(pb, 3);       // padding
165     width  = avio_rl32(pb);
166     height = avio_rl32(pb);
167     avio_rl32(pb);          // unused, "desiredwidth"
168     avio_rl32(pb);          // unused, "desiredheight"
169     avio_r8(pb);            // 'P' == progressive, 'I' == interlaced
170     avio_skip(pb, 3);       // padding
171     aspect = av_int2double(avio_rl64(pb));
172     if (aspect > 0.9999 && aspect < 1.0001)
173         aspect = 4.0 / 3.0;
174     fps = av_int2double(avio_rl64(pb));
175     if (fps < 0.0f) {
176         if (s->error_recognition & AV_EF_EXPLODE) {
177             av_log(s, AV_LOG_ERROR, "Invalid frame rate %f\n", fps);
178             return AVERROR_INVALIDDATA;
179         } else {
180             av_log(s, AV_LOG_WARNING, "Invalid frame rate %f, setting to 0.\n", fps);
181             fps = 0.0f;
182         }
183     }
184
185     // number of packets per stream type, -1 means unknown, e.g. streaming
186     v_packs = avio_rl32(pb);
187     a_packs = avio_rl32(pb);
188     avio_rl32(pb); // text
189
190     avio_rl32(pb); // keyframe distance (?)
191
192     if (v_packs) {
193         vst = avformat_new_stream(s, NULL);
194         if (!vst)
195             return AVERROR(ENOMEM);
196         ctx->v_id = vst->index;
197
198         ret = av_image_check_size(width, height, 0, ctx);
199         if (ret < 0)
200             return ret;
201
202         vst->codecpar->codec_type            = AVMEDIA_TYPE_VIDEO;
203         vst->codecpar->codec_id              = AV_CODEC_ID_NUV;
204         vst->codecpar->width                 = width;
205         vst->codecpar->height                = height;
206         vst->codecpar->bits_per_coded_sample = 10;
207         vst->sample_aspect_ratio          = av_d2q(aspect * height / width,
208                                                    10000);
209 #if FF_API_R_FRAME_RATE
210         vst->r_frame_rate =
211 #endif
212         vst->avg_frame_rate = av_d2q(fps, 60000);
213         avpriv_set_pts_info(vst, 32, 1, 1000);
214     } else
215         ctx->v_id = -1;
216
217     if (a_packs) {
218         ast = avformat_new_stream(s, NULL);
219         if (!ast)
220             return AVERROR(ENOMEM);
221         ctx->a_id = ast->index;
222
223         ast->codecpar->codec_type            = AVMEDIA_TYPE_AUDIO;
224         ast->codecpar->codec_id              = AV_CODEC_ID_PCM_S16LE;
225         ast->codecpar->channels              = 2;
226         ast->codecpar->channel_layout        = AV_CH_LAYOUT_STEREO;
227         ast->codecpar->sample_rate           = 44100;
228         ast->codecpar->bit_rate              = 2 * 2 * 44100 * 8;
229         ast->codecpar->block_align           = 2 * 2;
230         ast->codecpar->bits_per_coded_sample = 16;
231         avpriv_set_pts_info(ast, 32, 1, 1000);
232     } else
233         ctx->a_id = -1;
234
235     if ((ret = get_codec_data(pb, vst, ast, is_mythtv)) < 0)
236         return ret;
237
238     ctx->rtjpg_video = vst && vst->codecpar->codec_id == AV_CODEC_ID_NUV;
239
240     return 0;
241 }
242
243 #define HDRSIZE 12
244
245 static int nuv_packet(AVFormatContext *s, AVPacket *pkt)
246 {
247     NUVContext *ctx = s->priv_data;
248     AVIOContext *pb = s->pb;
249     uint8_t hdr[HDRSIZE];
250     nuv_frametype frametype;
251     int ret, size;
252
253     while (!avio_feof(pb)) {
254         int copyhdrsize = ctx->rtjpg_video ? HDRSIZE : 0;
255         uint64_t pos    = avio_tell(pb);
256
257         ret = avio_read(pb, hdr, HDRSIZE);
258         if (ret < HDRSIZE)
259             return ret < 0 ? ret : AVERROR(EIO);
260
261         frametype = hdr[0];
262         size      = PKTSIZE(AV_RL32(&hdr[8]));
263
264         switch (frametype) {
265         case NUV_EXTRADATA:
266             if (!ctx->rtjpg_video) {
267                 avio_skip(pb, size);
268                 break;
269             }
270         case NUV_VIDEO:
271             if (ctx->v_id < 0) {
272                 av_log(s, AV_LOG_ERROR, "Video packet in file without video stream!\n");
273                 avio_skip(pb, size);
274                 break;
275             }
276             ret = av_new_packet(pkt, copyhdrsize + size);
277             if (ret < 0)
278                 return ret;
279
280             pkt->pos          = pos;
281             pkt->flags       |= hdr[2] == 0 ? AV_PKT_FLAG_KEY : 0;
282             pkt->pts          = AV_RL32(&hdr[4]);
283             pkt->stream_index = ctx->v_id;
284             memcpy(pkt->data, hdr, copyhdrsize);
285             ret = avio_read(pb, pkt->data + copyhdrsize, size);
286             if (ret < 0) {
287                 av_packet_unref(pkt);
288                 return ret;
289             }
290             if (ret < size)
291                 av_shrink_packet(pkt, copyhdrsize + ret);
292             return 0;
293         case NUV_AUDIO:
294             if (ctx->a_id < 0) {
295                 av_log(s, AV_LOG_ERROR, "Audio packet in file without audio stream!\n");
296                 avio_skip(pb, size);
297                 break;
298             }
299             ret               = av_get_packet(pb, pkt, size);
300             pkt->flags       |= AV_PKT_FLAG_KEY;
301             pkt->pos          = pos;
302             pkt->pts          = AV_RL32(&hdr[4]);
303             pkt->stream_index = ctx->a_id;
304             if (ret < 0)
305                 return ret;
306             return 0;
307         case NUV_SEEKP:
308             // contains no data, size value is invalid
309             break;
310         default:
311             avio_skip(pb, size);
312             break;
313         }
314     }
315
316     return AVERROR(EIO);
317 }
318
319 /**
320  * \brief looks for the string RTjjjjjjjjjj in the stream too resync reading
321  * \return 1 if the syncword is found 0 otherwise.
322  */
323 static int nuv_resync(AVFormatContext *s, int64_t pos_limit) {
324     AVIOContext *pb = s->pb;
325     uint32_t tag = 0;
326     while(!avio_feof(pb) && avio_tell(pb) < pos_limit) {
327         tag = (tag << 8) | avio_r8(pb);
328         if (tag                  == MKBETAG('R','T','j','j') &&
329            (tag = avio_rb32(pb)) == MKBETAG('j','j','j','j') &&
330            (tag = avio_rb32(pb)) == MKBETAG('j','j','j','j'))
331             return 1;
332     }
333     return 0;
334 }
335
336 /**
337  * \brief attempts to read a timestamp from stream at the given stream position
338  * \return timestamp if successful and AV_NOPTS_VALUE if failure
339  */
340 static int64_t nuv_read_dts(AVFormatContext *s, int stream_index,
341                             int64_t *ppos, int64_t pos_limit)
342 {
343     NUVContext *ctx = s->priv_data;
344     AVIOContext *pb = s->pb;
345     uint8_t hdr[HDRSIZE];
346     nuv_frametype frametype;
347     int size, key, idx;
348     int64_t pos, dts;
349
350     if (avio_seek(pb, *ppos, SEEK_SET) < 0)
351         return AV_NOPTS_VALUE;
352
353     if (!nuv_resync(s, pos_limit))
354         return AV_NOPTS_VALUE;
355
356     while (!avio_feof(pb) && avio_tell(pb) < pos_limit) {
357         if (avio_read(pb, hdr, HDRSIZE) < HDRSIZE)
358             return AV_NOPTS_VALUE;
359         frametype = hdr[0];
360         size = PKTSIZE(AV_RL32(&hdr[8]));
361         switch (frametype) {
362             case NUV_SEEKP:
363                 break;
364             case NUV_AUDIO:
365             case NUV_VIDEO:
366                 if (frametype == NUV_VIDEO) {
367                     idx = ctx->v_id;
368                     key = hdr[2] == 0;
369                 } else {
370                     idx = ctx->a_id;
371                     key = 1;
372                 }
373                 if (stream_index == idx) {
374
375                     pos = avio_tell(s->pb) - HDRSIZE;
376                     dts = AV_RL32(&hdr[4]);
377
378                     // TODO - add general support in av_gen_search, so it adds positions after reading timestamps
379                     av_add_index_entry(s->streams[stream_index], pos, dts, size + HDRSIZE, 0,
380                             key ? AVINDEX_KEYFRAME : 0);
381
382                     *ppos = pos;
383                     return dts;
384                 }
385             default:
386                 avio_skip(pb, size);
387                 break;
388         }
389     }
390     return AV_NOPTS_VALUE;
391 }
392
393
394 AVInputFormat ff_nuv_demuxer = {
395     .name           = "nuv",
396     .long_name      = NULL_IF_CONFIG_SMALL("NuppelVideo"),
397     .priv_data_size = sizeof(NUVContext),
398     .read_probe     = nuv_probe,
399     .read_header    = nuv_header,
400     .read_packet    = nuv_packet,
401     .read_timestamp = nuv_read_dts,
402     .flags          = AVFMT_GENERIC_INDEX,
403 };