vbr requires version=1 and samplesize=0 per QT spec
[libav.git] / libavformat / movenc.c
1 /*
2 * MOV, 3GP, MP4 encoder.
3 * Copyright (c) 2003 Thomas Raivio.
4 * Copyright (c) 2004 Gildas Bazin <gbazin at videolan dot org>.
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20 #include "avformat.h"
21 #include "avi.h"
22 #include "avio.h"
23 #include "mov.h"
24
25 #undef NDEBUG
26 #include <assert.h>
27
28 #define MOV_INDEX_CLUSTER_SIZE 16384
29 #define globalTimescale 1000
30
31 #define MODE_MP4 0
32 #define MODE_MOV 1
33 #define MODE_3GP 2
34 #define MODE_PSP 3 // example working PSP command line:
35 // ffmpeg -i testinput.avi -f psp -r 14.985 -s 320x240 -b 768 -ar 24000 -ab 32 M4V00001.MP4
36 #define MODE_3G2 4
37
38 typedef struct MOVIentry {
39 unsigned int flags, size;
40 uint64_t pos;
41 unsigned int samplesInChunk;
42 char key_frame;
43 unsigned int entries;
44 int64_t cts;
45 } MOVIentry;
46
47 typedef struct MOVIndex {
48 int mode;
49 int entry;
50 long timescale;
51 long time;
52 int64_t trackDuration;
53 long sampleCount;
54 long sampleDuration;
55 long sampleSize;
56 int hasKeyframes;
57 int hasBframes;
58 int language;
59 int trackID;
60 int tag;
61 AVCodecContext *enc;
62
63 int vosLen;
64 uint8_t *vosData;
65 MOVIentry *cluster;
66 } MOVTrack;
67
68 typedef struct MOVContext {
69 int mode;
70 int64_t time;
71 int nb_streams;
72 offset_t mdat_pos;
73 uint64_t mdat_size;
74 long timescale;
75 MOVTrack tracks[MAX_STREAMS];
76 } MOVContext;
77
78 //FIXME supprt 64bit varaint with wide placeholders
79 static offset_t updateSize (ByteIOContext *pb, offset_t pos)
80 {
81 offset_t curpos = url_ftell(pb);
82 url_fseek(pb, pos, SEEK_SET);
83 put_be32(pb, curpos - pos); /* rewrite size */
84 url_fseek(pb, curpos, SEEK_SET);
85
86 return curpos - pos;
87 }
88
89 /* Chunk offset atom */
90 static int mov_write_stco_tag(ByteIOContext *pb, MOVTrack* track)
91 {
92 int i;
93 int mode64 = 0; // use 32 bit size variant if possible
94 offset_t pos = url_ftell(pb);
95 put_be32(pb, 0); /* size */
96 if (pos > UINT32_MAX) {
97 mode64 = 1;
98 put_tag(pb, "co64");
99 } else
100 put_tag(pb, "stco");
101 put_be32(pb, 0); /* version & flags */
102 put_be32(pb, track->entry); /* entry count */
103 for (i=0; i<track->entry; i++) {
104 if(mode64 == 1)
105 put_be64(pb, track->cluster[i].pos);
106 else
107 put_be32(pb, track->cluster[i].pos);
108 }
109 return updateSize (pb, pos);
110 }
111
112 /* Sample size atom */
113 static int mov_write_stsz_tag(ByteIOContext *pb, MOVTrack* track)
114 {
115 int equalChunks = 1;
116 int i, j, entries = 0, tst = -1, oldtst = -1;
117
118 offset_t pos = url_ftell(pb);
119 put_be32(pb, 0); /* size */
120 put_tag(pb, "stsz");
121 put_be32(pb, 0); /* version & flags */
122
123 for (i=0; i<track->entry; i++) {
124 tst = track->cluster[i].size/track->cluster[i].entries;
125 if(oldtst != -1 && tst != oldtst) {
126 equalChunks = 0;
127 }
128 oldtst = tst;
129 entries += track->cluster[i].entries;
130 }
131 if (equalChunks) {
132 int sSize = track->cluster[0].size/track->cluster[0].entries;
133 put_be32(pb, sSize); // sample size
134 put_be32(pb, entries); // sample count
135 }
136 else {
137 put_be32(pb, 0); // sample size
138 put_be32(pb, entries); // sample count
139 for (i=0; i<track->entry; i++) {
140 for ( j=0; j<track->cluster[i].entries; j++) {
141 put_be32(pb, track->cluster[i].size /
142 track->cluster[i].entries);
143 }
144 }
145 }
146 return updateSize (pb, pos);
147 }
148
149 /* Sample to chunk atom */
150 static int mov_write_stsc_tag(ByteIOContext *pb, MOVTrack* track)
151 {
152 int index = 0, oldval = -1, i;
153 offset_t entryPos, curpos;
154
155 offset_t pos = url_ftell(pb);
156 put_be32(pb, 0); /* size */
157 put_tag(pb, "stsc");
158 put_be32(pb, 0); // version & flags
159 entryPos = url_ftell(pb);
160 put_be32(pb, track->entry); // entry count
161 for (i=0; i<track->entry; i++) {
162 if(oldval != track->cluster[i].samplesInChunk)
163 {
164 put_be32(pb, i+1); // first chunk
165 put_be32(pb, track->cluster[i].samplesInChunk); // samples per chunk
166 put_be32(pb, 0x1); // sample description index
167 oldval = track->cluster[i].samplesInChunk;
168 index++;
169 }
170 }
171 curpos = url_ftell(pb);
172 url_fseek(pb, entryPos, SEEK_SET);
173 put_be32(pb, index); // rewrite size
174 url_fseek(pb, curpos, SEEK_SET);
175
176 return updateSize (pb, pos);
177 }
178
179 /* Sync sample atom */
180 static int mov_write_stss_tag(ByteIOContext *pb, MOVTrack* track)
181 {
182 offset_t curpos, entryPos;
183 int i, index = 0;
184 offset_t pos = url_ftell(pb);
185 put_be32(pb, 0); // size
186 put_tag(pb, "stss");
187 put_be32(pb, 0); // version & flags
188 entryPos = url_ftell(pb);
189 put_be32(pb, track->entry); // entry count
190 for (i=0; i<track->entry; i++) {
191 if(track->cluster[i].key_frame == 1) {
192 put_be32(pb, i+1);
193 index++;
194 }
195 }
196 curpos = url_ftell(pb);
197 url_fseek(pb, entryPos, SEEK_SET);
198 put_be32(pb, index); // rewrite size
199 url_fseek(pb, curpos, SEEK_SET);
200 return updateSize (pb, pos);
201 }
202
203 static int mov_write_damr_tag(ByteIOContext *pb)
204 {
205 put_be32(pb, 0x11); /* size */
206 put_tag(pb, "damr");
207 put_tag(pb, "FFMP");
208 put_byte(pb, 0);
209
210 //put_be16(pb, 0x80); /* Mode set (all modes for AMR_NB) */
211 //put_be16(pb, 0xa); /* Mode change period (no restriction) */
212 put_be16(pb, 0x81ff); /* Mode set (all modes for AMR_NB) */
213 put_be16(pb, 1); /* Mode change period (no restriction) */
214 return 0x11;
215 }
216
217 static int mov_write_samr_tag(ByteIOContext *pb)
218 {
219 put_be32(pb, 0x11); /* size */
220 put_tag(pb, "samr");
221 put_tag(pb, "FFMP");
222 put_byte(pb, 1);
223
224 put_be16(pb, 0x80); /* Mode set (all modes for AMR_NB) */
225 put_be16(pb, 0x5); /* Mode change period (no restriction) */
226 return 0x11;
227 }
228
229 static int mov_write_enda_tag(ByteIOContext *pb)
230 {
231 put_be32(pb, 10);
232 put_tag(pb, "enda");
233 put_be16(pb, 1); /* little endian */
234 return 10;
235 }
236
237 static unsigned int descrLength(unsigned int len)
238 {
239 int i;
240 for(i=1; len>>(7*i); i++);
241 return len + 1 + i;
242 }
243
244 static void putDescr(ByteIOContext *pb, int tag, unsigned int size)
245 {
246 int i= descrLength(size) - size - 2;
247 put_byte(pb, tag);
248 for(; i>0; i--)
249 put_byte(pb, (size>>(7*i)) | 0x80);
250 put_byte(pb, size & 0x7F);
251 }
252
253 static int mov_write_esds_tag(ByteIOContext *pb, MOVTrack* track) // Basic
254 {
255 offset_t pos = url_ftell(pb);
256 int decoderSpecificInfoLen = track->vosLen ? descrLength(track->vosLen):0;
257
258 put_be32(pb, 0); // size
259 put_tag(pb, "esds");
260 put_be32(pb, 0); // Version
261
262 // ES descriptor
263 putDescr(pb, 0x03, 3 + descrLength(13 + decoderSpecificInfoLen) +
264 descrLength(1));
265 put_be16(pb, track->trackID);
266 put_byte(pb, 0x00); // flags (= no flags)
267
268 // DecoderConfig descriptor
269 putDescr(pb, 0x04, 13 + decoderSpecificInfoLen);
270
271 // Object type indication
272 put_byte(pb, codec_get_tag(ff_mov_obj_type, track->enc->codec_id));
273
274 // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
275 // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
276 if(track->enc->codec_type == CODEC_TYPE_AUDIO)
277 put_byte(pb, 0x15); // flags (= Audiostream)
278 else
279 put_byte(pb, 0x11); // flags (= Visualstream)
280
281 put_byte(pb, track->enc->rc_buffer_size>>(3+16)); // Buffersize DB (24 bits)
282 put_be16(pb, (track->enc->rc_buffer_size>>3)&0xFFFF); // Buffersize DB
283
284 put_be32(pb, FFMAX(track->enc->bit_rate, track->enc->rc_max_rate)); // maxbitrate (FIXME should be max rate in any 1 sec window)
285 if(track->enc->rc_max_rate != track->enc->rc_min_rate || track->enc->rc_min_rate==0)
286 put_be32(pb, 0); // vbr
287 else
288 put_be32(pb, track->enc->rc_max_rate); // avg bitrate
289
290 if (track->vosLen)
291 {
292 // DecoderSpecific info descriptor
293 putDescr(pb, 0x05, track->vosLen);
294 put_buffer(pb, track->vosData, track->vosLen);
295 }
296
297
298 // SL descriptor
299 putDescr(pb, 0x06, 1);
300 put_byte(pb, 0x02);
301 return updateSize (pb, pos);
302 }
303
304 static int mov_write_wave_tag(ByteIOContext *pb, MOVTrack* track)
305 {
306 offset_t pos = url_ftell(pb);
307
308 put_be32(pb, 0); /* size */
309 put_tag(pb, "wave");
310
311 put_be32(pb, 12); /* size */
312 put_tag(pb, "frma");
313 put_le32(pb, track->tag);
314
315 if (track->enc->codec_id == CODEC_ID_AAC) {
316 /* useless atom needed by mplayer, ipod, not needed by quicktime */
317 put_be32(pb, 12); /* size */
318 put_tag(pb, "mp4a");
319 put_be32(pb, 0);
320 mov_write_esds_tag(pb, track);
321 } else if (track->enc->codec_id == CODEC_ID_PCM_S24LE ||
322 track->enc->codec_id == CODEC_ID_PCM_S32LE) {
323 mov_write_enda_tag(pb);
324 } else if (track->enc->codec_id == CODEC_ID_AMR_NB) {
325 mov_write_samr_tag(pb);
326 }
327
328 put_be32(pb, 8); /* size */
329 put_be32(pb, 0); /* null tag */
330
331 return updateSize (pb, pos);
332 }
333
334 static const CodecTag codec_movaudio_tags[] = {
335 { CODEC_ID_PCM_MULAW, MKTAG('u', 'l', 'a', 'w') },
336 { CODEC_ID_PCM_ALAW, MKTAG('a', 'l', 'a', 'w') },
337 { CODEC_ID_ADPCM_IMA_QT, MKTAG('i', 'm', 'a', '4') },
338 { CODEC_ID_MACE3, MKTAG('M', 'A', 'C', '3') },
339 { CODEC_ID_MACE6, MKTAG('M', 'A', 'C', '6') },
340 { CODEC_ID_AAC, MKTAG('m', 'p', '4', 'a') },
341 { CODEC_ID_AMR_NB, MKTAG('s', 'a', 'm', 'r') },
342 { CODEC_ID_AMR_WB, MKTAG('s', 'a', 'w', 'b') },
343 { CODEC_ID_PCM_S16BE, MKTAG('t', 'w', 'o', 's') },
344 { CODEC_ID_PCM_S16LE, MKTAG('s', 'o', 'w', 't') },
345 { CODEC_ID_PCM_S24BE, MKTAG('i', 'n', '2', '4') },
346 { CODEC_ID_PCM_S24LE, MKTAG('i', 'n', '2', '4') },
347 { CODEC_ID_PCM_S32BE, MKTAG('i', 'n', '3', '2') },
348 { CODEC_ID_PCM_S32LE, MKTAG('i', 'n', '3', '2') },
349 { CODEC_ID_MP3, MKTAG('.', 'm', 'p', '3') },
350 { CODEC_ID_NONE, 0 },
351 };
352
353 static int mov_write_audio_tag(ByteIOContext *pb, MOVTrack* track)
354 {
355 offset_t pos = url_ftell(pb);
356 int vbr= track->enc->codec_id == CODEC_ID_AAC ||
357 track->enc->codec_id == CODEC_ID_MP3 ||
358 track->enc->codec_id == CODEC_ID_AMR_NB;
359 int version = track->mode == MODE_MOV &&
360 (vbr ||
361 track->enc->codec_id == CODEC_ID_PCM_S32LE ||
362 track->enc->codec_id == CODEC_ID_PCM_S24LE);
363
364 put_be32(pb, 0); /* size */
365 put_le32(pb, track->tag); // store it byteswapped
366 put_be32(pb, 0); /* Reserved */
367 put_be16(pb, 0); /* Reserved */
368 put_be16(pb, 1); /* Data-reference index, XXX == 1 */
369
370 /* SoundDescription */
371 put_be16(pb, version); /* Version */
372 put_be16(pb, 0); /* Revision level */
373 put_be32(pb, 0); /* Reserved */
374
375 put_be16(pb, track->enc->channels); /* Number of channels */
376 /* TODO: Currently hard-coded to 16-bit, there doesn't seem
377 to be a good way to get number of bits of audio */
378 put_be16(pb, 0x10); /* Reserved */
379
380 if(vbr) {
381 put_be16(pb, 0xfffe); /* compression ID (vbr)*/
382 } else {
383 put_be16(pb, 0); /* compression ID (= 0) */
384 }
385 put_be16(pb, 0); /* packet size (= 0) */
386 put_be16(pb, track->timescale); /* Time scale */
387 put_be16(pb, 0); /* Reserved */
388
389 if(version == 1) { /* SoundDescription V1 extended info */
390 if (vbr)
391 track->sampleSize = 0;
392 put_be32(pb, track->enc->frame_size); /* Samples per packet */
393 put_be32(pb, track->sampleSize / track->enc->channels); /* Bytes per packet */
394 put_be32(pb, track->sampleSize); /* Bytes per frame */
395 put_be32(pb, 2); /* Bytes per sample */
396 }
397
398 if(track->mode == MODE_MOV &&
399 (track->enc->codec_id == CODEC_ID_AAC ||
400 track->enc->codec_id == CODEC_ID_AMR_NB ||
401 track->enc->codec_id == CODEC_ID_PCM_S24LE ||
402 track->enc->codec_id == CODEC_ID_PCM_S32LE))
403 mov_write_wave_tag(pb, track);
404 else if(track->enc->codec_id == CODEC_ID_AAC)
405 mov_write_esds_tag(pb, track);
406 else if(track->enc->codec_id == CODEC_ID_AMR_NB)
407 mov_write_damr_tag(pb);
408
409 return updateSize (pb, pos);
410 }
411
412 static int mov_write_d263_tag(ByteIOContext *pb)
413 {
414 put_be32(pb, 0xf); /* size */
415 put_tag(pb, "d263");
416 put_tag(pb, "FFMP");
417 put_be16(pb, 0x0a);
418 put_byte(pb, 0);
419 return 0xf;
420 }
421
422 /* TODO: No idea about these values */
423 static int mov_write_svq3_tag(ByteIOContext *pb)
424 {
425 put_be32(pb, 0x15);
426 put_tag(pb, "SMI ");
427 put_tag(pb, "SEQH");
428 put_be32(pb, 0x5);
429 put_be32(pb, 0xe2c0211d);
430 put_be32(pb, 0xc0000000);
431 put_byte(pb, 0);
432 return 0x15;
433 }
434
435 static uint8_t *avc_find_startcode( uint8_t *p, uint8_t *end )
436 {
437 uint8_t *a = p + 4 - ((int)p & 3);
438
439 for( end -= 3; p < a && p < end; p++ ) {
440 if( p[0] == 0 && p[1] == 0 && p[2] == 1 )
441 return p;
442 }
443
444 for( end -= 3; p < end; p += 4 ) {
445 uint32_t x = *(uint32_t*)p;
446 // if( (x - 0x01000100) & (~x) & 0x80008000 ) // little endian
447 // if( (x - 0x00010001) & (~x) & 0x00800080 ) // big endian
448 if( (x - 0x01010101) & (~x) & 0x80808080 ) { // generic
449 if( p[1] == 0 ) {
450 if( p[0] == 0 && p[2] == 1 )
451 return p-1;
452 if( p[2] == 0 && p[3] == 1 )
453 return p;
454 }
455 if( p[3] == 0 ) {
456 if( p[2] == 0 && p[4] == 1 )
457 return p+1;
458 if( p[4] == 0 && p[5] == 1 )
459 return p+2;
460 }
461 }
462 }
463
464 for( end += 3; p < end; p++ ) {
465 if( p[0] == 0 && p[1] == 0 && p[2] == 1 )
466 return p;
467 }
468
469 return end + 3;
470 }
471
472 static void avc_parse_nal_units(uint8_t **buf, int *size)
473 {
474 ByteIOContext pb;
475 uint8_t *p = *buf;
476 uint8_t *end = p + *size;
477 uint8_t *nal_start, *nal_end;
478
479 url_open_dyn_buf(&pb);
480 nal_start = avc_find_startcode(p, end);
481 while (nal_start < end) {
482 while(!*(nal_start++));
483 nal_end = avc_find_startcode(nal_start, end);
484 put_be32(&pb, nal_end - nal_start);
485 put_buffer(&pb, nal_start, nal_end - nal_start);
486 nal_start = nal_end;
487 }
488 av_freep(buf);
489 *size = url_close_dyn_buf(&pb, buf);
490 }
491
492 static int mov_write_avcc_tag(ByteIOContext *pb, MOVTrack *track)
493 {
494 offset_t pos = url_ftell(pb);
495
496 put_be32(pb, 0);
497 put_tag(pb, "avcC");
498 if (track->vosLen > 6) {
499 /* check for h264 start code */
500 if (BE_32(track->vosData) == 0x00000001) {
501 uint8_t *buf, *end;
502 uint32_t sps_size=0, pps_size=0;
503 uint8_t *sps=0, *pps=0;
504
505 avc_parse_nal_units(&track->vosData, &track->vosLen);
506 buf = track->vosData;
507 end = track->vosData + track->vosLen;
508
509 /* look for sps and pps */
510 while (buf < end) {
511 unsigned int size;
512 uint8_t nal_type;
513 size = BE_32(buf);
514 nal_type = buf[4] & 0x1f;
515 if (nal_type == 7) { /* SPS */
516 sps = buf + 4;
517 sps_size = size;
518 } else if (nal_type == 8) { /* PPS */
519 pps = buf + 4;
520 pps_size = size;
521 }
522 buf += size + 4;
523 }
524 assert(sps);
525 assert(pps);
526
527 put_byte(pb, 1); /* version */
528 put_byte(pb, sps[1]); /* profile */
529 put_byte(pb, sps[2]); /* profile compat */
530 put_byte(pb, sps[3]); /* level */
531 put_byte(pb, 0xff); /* 6 bits reserved (111111) + 2 bits nal size length - 1 (11) */
532 put_byte(pb, 0xe1); /* 3 bits reserved (111) + 5 bits number of sps (00001) */
533
534 put_be16(pb, sps_size);
535 put_buffer(pb, sps, sps_size);
536 put_byte(pb, 1); /* number of pps */
537 put_be16(pb, pps_size);
538 put_buffer(pb, pps, pps_size);
539 } else {
540 put_buffer(pb, track->vosData, track->vosLen);
541 }
542 }
543 return updateSize(pb, pos);
544 }
545
546 static const CodecTag codec_movvideo_tags[] = {
547 { CODEC_ID_SVQ1, MKTAG('S', 'V', 'Q', '1') },
548 { CODEC_ID_SVQ3, MKTAG('S', 'V', 'Q', '3') },
549 { CODEC_ID_MPEG4, MKTAG('m', 'p', '4', 'v') },
550 { CODEC_ID_H263, MKTAG('s', '2', '6', '3') },
551 { CODEC_ID_H264, MKTAG('a', 'v', 'c', '1') },
552 /* special handling in mov_find_video_codec_tag */
553 { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'c', ' ') }, /* DV NTSC */
554 { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'c', 'p') }, /* DV PAL */
555 { CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'p', 'p') }, /* DVCPRO PAL */
556 { CODEC_ID_DVVIDEO, MKTAG('d', 'v', '5', 'n') }, /* DVCPRO50 NTSC */
557 { CODEC_ID_DVVIDEO, MKTAG('d', 'v', '5', 'p') }, /* DVCPRO50 PAL */
558 { CODEC_ID_NONE, 0 },
559 };
560
561 static int mov_find_video_codec_tag(AVFormatContext *s, MOVTrack *track)
562 {
563 int tag = track->enc->codec_tag;
564 if (!tag) {
565 if (track->enc->codec_id == CODEC_ID_DVVIDEO) {
566 if (track->enc->height == 480) { /* NTSC */
567 if (track->enc->pix_fmt == PIX_FMT_YUV422P)
568 tag = MKTAG('d', 'v', '5', 'n');
569 else
570 tag = MKTAG('d', 'v', 'c', ' ');
571 } else { /* assume PAL */
572 if (track->enc->pix_fmt == PIX_FMT_YUV422P)
573 tag = MKTAG('d', 'v', '5', 'p');
574 else if (track->enc->pix_fmt == PIX_FMT_YUV420P)
575 tag = MKTAG('d', 'v', 'c', 'p');
576 else
577 tag = MKTAG('d', 'v', 'p', 'p');
578 }
579 } else {
580 tag = codec_get_tag(codec_movvideo_tags, track->enc->codec_id);
581 }
582 }
583 // if no mac fcc found, try with Microsoft tags
584 if (!tag) {
585 tag = codec_get_tag(codec_bmp_tags, track->enc->codec_id);
586 if (tag) {
587 av_log(s, AV_LOG_INFO, "Warning, using MS style video codec tag, the file may be unplayable!\n");
588 }
589 }
590 assert(tag);
591 return tag;
592 }
593
594 static int mov_find_audio_codec_tag(AVFormatContext *s, MOVTrack *track)
595 {
596 int tag = track->enc->codec_tag;
597 if (!tag) {
598 tag = codec_get_tag(codec_movaudio_tags, track->enc->codec_id);
599 }
600 // if no mac fcc found, try with Microsoft tags
601 if (!tag) {
602 int ms_tag = codec_get_tag(codec_wav_tags, track->enc->codec_id);
603 if (ms_tag) {
604 tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
605 av_log(s, AV_LOG_INFO, "Warning, using MS style audio codec tag, the file may be unplayable!\n");
606 }
607 }
608 assert(tag);
609 return tag;
610 }
611
612 static int mov_write_video_tag(ByteIOContext *pb, MOVTrack* track)
613 {
614 offset_t pos = url_ftell(pb);
615 char compressor_name[32];
616
617 put_be32(pb, 0); /* size */
618 put_le32(pb, track->tag); // store it byteswapped
619 put_be32(pb, 0); /* Reserved */
620 put_be16(pb, 0); /* Reserved */
621 put_be16(pb, 1); /* Data-reference index */
622
623 put_be16(pb, 0); /* Codec stream version */
624 put_be16(pb, 0); /* Codec stream revision (=0) */
625 put_tag(pb, "FFMP"); /* Vendor */
626 if(track->enc->codec_id == CODEC_ID_RAWVIDEO) {
627 put_be32(pb, 0); /* Temporal Quality */
628 put_be32(pb, 0x400); /* Spatial Quality = lossless*/
629 } else {
630 put_be32(pb, 0x200); /* Temporal Quality = normal */
631 put_be32(pb, 0x200); /* Spatial Quality = normal */
632 }
633 put_be16(pb, track->enc->width); /* Video width */
634 put_be16(pb, track->enc->height); /* Video height */
635 put_be32(pb, 0x00480000); /* Horizontal resolution 72dpi */
636 put_be32(pb, 0x00480000); /* Vertical resolution 72dpi */
637 put_be32(pb, 0); /* Data size (= 0) */
638 put_be16(pb, 1); /* Frame count (= 1) */
639
640 memset(compressor_name,0,32);
641 if (track->enc->codec && track->enc->codec->name)
642 strncpy(compressor_name,track->enc->codec->name,31);
643 put_byte(pb, strlen(compressor_name));
644 put_buffer(pb, compressor_name, 31);
645
646 put_be16(pb, 0x18); /* Reserved */
647 put_be16(pb, 0xffff); /* Reserved */
648 if(track->enc->codec_id == CODEC_ID_MPEG4)
649 mov_write_esds_tag(pb, track);
650 else if(track->enc->codec_id == CODEC_ID_H263)
651 mov_write_d263_tag(pb);
652 else if(track->enc->codec_id == CODEC_ID_SVQ3)
653 mov_write_svq3_tag(pb);
654 else if(track->enc->codec_id == CODEC_ID_H264)
655 mov_write_avcc_tag(pb, track);
656
657 return updateSize (pb, pos);
658 }
659
660 static int mov_write_stsd_tag(ByteIOContext *pb, MOVTrack* track)
661 {
662 offset_t pos = url_ftell(pb);
663 put_be32(pb, 0); /* size */
664 put_tag(pb, "stsd");
665 put_be32(pb, 0); /* version & flags */
666 put_be32(pb, 1); /* entry count */
667 if (track->enc->codec_type == CODEC_TYPE_VIDEO)
668 mov_write_video_tag(pb, track);
669 else if (track->enc->codec_type == CODEC_TYPE_AUDIO)
670 mov_write_audio_tag(pb, track);
671 return updateSize(pb, pos);
672 }
673
674 static int mov_write_ctts_tag(ByteIOContext *pb, MOVTrack* track)
675 {
676 Time2Sample *ctts_entries;
677 uint32_t entries = 0;
678 uint32_t atom_size;
679 int i;
680
681 ctts_entries = av_malloc((track->entry + 1) * sizeof(*ctts_entries)); /* worst case */
682 ctts_entries[0].count = 1;
683 ctts_entries[0].duration = track->cluster[0].cts;
684 for (i=1; i<track->entry; i++) {
685 if (track->cluster[i].cts == ctts_entries[entries].duration) {
686 ctts_entries[entries].count++; /* compress */
687 } else {
688 entries++;
689 ctts_entries[entries].duration = track->cluster[i].cts;
690 ctts_entries[entries].count = 1;
691 }
692 }
693 entries++; /* last one */
694 atom_size = 16 + (entries * 8);
695 put_be32(pb, atom_size); /* size */
696 put_tag(pb, "ctts");
697 put_be32(pb, 0); /* version & flags */
698 put_be32(pb, entries); /* entry count */
699 for (i=0; i<entries; i++) {
700 put_be32(pb, ctts_entries[i].count);
701 put_be32(pb, ctts_entries[i].duration);
702 }
703 av_free(ctts_entries);
704 return atom_size;
705 }
706
707 /* TODO: */
708 /* Time to sample atom */
709 static int mov_write_stts_tag(ByteIOContext *pb, MOVTrack* track)
710 {
711 put_be32(pb, 0x18); /* size */
712 put_tag(pb, "stts");
713 put_be32(pb, 0); /* version & flags */
714 put_be32(pb, 1); /* entry count */
715
716 put_be32(pb, track->sampleCount); /* sample count */
717 put_be32(pb, track->sampleDuration); /* sample duration */
718 return 0x18;
719 }
720
721 static int mov_write_dref_tag(ByteIOContext *pb)
722 {
723 put_be32(pb, 28); /* size */
724 put_tag(pb, "dref");
725 put_be32(pb, 0); /* version & flags */
726 put_be32(pb, 1); /* entry count */
727
728 put_be32(pb, 0xc); /* size */
729 put_tag(pb, "url ");
730 put_be32(pb, 1); /* version & flags */
731
732 return 28;
733 }
734
735 static int mov_write_stbl_tag(ByteIOContext *pb, MOVTrack* track)
736 {
737 offset_t pos = url_ftell(pb);
738 put_be32(pb, 0); /* size */
739 put_tag(pb, "stbl");
740 mov_write_stsd_tag(pb, track);
741 mov_write_stts_tag(pb, track);
742 if (track->enc->codec_type == CODEC_TYPE_VIDEO &&
743 track->hasKeyframes < track->entry)
744 mov_write_stss_tag(pb, track);
745 if (track->enc->codec_type == CODEC_TYPE_VIDEO &&
746 track->hasBframes)
747 mov_write_ctts_tag(pb, track);
748 mov_write_stsc_tag(pb, track);
749 mov_write_stsz_tag(pb, track);
750 mov_write_stco_tag(pb, track);
751 return updateSize(pb, pos);
752 }
753
754 static int mov_write_dinf_tag(ByteIOContext *pb)
755 {
756 offset_t pos = url_ftell(pb);
757 put_be32(pb, 0); /* size */
758 put_tag(pb, "dinf");
759 mov_write_dref_tag(pb);
760 return updateSize(pb, pos);
761 }
762
763 static int mov_write_smhd_tag(ByteIOContext *pb)
764 {
765 put_be32(pb, 16); /* size */
766 put_tag(pb, "smhd");
767 put_be32(pb, 0); /* version & flags */
768 put_be16(pb, 0); /* reserved (balance, normally = 0) */
769 put_be16(pb, 0); /* reserved */
770 return 16;
771 }
772
773 static int mov_write_vmhd_tag(ByteIOContext *pb)
774 {
775 put_be32(pb, 0x14); /* size (always 0x14) */
776 put_tag(pb, "vmhd");
777 put_be32(pb, 0x01); /* version & flags */
778 put_be64(pb, 0); /* reserved (graphics mode = copy) */
779 return 0x14;
780 }
781
782 static int mov_write_hdlr_tag(ByteIOContext *pb, MOVTrack* track)
783 {
784 const char *descr, *hdlr, *hdlr_type;
785 offset_t pos = url_ftell(pb);
786
787 if (!track) { /* no media --> data handler */
788 hdlr = "dhlr";
789 hdlr_type = "url ";
790 descr = "DataHandler";
791 } else {
792 hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
793 if (track->enc->codec_type == CODEC_TYPE_VIDEO) {
794 hdlr_type = "vide";
795 descr = "VideoHandler";
796 } else {
797 hdlr_type = "soun";
798 descr = "SoundHandler";
799 }
800 }
801
802 put_be32(pb, 0); /* size */
803 put_tag(pb, "hdlr");
804 put_be32(pb, 0); /* Version & flags */
805 put_buffer(pb, hdlr, 4); /* handler */
806 put_tag(pb, hdlr_type); /* handler type */
807 put_be32(pb ,0); /* reserved */
808 put_be32(pb ,0); /* reserved */
809 put_be32(pb ,0); /* reserved */
810 put_byte(pb, strlen(descr)); /* string counter */
811 put_buffer(pb, descr, strlen(descr)); /* handler description */
812 return updateSize(pb, pos);
813 }
814
815 static int mov_write_minf_tag(ByteIOContext *pb, MOVTrack* track)
816 {
817 offset_t pos = url_ftell(pb);
818 put_be32(pb, 0); /* size */
819 put_tag(pb, "minf");
820 if(track->enc->codec_type == CODEC_TYPE_VIDEO)
821 mov_write_vmhd_tag(pb);
822 else
823 mov_write_smhd_tag(pb);
824 if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
825 mov_write_hdlr_tag(pb, NULL);
826 mov_write_dinf_tag(pb);
827 mov_write_stbl_tag(pb, track);
828 return updateSize(pb, pos);
829 }
830
831 static int mov_write_mdhd_tag(ByteIOContext *pb, MOVTrack* track)
832 {
833 int version = track->trackDuration < INT32_MAX ? 0 : 1;
834
835 (version == 1) ? put_be32(pb, 44) : put_be32(pb, 32); /* size */
836 put_tag(pb, "mdhd");
837 put_byte(pb, version);
838 put_be24(pb, 0); /* flags */
839 if (version == 1) {
840 put_be64(pb, track->time);
841 put_be64(pb, track->time);
842 } else {
843 put_be32(pb, track->time); /* creation time */
844 put_be32(pb, track->time); /* modification time */
845 }
846 put_be32(pb, track->timescale); /* time scale (sample rate for audio) */
847 (version == 1) ? put_be64(pb, track->trackDuration) : put_be32(pb, track->trackDuration); /* duration */
848 put_be16(pb, track->language); /* language */
849 put_be16(pb, 0); /* reserved (quality) */
850 return 32;
851 }
852
853 static int mov_write_mdia_tag(ByteIOContext *pb, MOVTrack* track)
854 {
855 offset_t pos = url_ftell(pb);
856 put_be32(pb, 0); /* size */
857 put_tag(pb, "mdia");
858 mov_write_mdhd_tag(pb, track);
859 mov_write_hdlr_tag(pb, track);
860 mov_write_minf_tag(pb, track);
861 return updateSize(pb, pos);
862 }
863
864 static int mov_write_tkhd_tag(ByteIOContext *pb, MOVTrack* track)
865 {
866 int64_t duration = av_rescale_rnd(track->trackDuration, globalTimescale, track->timescale, AV_ROUND_UP);
867 int version = duration < INT32_MAX ? 0 : 1;
868
869 (version == 1) ? put_be32(pb, 104) : put_be32(pb, 92); /* size */
870 put_tag(pb, "tkhd");
871 put_byte(pb, version);
872 put_be24(pb, 0xf); /* flags (track enabled) */
873 if (version == 1) {
874 put_be64(pb, track->time);
875 put_be64(pb, track->time);
876 } else {
877 put_be32(pb, track->time); /* creation time */
878 put_be32(pb, track->time); /* modification time */
879 }
880 put_be32(pb, track->trackID); /* track-id */
881 put_be32(pb, 0); /* reserved */
882 (version == 1) ? put_be64(pb, duration) : put_be32(pb, duration);
883
884 put_be32(pb, 0); /* reserved */
885 put_be32(pb, 0); /* reserved */
886 put_be32(pb, 0x0); /* reserved (Layer & Alternate group) */
887 /* Volume, only for audio */
888 if(track->enc->codec_type == CODEC_TYPE_AUDIO)
889 put_be16(pb, 0x0100);
890 else
891 put_be16(pb, 0);
892 put_be16(pb, 0); /* reserved */
893
894 /* Matrix structure */
895 put_be32(pb, 0x00010000); /* reserved */
896 put_be32(pb, 0x0); /* reserved */
897 put_be32(pb, 0x0); /* reserved */
898 put_be32(pb, 0x0); /* reserved */
899 put_be32(pb, 0x00010000); /* reserved */
900 put_be32(pb, 0x0); /* reserved */
901 put_be32(pb, 0x0); /* reserved */
902 put_be32(pb, 0x0); /* reserved */
903 put_be32(pb, 0x40000000); /* reserved */
904
905 /* Track width and height, for visual only */
906 if(track->enc->codec_type == CODEC_TYPE_VIDEO) {
907 double sample_aspect_ratio = av_q2d(track->enc->sample_aspect_ratio);
908 if( !sample_aspect_ratio ) sample_aspect_ratio = 1;
909 put_be32(pb, sample_aspect_ratio * track->enc->width*0x10000);
910 put_be32(pb, track->enc->height*0x10000);
911 }
912 else {
913 put_be32(pb, 0);
914 put_be32(pb, 0);
915 }
916 return 0x5c;
917 }
918
919 // This box seems important for the psp playback ... without it the movie seems to hang
920 static int mov_write_edts_tag(ByteIOContext *pb, MOVTrack *track)
921 {
922 put_be32(pb, 0x24); /* size */
923 put_tag(pb, "edts");
924 put_be32(pb, 0x1c); /* size */
925 put_tag(pb, "elst");
926 put_be32(pb, 0x0);
927 put_be32(pb, 0x1);
928
929 put_be32(pb, av_rescale_rnd(track->trackDuration, globalTimescale, track->timescale, AV_ROUND_UP)); /* duration ... doesn't seem to effect psp */
930
931 if (track->hasBframes)
932 put_be32(pb, track->sampleDuration); /* first pts is 1 */
933 else
934 put_be32(pb, 0);
935 put_be32(pb, 0x00010000);
936 return 0x24;
937 }
938
939 // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
940 static int mov_write_uuid_tag_psp(ByteIOContext *pb, MOVTrack *mov)
941 {
942 put_be32(pb, 0x34); /* size ... reports as 28 in mp4box! */
943 put_tag(pb, "uuid");
944 put_tag(pb, "USMT");
945 put_be32(pb, 0x21d24fce);
946 put_be32(pb, 0xbb88695c);
947 put_be32(pb, 0xfac9c740);
948 put_be32(pb, 0x1c); // another size here!
949 put_tag(pb, "MTDT");
950 put_be32(pb, 0x00010012);
951 put_be32(pb, 0x0a);
952 put_be32(pb, 0x55c40000);
953 put_be32(pb, 0x1);
954 put_be32(pb, 0x0);
955 return 0x34;
956 }
957
958 static int mov_write_trak_tag(ByteIOContext *pb, MOVTrack* track)
959 {
960 offset_t pos = url_ftell(pb);
961 put_be32(pb, 0); /* size */
962 put_tag(pb, "trak");
963 mov_write_tkhd_tag(pb, track);
964 if (track->mode == MODE_PSP || track->hasBframes)
965 mov_write_edts_tag(pb, track); // PSP Movies require edts box
966 mov_write_mdia_tag(pb, track);
967 if (track->mode == MODE_PSP)
968 mov_write_uuid_tag_psp(pb,track); // PSP Movies require this uuid box
969 return updateSize(pb, pos);
970 }
971
972 #if 0
973 /* TODO: Not sorted out, but not necessary either */
974 static int mov_write_iods_tag(ByteIOContext *pb, MOVContext *mov)
975 {
976 put_be32(pb, 0x15); /* size */
977 put_tag(pb, "iods");
978 put_be32(pb, 0); /* version & flags */
979 put_be16(pb, 0x1007);
980 put_byte(pb, 0);
981 put_be16(pb, 0x4fff);
982 put_be16(pb, 0xfffe);
983 put_be16(pb, 0x01ff);
984 return 0x15;
985 }
986 #endif
987
988 static int mov_write_mvhd_tag(ByteIOContext *pb, MOVContext *mov)
989 {
990 int maxTrackID = 1, i;
991 int64_t maxTrackLenTemp, maxTrackLen = 0;
992 int version;
993
994 for (i=0; i<mov->nb_streams; i++) {
995 if(mov->tracks[i].entry > 0) {
996 maxTrackLenTemp = av_rescale_rnd(mov->tracks[i].trackDuration, globalTimescale, mov->tracks[i].timescale, AV_ROUND_UP);
997 if(maxTrackLen < maxTrackLenTemp)
998 maxTrackLen = maxTrackLenTemp;
999 if(maxTrackID < mov->tracks[i].trackID)
1000 maxTrackID = mov->tracks[i].trackID;
1001 }
1002 }
1003
1004 version = maxTrackLen < UINT32_MAX ? 0 : 1;
1005 (version == 1) ? put_be32(pb, 120) : put_be32(pb, 108); /* size */
1006 put_tag(pb, "mvhd");
1007 put_byte(pb, version);
1008 put_be24(pb, 0); /* flags */
1009 if (version == 1) {
1010 put_be64(pb, mov->time);
1011 put_be64(pb, mov->time);
1012 } else {
1013 put_be32(pb, mov->time); /* creation time */
1014 put_be32(pb, mov->time); /* modification time */
1015 }
1016 put_be32(pb, mov->timescale); /* timescale */
1017 (version == 1) ? put_be64(pb, maxTrackLen) : put_be32(pb, maxTrackLen); /* duration of longest track */
1018
1019 put_be32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
1020 put_be16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
1021 put_be16(pb, 0); /* reserved */
1022 put_be32(pb, 0); /* reserved */
1023 put_be32(pb, 0); /* reserved */
1024
1025 /* Matrix structure */
1026 put_be32(pb, 0x00010000); /* reserved */
1027 put_be32(pb, 0x0); /* reserved */
1028 put_be32(pb, 0x0); /* reserved */
1029 put_be32(pb, 0x0); /* reserved */
1030 put_be32(pb, 0x00010000); /* reserved */
1031 put_be32(pb, 0x0); /* reserved */
1032 put_be32(pb, 0x0); /* reserved */
1033 put_be32(pb, 0x0); /* reserved */
1034 put_be32(pb, 0x40000000); /* reserved */
1035
1036 put_be32(pb, 0); /* reserved (preview time) */
1037 put_be32(pb, 0); /* reserved (preview duration) */
1038 put_be32(pb, 0); /* reserved (poster time) */
1039 put_be32(pb, 0); /* reserved (selection time) */
1040 put_be32(pb, 0); /* reserved (selection duration) */
1041 put_be32(pb, 0); /* reserved (current time) */
1042 put_be32(pb, maxTrackID+1); /* Next track id */
1043 return 0x6c;
1044 }
1045
1046 static int mov_write_itunes_hdlr_tag(ByteIOContext *pb, MOVContext* mov,
1047 AVFormatContext *s)
1048 {
1049 offset_t pos = url_ftell(pb);
1050 put_be32(pb, 0); /* size */
1051 put_tag(pb, "hdlr");
1052 put_be32(pb, 0);
1053 put_be32(pb, 0);
1054 put_tag(pb, "mdir");
1055 put_tag(pb, "appl");
1056 put_be32(pb, 0);
1057 put_be32(pb, 0);
1058 put_be16(pb, 0);
1059 return updateSize(pb, pos);
1060 }
1061
1062 /* helper function to write a data tag with the specified string as data */
1063 static int mov_write_string_data_tag(ByteIOContext *pb, const char *data, int long_style)
1064 {
1065 if(long_style){
1066 offset_t pos = url_ftell(pb);
1067 put_be32(pb, 0); /* size */
1068 put_tag(pb, "data");
1069 put_be32(pb, 1);
1070 put_be32(pb, 0);
1071 put_buffer(pb, data, strlen(data));
1072 return updateSize(pb, pos);
1073 }else{
1074 put_be16(pb, strlen(data)); /* string length */
1075 put_be16(pb, 0);
1076 put_buffer(pb, data, strlen(data));
1077 return strlen(data) + 4;
1078 }
1079 }
1080
1081 static int mov_write_string_tag(ByteIOContext *pb, const char *name, const char *value, int long_style){
1082 int size = 0;
1083 if ( value && value[0] ) {
1084 offset_t pos = url_ftell(pb);
1085 put_be32(pb, 0); /* size */
1086 put_tag(pb, name);
1087 mov_write_string_data_tag(pb, value, long_style);
1088 size= updateSize(pb, pos);
1089 }
1090 return size;
1091 }
1092
1093 /* iTunes year */
1094 static int mov_write_day_tag(ByteIOContext *pb, int year, int long_style)
1095 {
1096 if(year){
1097 char year_str[5];
1098 snprintf(year_str, sizeof(year_str), "%04d", year);
1099 return mov_write_string_tag(pb, "\251day", year_str, long_style);
1100 }else
1101 return 0;
1102 }
1103
1104 /* iTunes track number */
1105 static int mov_write_trkn_tag(ByteIOContext *pb, MOVContext* mov,
1106 AVFormatContext *s)
1107 {
1108 int size = 0;
1109 if ( s->track ) {
1110 offset_t pos = url_ftell(pb);
1111 put_be32(pb, 0); /* size */
1112 put_tag(pb, "trkn");
1113 {
1114 offset_t pos = url_ftell(pb);
1115 put_be32(pb, 0); /* size */
1116 put_tag(pb, "data");
1117 put_be32(pb, 0); // 8 bytes empty
1118 put_be32(pb, 0);
1119 put_be16(pb, 0); // empty
1120 put_be16(pb, s->track); // track number
1121 put_be16(pb, 0); // total track number
1122 put_be16(pb, 0); // empty
1123 updateSize(pb, pos);
1124 }
1125 size = updateSize(pb, pos);
1126 }
1127 return size;
1128 }
1129
1130 /* iTunes meta data list */
1131 static int mov_write_ilst_tag(ByteIOContext *pb, MOVContext* mov,
1132 AVFormatContext *s)
1133 {
1134 offset_t pos = url_ftell(pb);
1135 put_be32(pb, 0); /* size */
1136 put_tag(pb, "ilst");
1137 mov_write_string_tag(pb, "\251nam", s->title , 1);
1138 mov_write_string_tag(pb, "\251ART", s->author , 1);
1139 mov_write_string_tag(pb, "\251wrt", s->author , 1);
1140 mov_write_string_tag(pb, "\251alb", s->album , 1);
1141 mov_write_day_tag(pb, s->year ,1);
1142 if(mov->tracks[0].enc && !(mov->tracks[0].enc->flags & CODEC_FLAG_BITEXACT))
1143 mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 1);
1144 mov_write_string_tag(pb, "\251cmt", s->comment , 1);
1145 mov_write_string_tag(pb, "\251gen", s->genre , 1);
1146 mov_write_trkn_tag(pb, mov, s);
1147 return updateSize(pb, pos);
1148 }
1149
1150 /* iTunes meta data tag */
1151 static int mov_write_meta_tag(ByteIOContext *pb, MOVContext* mov,
1152 AVFormatContext *s)
1153 {
1154 int size = 0;
1155
1156 // only save meta tag if required
1157 if ( s->title[0] || s->author[0] || s->album[0] || s->year ||
1158 s->comment[0] || s->genre[0] || s->track ) {
1159 offset_t pos = url_ftell(pb);
1160 put_be32(pb, 0); /* size */
1161 put_tag(pb, "meta");
1162 put_be32(pb, 0);
1163 mov_write_itunes_hdlr_tag(pb, mov, s);
1164 mov_write_ilst_tag(pb, mov, s);
1165 size = updateSize(pb, pos);
1166 }
1167 return size;
1168 }
1169
1170 static int mov_write_udta_tag(ByteIOContext *pb, MOVContext* mov,
1171 AVFormatContext *s)
1172 {
1173 offset_t pos = url_ftell(pb);
1174 int i;
1175
1176 put_be32(pb, 0); /* size */
1177 put_tag(pb, "udta");
1178
1179 /* iTunes meta data */
1180 mov_write_meta_tag(pb, mov, s);
1181
1182 if(mov->mode == MODE_MOV){ // the title field breaks gtkpod with mp4 and my suspicion is that stuff isnt valid in mp4
1183 /* Requirements */
1184 for (i=0; i<mov->nb_streams; i++) {
1185 if(mov->tracks[i].entry <= 0) continue;
1186 if (mov->tracks[i].enc->codec_id == CODEC_ID_AAC ||
1187 mov->tracks[i].enc->codec_id == CODEC_ID_MPEG4) {
1188 mov_write_string_tag(pb, "\251req", "QuickTime 6.0 or greater", 0);
1189 break;
1190 }
1191 }
1192
1193 mov_write_string_tag(pb, "\251nam", s->title , 0);
1194 mov_write_string_tag(pb, "\251aut", s->author , 0);
1195 mov_write_string_tag(pb, "\251alb", s->album , 0);
1196 mov_write_day_tag(pb, s->year, 0);
1197 if(mov->tracks[0].enc && !(mov->tracks[0].enc->flags & CODEC_FLAG_BITEXACT))
1198 mov_write_string_tag(pb, "\251enc", LIBAVFORMAT_IDENT, 0);
1199 mov_write_string_tag(pb, "\251des", s->comment , 0);
1200 mov_write_string_tag(pb, "\251gen", s->genre , 0);
1201 }
1202
1203 return updateSize(pb, pos);
1204 }
1205
1206
1207 static size_t ascii_to_wc (ByteIOContext *pb, char *b, size_t n)
1208 {
1209 size_t i;
1210 unsigned char c;
1211 for (i = 0; i < n - 1; i++) {
1212 c = b[i];
1213 if (! (0x20 <= c && c <= 0x7f ))
1214 c = 0x3f; /* '?' */
1215 put_be16(pb, c);
1216 }
1217 put_be16(pb, 0x00);
1218 return 2*n;
1219 }
1220
1221 static uint16_t language_code (const char *str)
1222 {
1223 return ((((str[0]-0x60) & 0x1F)<<10) + (((str[1]-0x60) & 0x1F)<<5) + ((str[2]-0x60) & 0x1F));
1224 }
1225
1226 static int mov_write_uuidusmt_tag (ByteIOContext *pb, AVFormatContext *s)
1227 {
1228 size_t len, size;
1229 offset_t pos, curpos;
1230
1231 size = 0;
1232 if (s->title[0]) {
1233 pos = url_ftell(pb);
1234 put_be32(pb, 0); /* size placeholder*/
1235 put_tag(pb, "uuid");
1236 put_tag(pb, "USMT");
1237 put_be32(pb, 0x21d24fce ); /* 96 bit UUID */
1238 put_be32(pb, 0xbb88695c );
1239 put_be32(pb, 0xfac9c740 );
1240 size += 24;
1241
1242 put_be32(pb, 0); /* size placeholder*/
1243 put_tag(pb, "MTDT");
1244 put_be16(pb, 4);
1245 size += 10;
1246
1247 // ?
1248 put_be16(pb, 0x0C); /* size */
1249 put_be32(pb, 0x0B); /* type */
1250 put_be16(pb, language_code("und")); /* language */
1251 put_be16(pb, 0x0); /* ? */
1252 put_be16(pb, 0x021C); /* data */
1253 size += 12;
1254
1255 // Encoder
1256 len = strlen(LIBAVCODEC_IDENT)+1;
1257 put_be16(pb, len*2+10); /* size */
1258 put_be32(pb, 0x04); /* type */
1259 put_be16(pb, language_code("eng")); /* language */
1260 put_be16(pb, 0x01); /* ? */
1261 ascii_to_wc(pb, LIBAVCODEC_IDENT, len);
1262 size += len*2+10;
1263
1264 // Title
1265 len = strlen(s->title)+1;
1266 put_be16(pb, len*2+10); /* size */
1267 put_be32(pb, 0x01); /* type */
1268 put_be16(pb, language_code("eng")); /* language */
1269 put_be16(pb, 0x01); /* ? */
1270 ascii_to_wc (pb, s->title, len);
1271 size += len*2+10;
1272
1273 // Date
1274 // snprintf(dt,32,"%04d/%02d/%02d %02d:%02d:%02d",t_st->tm_year+1900,t_st->tm_mon+1,t_st->tm_mday,t_st->tm_hour,t_st->tm_min,t_st->tm_sec);
1275 len = strlen("2006/04/01 11:11:11")+1;
1276 put_be16(pb, len*2+10); /* size */
1277 put_be32(pb, 0x03); /* type */
1278 put_be16(pb, language_code("und")); /* language */
1279 put_be16(pb, 0x01); /* ? */
1280 ascii_to_wc (pb, "2006/04/01 11:11:11", len);
1281 size += len*2+10;
1282
1283 // size
1284 curpos = url_ftell(pb);
1285 url_fseek(pb, pos, SEEK_SET);
1286 put_be32(pb, size);
1287 url_fseek(pb, pos+24, SEEK_SET);
1288 put_be32(pb, size-24);
1289 url_fseek(pb, curpos, SEEK_SET);
1290 }
1291
1292 return size;
1293 }
1294
1295 static int mov_write_moov_tag(ByteIOContext *pb, MOVContext *mov,
1296 AVFormatContext *s)
1297 {
1298 int i;
1299 offset_t pos = url_ftell(pb);
1300 put_be32(pb, 0); /* size placeholder*/
1301 put_tag(pb, "moov");
1302 mov->timescale = globalTimescale;
1303
1304 for (i=0; i<mov->nb_streams; i++) {
1305 if(mov->tracks[i].entry <= 0) continue;
1306
1307 if(mov->tracks[i].enc->codec_type == CODEC_TYPE_VIDEO) {
1308 mov->tracks[i].timescale = mov->tracks[i].enc->time_base.den;
1309 mov->tracks[i].sampleDuration = mov->tracks[i].enc->time_base.num;
1310 } else if(mov->tracks[i].enc->codec_type == CODEC_TYPE_AUDIO) {
1311 mov->tracks[i].timescale = mov->tracks[i].enc->sample_rate;
1312 mov->tracks[i].sampleDuration = mov->tracks[i].enc->frame_size;
1313 }
1314
1315 mov->tracks[i].trackDuration =
1316 (int64_t)mov->tracks[i].sampleCount * mov->tracks[i].sampleDuration;
1317 mov->tracks[i].time = mov->time;
1318 mov->tracks[i].trackID = i+1;
1319 }
1320
1321 mov_write_mvhd_tag(pb, mov);
1322 //mov_write_iods_tag(pb, mov);
1323 for (i=0; i<mov->nb_streams; i++) {
1324 if(mov->tracks[i].entry > 0) {
1325 mov_write_trak_tag(pb, &(mov->tracks[i]));
1326 }
1327 }
1328
1329 if (mov->mode == MODE_PSP)
1330 mov_write_uuidusmt_tag(pb, s);
1331 else
1332 mov_write_udta_tag(pb, mov, s);
1333
1334 return updateSize(pb, pos);
1335 }
1336
1337 static int mov_write_mdat_tag(ByteIOContext *pb, MOVContext* mov)
1338 {
1339 put_be32(pb, 8); // placeholder for extended size field (64 bit)
1340 put_tag(pb, "wide");
1341
1342 mov->mdat_pos = url_ftell(pb);
1343 put_be32(pb, 0); /* size placeholder*/
1344 put_tag(pb, "mdat");
1345 return 0;
1346 }
1347
1348 /* TODO: This needs to be more general */
1349 static void mov_write_ftyp_tag (ByteIOContext *pb, AVFormatContext *s)
1350 {
1351 MOVContext *mov = s->priv_data;
1352
1353 put_be32(pb, 0x14 ); /* size */
1354 put_tag(pb, "ftyp");
1355
1356 if ( mov->mode == MODE_3GP )
1357 put_tag(pb, "3gp4");
1358 else if ( mov->mode == MODE_3G2 )
1359 put_tag(pb, "3g2a");
1360 else if ( mov->mode == MODE_PSP )
1361 put_tag(pb, "MSNV");
1362 else if ( mov->mode == MODE_MP4 )
1363 put_tag(pb, "isom");
1364 else
1365 put_tag(pb, "qt ");
1366
1367 put_be32(pb, 0x200 );
1368
1369 if ( mov->mode == MODE_3GP )
1370 put_tag(pb, "3gp4");
1371 else if ( mov->mode == MODE_3G2 )
1372 put_tag(pb, "3g2a");
1373 else if ( mov->mode == MODE_PSP )
1374 put_tag(pb, "MSNV");
1375 else if ( mov->mode == MODE_MP4 )
1376 put_tag(pb, "mp41");
1377 else
1378 put_tag(pb, "qt ");
1379 }
1380
1381 static void mov_write_uuidprof_tag(ByteIOContext *pb, AVFormatContext *s)
1382 {
1383 AVCodecContext *VideoCodec = s->streams[0]->codec;
1384 AVCodecContext *AudioCodec = s->streams[1]->codec;
1385 int AudioRate = AudioCodec->sample_rate;
1386 int FrameRate = ((VideoCodec->time_base.den) * (0x10000))/ (VideoCodec->time_base.num);
1387 int audio_kbitrate= AudioCodec->bit_rate / 1000;
1388 int video_kbitrate= FFMIN(VideoCodec->bit_rate / 1000, 800 - audio_kbitrate);
1389
1390 put_be32(pb, 0x94 ); /* size */
1391 put_tag(pb, "uuid");
1392 put_tag(pb, "PROF");
1393
1394 put_be32(pb, 0x21d24fce ); /* 96 bit UUID */
1395 put_be32(pb, 0xbb88695c );
1396 put_be32(pb, 0xfac9c740 );
1397
1398 put_be32(pb, 0x0 ); /* ? */
1399 put_be32(pb, 0x3 ); /* 3 sections ? */
1400
1401 put_be32(pb, 0x14 ); /* size */
1402 put_tag(pb, "FPRF");
1403 put_be32(pb, 0x0 ); /* ? */
1404 put_be32(pb, 0x0 ); /* ? */
1405 put_be32(pb, 0x0 ); /* ? */
1406
1407 put_be32(pb, 0x2c ); /* size */
1408 put_tag(pb, "APRF"); /* audio */
1409 put_be32(pb, 0x0 );
1410 put_be32(pb, 0x2 ); /* TrackID */
1411 put_tag(pb, "mp4a");
1412 put_be32(pb, 0x20f );
1413 put_be32(pb, 0x0 );
1414 put_be32(pb, audio_kbitrate);
1415 put_be32(pb, audio_kbitrate);
1416 put_be32(pb, AudioRate );
1417 put_be32(pb, AudioCodec->channels );
1418
1419 put_be32(pb, 0x34 ); /* size */
1420 put_tag(pb, "VPRF"); /* video */
1421 put_be32(pb, 0x0 );
1422 put_be32(pb, 0x1 ); /* TrackID */
1423 if (VideoCodec->codec_id == CODEC_ID_H264) {
1424 put_tag(pb, "avc1");
1425 put_be16(pb, 0x014D );
1426 put_be16(pb, 0x0015 );
1427 } else {
1428 put_tag(pb, "mp4v");
1429 put_be16(pb, 0x0000 );
1430 put_be16(pb, 0x0103 );
1431 }
1432 put_be32(pb, 0x0 );
1433 put_be32(pb, video_kbitrate);
1434 put_be32(pb, video_kbitrate);
1435 put_be32(pb, FrameRate);
1436 put_be32(pb, FrameRate);
1437 put_be16(pb, VideoCodec->width);
1438 put_be16(pb, VideoCodec->height);
1439 put_be32(pb, 0x010001); /* ? */
1440 }
1441
1442 static int mov_write_header(AVFormatContext *s)
1443 {
1444 ByteIOContext *pb = &s->pb;
1445 MOVContext *mov = s->priv_data;
1446 int i;
1447
1448 /* Default mode == MP4 */
1449 mov->mode = MODE_MP4;
1450
1451 if (s->oformat != NULL) {
1452 if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
1453 else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3G2;
1454 else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
1455 else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
1456
1457 mov_write_ftyp_tag(pb,s);
1458 if ( mov->mode == MODE_PSP ) {
1459 if ( s->nb_streams != 2 ) {
1460 av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
1461 return -1;
1462 }
1463 mov_write_uuidprof_tag(pb,s);
1464 }
1465 }
1466
1467 for(i=0; i<s->nb_streams; i++){
1468 AVStream *st= s->streams[i];
1469 MOVTrack *track= &mov->tracks[i];
1470
1471 track->enc = st->codec;
1472 if(st->codec->codec_type == CODEC_TYPE_VIDEO){
1473 track->tag = mov_find_video_codec_tag(s, track);
1474 av_set_pts_info(st, 64, 1, st->codec->time_base.den);
1475 }else if(st->codec->codec_type == CODEC_TYPE_AUDIO){
1476 track->tag = mov_find_audio_codec_tag(s, track);
1477 av_set_pts_info(st, 64, 1, st->codec->sample_rate);
1478
1479 switch (st->codec->codec_id) {
1480 case CODEC_ID_PCM_MULAW:
1481 case CODEC_ID_PCM_ALAW:
1482 track->sampleSize = 1 * st->codec->channels;
1483 break;
1484 case CODEC_ID_PCM_S16BE:
1485 case CODEC_ID_PCM_S16LE:
1486 track->sampleSize = 2 * st->codec->channels;
1487 break;
1488 case CODEC_ID_PCM_S24BE:
1489 case CODEC_ID_PCM_S24LE:
1490 track->sampleSize = 3 * st->codec->channels;
1491 break;
1492 case CODEC_ID_PCM_S32BE:
1493 case CODEC_ID_PCM_S32LE:
1494 track->sampleSize = 4 * st->codec->channels;
1495 break;
1496 default:
1497 track->sampleSize = 0;
1498 }
1499 }
1500 track->language = ff_mov_iso639_to_lang(st->language, mov->mode != MODE_MOV);
1501 track->mode = mov->mode;
1502 }
1503
1504 mov_write_mdat_tag(pb, mov);
1505 mov->time = s->timestamp + 0x7C25B080; //1970 based -> 1904 based
1506 mov->nb_streams = s->nb_streams;
1507
1508 put_flush_packet(pb);
1509
1510 return 0;
1511 }
1512
1513 static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
1514 {
1515 MOVContext *mov = s->priv_data;
1516 ByteIOContext *pb = &s->pb;
1517 MOVTrack *trk = &mov->tracks[pkt->stream_index];
1518 AVCodecContext *enc = trk->enc;
1519 unsigned int samplesInChunk = 0;
1520 int size= pkt->size;
1521
1522 if (url_is_streamed(&s->pb)) return 0; /* Can't handle that */
1523 if (!size) return 0; /* Discard 0 sized packets */
1524
1525 if (enc->codec_type == CODEC_ID_AMR_NB) {
1526 /* We must find out how many AMR blocks there are in one packet */
1527 static uint16_t packed_size[16] =
1528 {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 0};
1529 int len = 0;
1530
1531 while (len < size && samplesInChunk < 100) {
1532 len += packed_size[(pkt->data[len] >> 3) & 0x0F];
1533 samplesInChunk++;
1534 }
1535 } else if (trk->sampleSize)
1536 samplesInChunk = size/trk->sampleSize;
1537 else
1538 samplesInChunk = 1;
1539
1540 /* copy extradata if it exists */
1541 if (trk->vosLen == 0 && enc->extradata_size > 0) {
1542 trk->vosLen = enc->extradata_size;
1543 trk->vosData = av_malloc(trk->vosLen);
1544 memcpy(trk->vosData, enc->extradata, trk->vosLen);
1545 }
1546
1547 if (enc->codec_id == CODEC_ID_H264 && trk->vosLen > 0 && *(uint8_t *)trk->vosData != 1) {
1548 /* from x264 or from bytestream h264 */
1549 /* nal reformating needed */
1550 avc_parse_nal_units(&pkt->data, &pkt->size);
1551 assert(pkt->size);
1552 size = pkt->size;
1553 }
1554
1555 if (!(trk->entry % MOV_INDEX_CLUSTER_SIZE)) {
1556 trk->cluster = av_realloc(trk->cluster, (trk->entry + MOV_INDEX_CLUSTER_SIZE) * sizeof(*trk->cluster));
1557 if (!trk->cluster)
1558 return -1;
1559 }
1560
1561 trk->cluster[trk->entry].pos = url_ftell(pb);
1562 trk->cluster[trk->entry].samplesInChunk = samplesInChunk;
1563 trk->cluster[trk->entry].size = size;
1564 trk->cluster[trk->entry].entries = samplesInChunk;
1565 if(enc->codec_type == CODEC_TYPE_VIDEO) {
1566 if (pkt->dts != pkt->pts)
1567 trk->hasBframes = 1;
1568 trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
1569 trk->cluster[trk->entry].key_frame = !!(pkt->flags & PKT_FLAG_KEY);
1570 if(trk->cluster[trk->entry].key_frame)
1571 trk->hasKeyframes++;
1572 }
1573 trk->entry++;
1574 trk->sampleCount += samplesInChunk;
1575 mov->mdat_size += size;
1576
1577 put_buffer(pb, pkt->data, size);
1578
1579 put_flush_packet(pb);
1580 return 0;
1581 }
1582
1583 static int mov_write_trailer(AVFormatContext *s)
1584 {
1585 MOVContext *mov = s->priv_data;
1586 ByteIOContext *pb = &s->pb;
1587 int res = 0;
1588 int i;
1589
1590 offset_t moov_pos = url_ftell(pb);
1591
1592 /* Write size of mdat tag */
1593 if (mov->mdat_size+8 <= UINT32_MAX) {
1594 url_fseek(pb, mov->mdat_pos, SEEK_SET);
1595 put_be32(pb, mov->mdat_size+8);
1596 } else {
1597 /* overwrite 'wide' placeholder atom */
1598 url_fseek(pb, mov->mdat_pos - 8, SEEK_SET);
1599 put_be32(pb, 1); /* special value: real atom size will be 64 bit value after tag field */
1600 put_tag(pb, "mdat");
1601 put_be64(pb, mov->mdat_size+16);
1602 }
1603 url_fseek(pb, moov_pos, SEEK_SET);
1604
1605 mov_write_moov_tag(pb, mov, s);
1606
1607 for (i=0; i<mov->nb_streams; i++) {
1608 av_freep(&mov->tracks[i].cluster);
1609
1610 if( mov->tracks[i].vosLen ) av_free( mov->tracks[i].vosData );
1611
1612 }
1613
1614 put_flush_packet(pb);
1615
1616 return res;
1617 }
1618
1619 static AVOutputFormat mov_oformat = {
1620 "mov",
1621 "mov format",
1622 NULL,
1623 "mov",
1624 sizeof(MOVContext),
1625 CODEC_ID_AAC,
1626 CODEC_ID_MPEG4,
1627 mov_write_header,
1628 mov_write_packet,
1629 mov_write_trailer,
1630 .flags = AVFMT_GLOBALHEADER,
1631 };
1632
1633 static AVOutputFormat _3gp_oformat = {
1634 "3gp",
1635 "3gp format",
1636 NULL,
1637 "3gp",
1638 sizeof(MOVContext),
1639 CODEC_ID_AMR_NB,
1640 CODEC_ID_H263,
1641 mov_write_header,
1642 mov_write_packet,
1643 mov_write_trailer,
1644 .flags = AVFMT_GLOBALHEADER,
1645 };
1646
1647 static AVOutputFormat mp4_oformat = {
1648 "mp4",
1649 "mp4 format",
1650 "application/mp4",
1651 "mp4,m4a",
1652 sizeof(MOVContext),
1653 CODEC_ID_AAC,
1654 CODEC_ID_MPEG4,
1655 mov_write_header,
1656 mov_write_packet,
1657 mov_write_trailer,
1658 .flags = AVFMT_GLOBALHEADER,
1659 };
1660
1661 static AVOutputFormat psp_oformat = {
1662 "psp",
1663 "psp mp4 format",
1664 NULL,
1665 "mp4,psp",
1666 sizeof(MOVContext),
1667 CODEC_ID_AAC,
1668 CODEC_ID_MPEG4,
1669 mov_write_header,
1670 mov_write_packet,
1671 mov_write_trailer,
1672 .flags = AVFMT_GLOBALHEADER,
1673 };
1674
1675 static AVOutputFormat _3g2_oformat = {
1676 "3g2",
1677 "3gp2 format",
1678 NULL,
1679 "3g2",
1680 sizeof(MOVContext),
1681 CODEC_ID_AMR_NB,
1682 CODEC_ID_H263,
1683 mov_write_header,
1684 mov_write_packet,
1685 mov_write_trailer,
1686 .flags = AVFMT_GLOBALHEADER,
1687 };
1688
1689 int movenc_init(void)
1690 {
1691 av_register_output_format(&mov_oformat);
1692 av_register_output_format(&_3gp_oformat);
1693 av_register_output_format(&mp4_oformat);
1694 av_register_output_format(&psp_oformat);
1695 av_register_output_format(&_3g2_oformat);
1696 return 0;
1697 }