]> git.sesse.net Git - ffmpeg/blob - libavformat/avienc.c
another MPEG-2 long gop codec ul
[ffmpeg] / libavformat / avienc.c
1 /*
2  * AVI encoder.
3  * Copyright (c) 2000 Fabrice Bellard.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18  */
19 #include "avformat.h"
20 #include "avi.h"
21 #include "riff.h"
22
23 /*
24  * TODO:
25  *  - fill all fields if non streamed (nb_frames for example)
26  */
27
28 #ifdef CONFIG_AVI_MUXER
29 typedef struct AVIIentry {
30     unsigned int flags, pos, len;
31 } AVIIentry;
32
33 #define AVI_INDEX_CLUSTER_SIZE 16384
34
35 typedef struct AVIIndex {
36     offset_t    indx_start;
37     int         entry;
38     int         ents_allocated;
39     AVIIentry** cluster;
40 } AVIIndex;
41
42 typedef struct {
43     offset_t riff_start, movi_list, odml_list;
44     offset_t frames_hdr_all, frames_hdr_strm[MAX_STREAMS];
45     int audio_strm_length[MAX_STREAMS];
46     int riff_id;
47     int packet_count[MAX_STREAMS];
48
49     AVIIndex indexes[MAX_STREAMS];
50 } AVIContext;
51
52 static inline AVIIentry* avi_get_ientry(AVIIndex* idx, int ent_id)
53 {
54     int cl = ent_id / AVI_INDEX_CLUSTER_SIZE;
55     int id = ent_id % AVI_INDEX_CLUSTER_SIZE;
56     return &idx->cluster[cl][id];
57 }
58
59 static offset_t avi_start_new_riff(AVIContext *avi, ByteIOContext *pb,
60                                    const char* riff_tag, const char* list_tag)
61 {
62     offset_t loff;
63     int i;
64
65     avi->riff_id++;
66     for (i=0; i<MAX_STREAMS; i++)
67          avi->indexes[i].entry = 0;
68
69     avi->riff_start = start_tag(pb, "RIFF");
70     put_tag(pb, riff_tag);
71     loff = start_tag(pb, "LIST");
72     put_tag(pb, list_tag);
73     return loff;
74 }
75
76 static unsigned char* avi_stream2fourcc(unsigned char* tag, int index,
77                                         enum CodecType type)
78 {
79     tag[0] = '0';
80     tag[1] = '0' + index;
81     if (type == CODEC_TYPE_VIDEO) {
82         tag[2] = 'd';
83         tag[3] = 'c';
84     } else {
85         tag[2] = 'w';
86         tag[3] = 'b';
87     }
88     tag[4] = '\0';
89     return tag;
90 }
91
92 static int avi_write_header(AVFormatContext *s)
93 {
94     AVIContext *avi = s->priv_data;
95     ByteIOContext *pb = &s->pb;
96     int bitrate, n, i, nb_frames, au_byterate, au_ssize, au_scale;
97     AVCodecContext *stream, *video_enc;
98     offset_t list1, list2, strh, strf;
99
100     /* header list */
101     avi->riff_id = 0;
102     list1 = avi_start_new_riff(avi, pb, "AVI ", "hdrl");
103
104     /* avi header */
105     put_tag(pb, "avih");
106     put_le32(pb, 14 * 4);
107     bitrate = 0;
108
109     video_enc = NULL;
110     for(n=0;n<s->nb_streams;n++) {
111         stream = s->streams[n]->codec;
112         bitrate += stream->bit_rate;
113         if (stream->codec_type == CODEC_TYPE_VIDEO)
114             video_enc = stream;
115     }
116
117     nb_frames = 0;
118
119     if(video_enc){
120         put_le32(pb, (uint32_t)(int64_t_C(1000000) * video_enc->time_base.num / video_enc->time_base.den));
121     } else {
122         put_le32(pb, 0);
123     }
124     put_le32(pb, bitrate / 8); /* XXX: not quite exact */
125     put_le32(pb, 0); /* padding */
126     if (url_is_streamed(pb))
127         put_le32(pb, AVIF_TRUSTCKTYPE | AVIF_ISINTERLEAVED); /* flags */
128     else
129         put_le32(pb, AVIF_TRUSTCKTYPE | AVIF_HASINDEX | AVIF_ISINTERLEAVED); /* flags */
130     avi->frames_hdr_all = url_ftell(pb); /* remember this offset to fill later */
131     put_le32(pb, nb_frames); /* nb frames, filled later */
132     put_le32(pb, 0); /* initial frame */
133     put_le32(pb, s->nb_streams); /* nb streams */
134     put_le32(pb, 1024 * 1024); /* suggested buffer size */
135     if(video_enc){
136         put_le32(pb, video_enc->width);
137         put_le32(pb, video_enc->height);
138     } else {
139         put_le32(pb, 0);
140         put_le32(pb, 0);
141     }
142     put_le32(pb, 0); /* reserved */
143     put_le32(pb, 0); /* reserved */
144     put_le32(pb, 0); /* reserved */
145     put_le32(pb, 0); /* reserved */
146
147     /* stream list */
148     for(i=0;i<n;i++) {
149         list2 = start_tag(pb, "LIST");
150         put_tag(pb, "strl");
151
152         stream = s->streams[i]->codec;
153
154         /* FourCC should really be set by the codec itself */
155         if (! stream->codec_tag) {
156             stream->codec_tag = codec_get_bmp_tag(stream->codec_id);
157         }
158
159         /* stream generic header */
160         strh = start_tag(pb, "strh");
161         switch(stream->codec_type) {
162         case CODEC_TYPE_VIDEO: put_tag(pb, "vids"); break;
163         case CODEC_TYPE_AUDIO: put_tag(pb, "auds"); break;
164 //        case CODEC_TYPE_TEXT : put_tag(pb, "txts"); break;
165         case CODEC_TYPE_DATA : put_tag(pb, "dats"); break;
166         }
167         if(stream->codec_type == CODEC_TYPE_VIDEO)
168             put_le32(pb, stream->codec_tag);
169         else
170             put_le32(pb, 1);
171         put_le32(pb, 0); /* flags */
172         put_le16(pb, 0); /* priority */
173         put_le16(pb, 0); /* language */
174         put_le32(pb, 0); /* initial frame */
175
176         ff_parse_specific_params(stream, &au_byterate, &au_ssize, &au_scale);
177
178         put_le32(pb, au_scale); /* scale */
179         put_le32(pb, au_byterate); /* rate */
180         av_set_pts_info(s->streams[i], 64, au_scale, au_byterate);
181
182         put_le32(pb, 0); /* start */
183         avi->frames_hdr_strm[i] = url_ftell(pb); /* remember this offset to fill later */
184         if (url_is_streamed(pb))
185             put_le32(pb, AVI_MAX_RIFF_SIZE); /* FIXME: this may be broken, but who cares */
186         else
187             put_le32(pb, 0); /* length, XXX: filled later */
188
189         /* suggested buffer size */ //FIXME set at the end to largest chunk
190         if(stream->codec_type == CODEC_TYPE_VIDEO)
191             put_le32(pb, 1024 * 1024);
192         else if(stream->codec_type == CODEC_TYPE_AUDIO)
193             put_le32(pb, 12 * 1024);
194         else
195             put_le32(pb, 0);
196         put_le32(pb, -1); /* quality */
197         put_le32(pb, au_ssize); /* sample size */
198         put_le32(pb, 0);
199         put_le16(pb, stream->width);
200         put_le16(pb, stream->height);
201         end_tag(pb, strh);
202
203       if(stream->codec_type != CODEC_TYPE_DATA){
204         strf = start_tag(pb, "strf");
205         switch(stream->codec_type) {
206         case CODEC_TYPE_VIDEO:
207             put_bmp_header(pb, stream, codec_bmp_tags, 0);
208             break;
209         case CODEC_TYPE_AUDIO:
210             if (put_wav_header(pb, stream) < 0) {
211                 av_free(avi);
212                 return -1;
213             }
214             break;
215         default:
216             return -1;
217         }
218         end_tag(pb, strf);
219       }
220
221         if (!url_is_streamed(pb)) {
222             unsigned char tag[5];
223             int j;
224
225             /* Starting to lay out AVI OpenDML master index.
226              * We want to make it JUNK entry for now, since we'd
227              * like to get away without making AVI an OpenDML one
228              * for compatibility reasons.
229              */
230             avi->indexes[i].entry = avi->indexes[i].ents_allocated = 0;
231             avi->indexes[i].indx_start = start_tag(pb, "JUNK");
232             put_le16(pb, 4);        /* wLongsPerEntry */
233             put_byte(pb, 0);        /* bIndexSubType (0 == frame index) */
234             put_byte(pb, 0);        /* bIndexType (0 == AVI_INDEX_OF_INDEXES) */
235             put_le32(pb, 0);        /* nEntriesInUse (will fill out later on) */
236             put_tag(pb, avi_stream2fourcc(&tag[0], i, stream->codec_type));
237                                     /* dwChunkId */
238             put_le64(pb, 0);        /* dwReserved[3]
239             put_le32(pb, 0);           Must be 0.    */
240             for (j=0; j < AVI_MASTER_INDEX_SIZE * 2; j++)
241                  put_le64(pb, 0);
242             end_tag(pb, avi->indexes[i].indx_start);
243         }
244
245         end_tag(pb, list2);
246     }
247
248     if (!url_is_streamed(pb)) {
249         /* AVI could become an OpenDML one, if it grows beyond 2Gb range */
250         avi->odml_list = start_tag(pb, "JUNK");
251         put_tag(pb, "odml");
252         put_tag(pb, "dmlh");
253         put_le32(pb, 248);
254         for (i = 0; i < 248; i+= 4)
255              put_le32(pb, 0);
256         end_tag(pb, avi->odml_list);
257     }
258
259     end_tag(pb, list1);
260
261     avi->movi_list = start_tag(pb, "LIST");
262     put_tag(pb, "movi");
263
264     put_flush_packet(pb);
265
266     return 0;
267 }
268
269 static int avi_write_ix(AVFormatContext *s)
270 {
271     ByteIOContext *pb = &s->pb;
272     AVIContext *avi = s->priv_data;
273     unsigned char tag[5];
274     unsigned char ix_tag[] = "ix00";
275     int i, j;
276
277     assert(!url_is_streamed(pb));
278
279     if (avi->riff_id > AVI_MASTER_INDEX_SIZE)
280         return -1;
281
282     for (i=0;i<s->nb_streams;i++) {
283          offset_t ix, pos;
284
285          avi_stream2fourcc(&tag[0], i, s->streams[i]->codec->codec_type);
286          ix_tag[3] = '0' + i;
287
288          /* Writing AVI OpenDML leaf index chunk */
289          ix = url_ftell(pb);
290          put_tag(pb, &ix_tag[0]);     /* ix?? */
291          put_le32(pb, avi->indexes[i].entry * 8 + 24);
292                                       /* chunk size */
293          put_le16(pb, 2);             /* wLongsPerEntry */
294          put_byte(pb, 0);             /* bIndexSubType (0 == frame index) */
295          put_byte(pb, 1);             /* bIndexType (1 == AVI_INDEX_OF_CHUNKS) */
296          put_le32(pb, avi->indexes[i].entry);
297                                       /* nEntriesInUse */
298          put_tag(pb, &tag[0]);        /* dwChunkId */
299          put_le64(pb, avi->movi_list);/* qwBaseOffset */
300          put_le32(pb, 0);             /* dwReserved_3 (must be 0) */
301
302          for (j=0; j<avi->indexes[i].entry; j++) {
303              AVIIentry* ie = avi_get_ientry(&avi->indexes[i], j);
304              put_le32(pb, ie->pos + 8);
305              put_le32(pb, ((uint32_t)ie->len & ~0x80000000) |
306                           (ie->flags & 0x10 ? 0 : 0x80000000));
307          }
308          put_flush_packet(pb);
309          pos = url_ftell(pb);
310
311          /* Updating one entry in the AVI OpenDML master index */
312          url_fseek(pb, avi->indexes[i].indx_start - 8, SEEK_SET);
313          put_tag(pb, "indx");                 /* enabling this entry */
314          url_fskip(pb, 8);
315          put_le32(pb, avi->riff_id);          /* nEntriesInUse */
316          url_fskip(pb, 16*avi->riff_id);
317          put_le64(pb, ix);                    /* qwOffset */
318          put_le32(pb, pos - ix);              /* dwSize */
319          put_le32(pb, avi->indexes[i].entry); /* dwDuration */
320
321          url_fseek(pb, pos, SEEK_SET);
322     }
323     return 0;
324 }
325
326 static int avi_write_idx1(AVFormatContext *s)
327 {
328     ByteIOContext *pb = &s->pb;
329     AVIContext *avi = s->priv_data;
330     offset_t file_size, idx_chunk;
331     int i, n, nb_frames, au_byterate, au_ssize, au_scale;
332     AVCodecContext *stream;
333     unsigned char tag[5];
334
335     if (!url_is_streamed(pb)) {
336         AVIIentry* ie = 0, *tie;
337         int entry[MAX_STREAMS];
338         int empty, stream_id = -1;
339
340         idx_chunk = start_tag(pb, "idx1");
341         memset(&entry[0], 0, sizeof(entry));
342         do {
343             empty = 1;
344             for (i=0; i<s->nb_streams; i++) {
345                  if (avi->indexes[i].entry <= entry[i])
346                      continue;
347
348                  tie = avi_get_ientry(&avi->indexes[i], entry[i]);
349                  if (empty || tie->pos < ie->pos) {
350                      ie = tie;
351                      stream_id = i;
352                  }
353                  empty = 0;
354             }
355             if (!empty) {
356                 avi_stream2fourcc(&tag[0], stream_id,
357                                   s->streams[stream_id]->codec->codec_type);
358                 put_tag(pb, &tag[0]);
359                 put_le32(pb, ie->flags);
360                 put_le32(pb, ie->pos);
361                 put_le32(pb, ie->len);
362                 entry[stream_id]++;
363             }
364         } while (!empty);
365         end_tag(pb, idx_chunk);
366
367         /* Fill in frame/sample counters */
368         file_size = url_ftell(pb);
369         nb_frames = 0;
370         for(n=0;n<s->nb_streams;n++) {
371             assert(avi->frames_hdr_strm[n]);
372                 stream = s->streams[n]->codec;
373                 url_fseek(pb, avi->frames_hdr_strm[n], SEEK_SET);
374                 ff_parse_specific_params(stream, &au_byterate, &au_ssize, &au_scale);
375                 if (au_ssize == 0) {
376                     put_le32(pb, avi->packet_count[n]);
377                 } else {
378                     put_le32(pb, avi->audio_strm_length[n] / au_ssize);
379                 }
380             if(stream->codec_type == CODEC_TYPE_VIDEO)
381                 nb_frames = FFMAX(nb_frames, avi->packet_count[n]);
382        }
383         assert(avi->frames_hdr_all);
384         url_fseek(pb, avi->frames_hdr_all, SEEK_SET);
385         put_le32(pb, nb_frames);
386        url_fseek(pb, file_size, SEEK_SET);
387     }
388     return 0;
389 }
390
391 static int avi_write_packet(AVFormatContext *s, AVPacket *pkt)
392 {
393     AVIContext *avi = s->priv_data;
394     ByteIOContext *pb = &s->pb;
395     unsigned char tag[5];
396     unsigned int flags=0;
397     const int stream_index= pkt->stream_index;
398     AVCodecContext *enc= s->streams[stream_index]->codec;
399     int size= pkt->size;
400
401 //    av_log(s, AV_LOG_DEBUG, "%lld %d %d\n", pkt->dts, avi->packet_count[stream_index], stream_index);
402     while(enc->block_align==0 && pkt->dts != AV_NOPTS_VALUE && pkt->dts > avi->packet_count[stream_index]){
403         AVPacket empty_packet;
404
405         av_init_packet(&empty_packet);
406         empty_packet.size= 0;
407         empty_packet.data= NULL;
408         empty_packet.stream_index= stream_index;
409         avi_write_packet(s, &empty_packet);
410 //        av_log(s, AV_LOG_DEBUG, "dup %lld %d\n", pkt->dts, avi->packet_count[stream_index]);
411     }
412     avi->packet_count[stream_index]++;
413
414     // Make sure to put an OpenDML chunk when the file size exceeds the limits
415     if (!url_is_streamed(pb) &&
416         (url_ftell(pb) - avi->riff_start > AVI_MAX_RIFF_SIZE)) {
417
418         avi_write_ix(s);
419         end_tag(pb, avi->movi_list);
420
421         if (avi->riff_id == 1)
422             avi_write_idx1(s);
423
424         end_tag(pb, avi->riff_start);
425         avi->movi_list = avi_start_new_riff(avi, pb, "AVIX", "movi");
426     }
427
428     avi_stream2fourcc(&tag[0], stream_index, enc->codec_type);
429     if(pkt->flags&PKT_FLAG_KEY)
430         flags = 0x10;
431     if (enc->codec_type == CODEC_TYPE_AUDIO) {
432        avi->audio_strm_length[stream_index] += size;
433     }
434
435     if (!url_is_streamed(&s->pb)) {
436         AVIIndex* idx = &avi->indexes[stream_index];
437         int cl = idx->entry / AVI_INDEX_CLUSTER_SIZE;
438         int id = idx->entry % AVI_INDEX_CLUSTER_SIZE;
439         if (idx->ents_allocated <= idx->entry) {
440             idx->cluster = av_realloc(idx->cluster, (cl+1)*sizeof(void*));
441             if (!idx->cluster)
442                 return -1;
443             idx->cluster[cl] = av_malloc(AVI_INDEX_CLUSTER_SIZE*sizeof(AVIIentry));
444             if (!idx->cluster[cl])
445                 return -1;
446             idx->ents_allocated += AVI_INDEX_CLUSTER_SIZE;
447         }
448
449         idx->cluster[cl][id].flags = flags;
450         idx->cluster[cl][id].pos = url_ftell(pb) - avi->movi_list;
451         idx->cluster[cl][id].len = size;
452         idx->entry++;
453     }
454
455     put_buffer(pb, tag, 4);
456     put_le32(pb, size);
457     put_buffer(pb, pkt->data, size);
458     if (size & 1)
459         put_byte(pb, 0);
460
461     put_flush_packet(pb);
462     return 0;
463 }
464
465 static int avi_write_trailer(AVFormatContext *s)
466 {
467     AVIContext *avi = s->priv_data;
468     ByteIOContext *pb = &s->pb;
469     int res = 0;
470     int i, j, n, nb_frames;
471     offset_t file_size;
472
473     if (!url_is_streamed(pb))
474     {
475     if (avi->riff_id == 1) {
476         end_tag(pb, avi->movi_list);
477         res = avi_write_idx1(s);
478         end_tag(pb, avi->riff_start);
479     } else {
480         avi_write_ix(s);
481         end_tag(pb, avi->movi_list);
482         end_tag(pb, avi->riff_start);
483
484         file_size = url_ftell(pb);
485         url_fseek(pb, avi->odml_list - 8, SEEK_SET);
486         put_tag(pb, "LIST"); /* Making this AVI OpenDML one */
487         url_fskip(pb, 16);
488
489         for (n=nb_frames=0;n<s->nb_streams;n++) {
490              AVCodecContext *stream = s->streams[n]->codec;
491              if (stream->codec_type == CODEC_TYPE_VIDEO) {
492                  if (nb_frames < avi->packet_count[n])
493                      nb_frames = avi->packet_count[n];
494              } else {
495                  if (stream->codec_id == CODEC_ID_MP2 || stream->codec_id == CODEC_ID_MP3) {
496                      nb_frames += avi->packet_count[n];
497                 }
498             }
499         }
500         put_le32(pb, nb_frames);
501         url_fseek(pb, file_size, SEEK_SET);
502     }
503     }
504     put_flush_packet(pb);
505
506     for (i=0; i<MAX_STREAMS; i++) {
507          for (j=0; j<avi->indexes[i].ents_allocated/AVI_INDEX_CLUSTER_SIZE; j++)
508               av_free(avi->indexes[i].cluster[j]);
509          av_free(avi->indexes[i].cluster);
510          avi->indexes[i].cluster = NULL;
511          avi->indexes[i].ents_allocated = avi->indexes[i].entry = 0;
512     }
513
514     return res;
515 }
516
517 AVOutputFormat avi_muxer = {
518     "avi",
519     "avi format",
520     "video/x-msvideo",
521     "avi",
522     sizeof(AVIContext),
523     CODEC_ID_MP2,
524     CODEC_ID_MPEG4,
525     avi_write_header,
526     avi_write_packet,
527     avi_write_trailer,
528 };
529 #endif //CONFIG_AVI_MUXER