]> git.sesse.net Git - ffmpeg/blob - libavformat/avienc.c
73af73808954441b1d8a1d7b4adf59b6124e2d31
[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 void avi_write_info_tag(ByteIOContext *pb, const char *tag, const char *str)
93 {
94     int len = strlen(str);
95     if (len > 0) {
96         len++;
97         put_tag(pb, tag);
98         put_le32(pb, len);
99         put_strz(pb, str);
100         if (len & 1)
101             put_byte(pb, 0);
102     }
103 }
104
105 static int avi_write_counters(AVFormatContext* s, int riff_id)
106 {
107     ByteIOContext *pb = &s->pb;
108     AVIContext *avi = s->priv_data;
109     int n, au_byterate, au_ssize, au_scale, nb_frames = 0;
110     offset_t file_size;
111     AVCodecContext* stream;
112
113     file_size = url_ftell(pb);
114     for(n = 0; n < s->nb_streams; n++) {
115         assert(avi->frames_hdr_strm[n]);
116         stream = s->streams[n]->codec;
117         url_fseek(pb, avi->frames_hdr_strm[n], SEEK_SET);
118         ff_parse_specific_params(stream, &au_byterate, &au_ssize, &au_scale);
119         if(au_ssize == 0) {
120             put_le32(pb, avi->packet_count[n]);
121         } else {
122             put_le32(pb, avi->audio_strm_length[n] / au_ssize);
123         }
124         if(stream->codec_type == CODEC_TYPE_VIDEO)
125             nb_frames = FFMAX(nb_frames, avi->packet_count[n]);
126     }
127     if(riff_id == 1) {
128         assert(avi->frames_hdr_all);
129         url_fseek(pb, avi->frames_hdr_all, SEEK_SET);
130         put_le32(pb, nb_frames);
131     }
132     url_fseek(pb, file_size, SEEK_SET);
133
134     return 0;
135 }
136
137 static int avi_write_header(AVFormatContext *s)
138 {
139     AVIContext *avi = s->priv_data;
140     ByteIOContext *pb = &s->pb;
141     int bitrate, n, i, nb_frames, au_byterate, au_ssize, au_scale;
142     AVCodecContext *stream, *video_enc;
143     offset_t list1, list2, strh, strf;
144
145     /* header list */
146     avi->riff_id = 0;
147     list1 = avi_start_new_riff(avi, pb, "AVI ", "hdrl");
148
149     /* avi header */
150     put_tag(pb, "avih");
151     put_le32(pb, 14 * 4);
152     bitrate = 0;
153
154     video_enc = NULL;
155     for(n=0;n<s->nb_streams;n++) {
156         stream = s->streams[n]->codec;
157         bitrate += stream->bit_rate;
158         if (stream->codec_type == CODEC_TYPE_VIDEO)
159             video_enc = stream;
160     }
161
162     nb_frames = 0;
163
164     if(video_enc){
165         put_le32(pb, (uint32_t)(int64_t_C(1000000) * video_enc->time_base.num / video_enc->time_base.den));
166     } else {
167         put_le32(pb, 0);
168     }
169     put_le32(pb, bitrate / 8); /* XXX: not quite exact */
170     put_le32(pb, 0); /* padding */
171     if (url_is_streamed(pb))
172         put_le32(pb, AVIF_TRUSTCKTYPE | AVIF_ISINTERLEAVED); /* flags */
173     else
174         put_le32(pb, AVIF_TRUSTCKTYPE | AVIF_HASINDEX | AVIF_ISINTERLEAVED); /* flags */
175     avi->frames_hdr_all = url_ftell(pb); /* remember this offset to fill later */
176     put_le32(pb, nb_frames); /* nb frames, filled later */
177     put_le32(pb, 0); /* initial frame */
178     put_le32(pb, s->nb_streams); /* nb streams */
179     put_le32(pb, 1024 * 1024); /* suggested buffer size */
180     if(video_enc){
181         put_le32(pb, video_enc->width);
182         put_le32(pb, video_enc->height);
183     } else {
184         put_le32(pb, 0);
185         put_le32(pb, 0);
186     }
187     put_le32(pb, 0); /* reserved */
188     put_le32(pb, 0); /* reserved */
189     put_le32(pb, 0); /* reserved */
190     put_le32(pb, 0); /* reserved */
191
192     /* stream list */
193     for(i=0;i<n;i++) {
194         list2 = start_tag(pb, "LIST");
195         put_tag(pb, "strl");
196
197         stream = s->streams[i]->codec;
198
199         /* FourCC should really be set by the codec itself */
200         if (! stream->codec_tag) {
201             stream->codec_tag = codec_get_bmp_tag(stream->codec_id);
202         }
203
204         /* stream generic header */
205         strh = start_tag(pb, "strh");
206         switch(stream->codec_type) {
207         case CODEC_TYPE_VIDEO: put_tag(pb, "vids"); break;
208         case CODEC_TYPE_AUDIO: put_tag(pb, "auds"); break;
209 //        case CODEC_TYPE_TEXT : put_tag(pb, "txts"); break;
210         case CODEC_TYPE_DATA : put_tag(pb, "dats"); break;
211         }
212         if(stream->codec_type == CODEC_TYPE_VIDEO)
213             put_le32(pb, stream->codec_tag);
214         else
215             put_le32(pb, 1);
216         put_le32(pb, 0); /* flags */
217         put_le16(pb, 0); /* priority */
218         put_le16(pb, 0); /* language */
219         put_le32(pb, 0); /* initial frame */
220
221         ff_parse_specific_params(stream, &au_byterate, &au_ssize, &au_scale);
222
223         put_le32(pb, au_scale); /* scale */
224         put_le32(pb, au_byterate); /* rate */
225         av_set_pts_info(s->streams[i], 64, au_scale, au_byterate);
226
227         put_le32(pb, 0); /* start */
228         avi->frames_hdr_strm[i] = url_ftell(pb); /* remember this offset to fill later */
229         if (url_is_streamed(pb))
230             put_le32(pb, AVI_MAX_RIFF_SIZE); /* FIXME: this may be broken, but who cares */
231         else
232             put_le32(pb, 0); /* length, XXX: filled later */
233
234         /* suggested buffer size */ //FIXME set at the end to largest chunk
235         if(stream->codec_type == CODEC_TYPE_VIDEO)
236             put_le32(pb, 1024 * 1024);
237         else if(stream->codec_type == CODEC_TYPE_AUDIO)
238             put_le32(pb, 12 * 1024);
239         else
240             put_le32(pb, 0);
241         put_le32(pb, -1); /* quality */
242         put_le32(pb, au_ssize); /* sample size */
243         put_le32(pb, 0);
244         put_le16(pb, stream->width);
245         put_le16(pb, stream->height);
246         end_tag(pb, strh);
247
248       if(stream->codec_type != CODEC_TYPE_DATA){
249         strf = start_tag(pb, "strf");
250         switch(stream->codec_type) {
251         case CODEC_TYPE_VIDEO:
252             put_bmp_header(pb, stream, codec_bmp_tags, 0);
253             break;
254         case CODEC_TYPE_AUDIO:
255             if (put_wav_header(pb, stream) < 0) {
256                 av_free(avi);
257                 return -1;
258             }
259             break;
260         default:
261             return -1;
262         }
263         end_tag(pb, strf);
264       }
265
266         if (!url_is_streamed(pb)) {
267             unsigned char tag[5];
268             int j;
269
270             /* Starting to lay out AVI OpenDML master index.
271              * We want to make it JUNK entry for now, since we'd
272              * like to get away without making AVI an OpenDML one
273              * for compatibility reasons.
274              */
275             avi->indexes[i].entry = avi->indexes[i].ents_allocated = 0;
276             avi->indexes[i].indx_start = start_tag(pb, "JUNK");
277             put_le16(pb, 4);        /* wLongsPerEntry */
278             put_byte(pb, 0);        /* bIndexSubType (0 == frame index) */
279             put_byte(pb, 0);        /* bIndexType (0 == AVI_INDEX_OF_INDEXES) */
280             put_le32(pb, 0);        /* nEntriesInUse (will fill out later on) */
281             put_tag(pb, avi_stream2fourcc(&tag[0], i, stream->codec_type));
282                                     /* dwChunkId */
283             put_le64(pb, 0);        /* dwReserved[3]
284             put_le32(pb, 0);           Must be 0.    */
285             for (j=0; j < AVI_MASTER_INDEX_SIZE * 2; j++)
286                  put_le64(pb, 0);
287             end_tag(pb, avi->indexes[i].indx_start);
288         }
289
290         end_tag(pb, list2);
291     }
292
293     if (!url_is_streamed(pb)) {
294         /* AVI could become an OpenDML one, if it grows beyond 2Gb range */
295         avi->odml_list = start_tag(pb, "JUNK");
296         put_tag(pb, "odml");
297         put_tag(pb, "dmlh");
298         put_le32(pb, 248);
299         for (i = 0; i < 248; i+= 4)
300              put_le32(pb, 0);
301         end_tag(pb, avi->odml_list);
302     }
303
304     end_tag(pb, list1);
305
306     list2 = start_tag(pb, "LIST");
307     put_tag(pb, "INFO");
308     avi_write_info_tag(pb, "INAM", s->title);
309     avi_write_info_tag(pb, "IART", s->author);
310     avi_write_info_tag(pb, "ICOP", s->copyright);
311     avi_write_info_tag(pb, "ICMT", s->comment);
312     avi_write_info_tag(pb, "IPRD", s->album);
313     avi_write_info_tag(pb, "IGNR", s->genre);
314     if(!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT))
315         avi_write_info_tag(pb, "ISFT", LIBAVFORMAT_IDENT);
316     end_tag(pb, list2);
317
318     /* some padding for easier tag editing */
319     list2 = start_tag(pb, "JUNK");
320     for (i = 0; i < 1016; i += 4)
321         put_le32(pb, 0);
322     end_tag(pb, list2);
323
324     avi->movi_list = start_tag(pb, "LIST");
325     put_tag(pb, "movi");
326
327     put_flush_packet(pb);
328
329     return 0;
330 }
331
332 static int avi_write_ix(AVFormatContext *s)
333 {
334     ByteIOContext *pb = &s->pb;
335     AVIContext *avi = s->priv_data;
336     unsigned char tag[5];
337     unsigned char ix_tag[] = "ix00";
338     int i, j;
339
340     assert(!url_is_streamed(pb));
341
342     if (avi->riff_id > AVI_MASTER_INDEX_SIZE)
343         return -1;
344
345     for (i=0;i<s->nb_streams;i++) {
346          offset_t ix, pos;
347
348          avi_stream2fourcc(&tag[0], i, s->streams[i]->codec->codec_type);
349          ix_tag[3] = '0' + i;
350
351          /* Writing AVI OpenDML leaf index chunk */
352          ix = url_ftell(pb);
353          put_tag(pb, &ix_tag[0]);     /* ix?? */
354          put_le32(pb, avi->indexes[i].entry * 8 + 24);
355                                       /* chunk size */
356          put_le16(pb, 2);             /* wLongsPerEntry */
357          put_byte(pb, 0);             /* bIndexSubType (0 == frame index) */
358          put_byte(pb, 1);             /* bIndexType (1 == AVI_INDEX_OF_CHUNKS) */
359          put_le32(pb, avi->indexes[i].entry);
360                                       /* nEntriesInUse */
361          put_tag(pb, &tag[0]);        /* dwChunkId */
362          put_le64(pb, avi->movi_list);/* qwBaseOffset */
363          put_le32(pb, 0);             /* dwReserved_3 (must be 0) */
364
365          for (j=0; j<avi->indexes[i].entry; j++) {
366              AVIIentry* ie = avi_get_ientry(&avi->indexes[i], j);
367              put_le32(pb, ie->pos + 8);
368              put_le32(pb, ((uint32_t)ie->len & ~0x80000000) |
369                           (ie->flags & 0x10 ? 0 : 0x80000000));
370          }
371          put_flush_packet(pb);
372          pos = url_ftell(pb);
373
374          /* Updating one entry in the AVI OpenDML master index */
375          url_fseek(pb, avi->indexes[i].indx_start - 8, SEEK_SET);
376          put_tag(pb, "indx");                 /* enabling this entry */
377          url_fskip(pb, 8);
378          put_le32(pb, avi->riff_id);          /* nEntriesInUse */
379          url_fskip(pb, 16*avi->riff_id);
380          put_le64(pb, ix);                    /* qwOffset */
381          put_le32(pb, pos - ix);              /* dwSize */
382          put_le32(pb, avi->indexes[i].entry); /* dwDuration */
383
384          url_fseek(pb, pos, SEEK_SET);
385     }
386     return 0;
387 }
388
389 static int avi_write_idx1(AVFormatContext *s)
390 {
391     ByteIOContext *pb = &s->pb;
392     AVIContext *avi = s->priv_data;
393     offset_t idx_chunk;
394     int i;
395     unsigned char tag[5];
396
397     if (!url_is_streamed(pb)) {
398         AVIIentry* ie = 0, *tie;
399         int entry[MAX_STREAMS];
400         int empty, stream_id = -1;
401
402         idx_chunk = start_tag(pb, "idx1");
403         memset(&entry[0], 0, sizeof(entry));
404         do {
405             empty = 1;
406             for (i=0; i<s->nb_streams; i++) {
407                  if (avi->indexes[i].entry <= entry[i])
408                      continue;
409
410                  tie = avi_get_ientry(&avi->indexes[i], entry[i]);
411                  if (empty || tie->pos < ie->pos) {
412                      ie = tie;
413                      stream_id = i;
414                  }
415                  empty = 0;
416             }
417             if (!empty) {
418                 avi_stream2fourcc(&tag[0], stream_id,
419                                   s->streams[stream_id]->codec->codec_type);
420                 put_tag(pb, &tag[0]);
421                 put_le32(pb, ie->flags);
422                 put_le32(pb, ie->pos);
423                 put_le32(pb, ie->len);
424                 entry[stream_id]++;
425             }
426         } while (!empty);
427         end_tag(pb, idx_chunk);
428
429         avi_write_counters(s, avi->riff_id);
430     }
431     return 0;
432 }
433
434 static int avi_write_packet(AVFormatContext *s, AVPacket *pkt)
435 {
436     AVIContext *avi = s->priv_data;
437     ByteIOContext *pb = &s->pb;
438     unsigned char tag[5];
439     unsigned int flags=0;
440     const int stream_index= pkt->stream_index;
441     AVCodecContext *enc= s->streams[stream_index]->codec;
442     int size= pkt->size;
443
444 //    av_log(s, AV_LOG_DEBUG, "%lld %d %d\n", pkt->dts, avi->packet_count[stream_index], stream_index);
445     while(enc->block_align==0 && pkt->dts != AV_NOPTS_VALUE && pkt->dts > avi->packet_count[stream_index]){
446         AVPacket empty_packet;
447
448         av_init_packet(&empty_packet);
449         empty_packet.size= 0;
450         empty_packet.data= NULL;
451         empty_packet.stream_index= stream_index;
452         avi_write_packet(s, &empty_packet);
453 //        av_log(s, AV_LOG_DEBUG, "dup %lld %d\n", pkt->dts, avi->packet_count[stream_index]);
454     }
455     avi->packet_count[stream_index]++;
456
457     // Make sure to put an OpenDML chunk when the file size exceeds the limits
458     if (!url_is_streamed(pb) &&
459         (url_ftell(pb) - avi->riff_start > AVI_MAX_RIFF_SIZE)) {
460
461         avi_write_ix(s);
462         end_tag(pb, avi->movi_list);
463
464         if (avi->riff_id == 1)
465             avi_write_idx1(s);
466
467         end_tag(pb, avi->riff_start);
468         avi->movi_list = avi_start_new_riff(avi, pb, "AVIX", "movi");
469     }
470
471     avi_stream2fourcc(&tag[0], stream_index, enc->codec_type);
472     if(pkt->flags&PKT_FLAG_KEY)
473         flags = 0x10;
474     if (enc->codec_type == CODEC_TYPE_AUDIO) {
475        avi->audio_strm_length[stream_index] += size;
476     }
477
478     if (!url_is_streamed(&s->pb)) {
479         AVIIndex* idx = &avi->indexes[stream_index];
480         int cl = idx->entry / AVI_INDEX_CLUSTER_SIZE;
481         int id = idx->entry % AVI_INDEX_CLUSTER_SIZE;
482         if (idx->ents_allocated <= idx->entry) {
483             idx->cluster = av_realloc(idx->cluster, (cl+1)*sizeof(void*));
484             if (!idx->cluster)
485                 return -1;
486             idx->cluster[cl] = av_malloc(AVI_INDEX_CLUSTER_SIZE*sizeof(AVIIentry));
487             if (!idx->cluster[cl])
488                 return -1;
489             idx->ents_allocated += AVI_INDEX_CLUSTER_SIZE;
490         }
491
492         idx->cluster[cl][id].flags = flags;
493         idx->cluster[cl][id].pos = url_ftell(pb) - avi->movi_list;
494         idx->cluster[cl][id].len = size;
495         idx->entry++;
496     }
497
498     put_buffer(pb, tag, 4);
499     put_le32(pb, size);
500     put_buffer(pb, pkt->data, size);
501     if (size & 1)
502         put_byte(pb, 0);
503
504     put_flush_packet(pb);
505     return 0;
506 }
507
508 static int avi_write_trailer(AVFormatContext *s)
509 {
510     AVIContext *avi = s->priv_data;
511     ByteIOContext *pb = &s->pb;
512     int res = 0;
513     int i, j, n, nb_frames;
514     offset_t file_size;
515
516     if (!url_is_streamed(pb))
517     {
518     if (avi->riff_id == 1) {
519         end_tag(pb, avi->movi_list);
520         res = avi_write_idx1(s);
521         end_tag(pb, avi->riff_start);
522     } else {
523         avi_write_ix(s);
524         end_tag(pb, avi->movi_list);
525         end_tag(pb, avi->riff_start);
526
527         file_size = url_ftell(pb);
528         url_fseek(pb, avi->odml_list - 8, SEEK_SET);
529         put_tag(pb, "LIST"); /* Making this AVI OpenDML one */
530         url_fskip(pb, 16);
531
532         for (n=nb_frames=0;n<s->nb_streams;n++) {
533              AVCodecContext *stream = s->streams[n]->codec;
534              if (stream->codec_type == CODEC_TYPE_VIDEO) {
535                  if (nb_frames < avi->packet_count[n])
536                      nb_frames = avi->packet_count[n];
537              } else {
538                  if (stream->codec_id == CODEC_ID_MP2 || stream->codec_id == CODEC_ID_MP3) {
539                      nb_frames += avi->packet_count[n];
540                 }
541             }
542         }
543         put_le32(pb, nb_frames);
544         url_fseek(pb, file_size, SEEK_SET);
545
546         avi_write_counters(s, avi->riff_id);
547     }
548     }
549     put_flush_packet(pb);
550
551     for (i=0; i<MAX_STREAMS; i++) {
552          for (j=0; j<avi->indexes[i].ents_allocated/AVI_INDEX_CLUSTER_SIZE; j++)
553               av_free(avi->indexes[i].cluster[j]);
554          av_free(avi->indexes[i].cluster);
555          avi->indexes[i].cluster = NULL;
556          avi->indexes[i].ents_allocated = avi->indexes[i].entry = 0;
557     }
558
559     return res;
560 }
561
562 AVOutputFormat avi_muxer = {
563     "avi",
564     "avi format",
565     "video/x-msvideo",
566     "avi",
567     sizeof(AVIContext),
568     CODEC_ID_MP2,
569     CODEC_ID_MPEG4,
570     avi_write_header,
571     avi_write_packet,
572     avi_write_trailer,
573 };
574 #endif //CONFIG_AVI_MUXER