1/*
2 * qt-faststart.c, v0.2
3 * by Mike Melanson (melanson@pcisys.net)
4 * This file is placed in the public domain. Use the program however you
5 * see fit.
6 *
7 * This utility rearranges a Quicktime file such that the moov atom
8 * is in front of the data, thus facilitating network streaming.
9 *
10 * To compile this program, start from the base directory from which you
11 * are building FFmpeg and type:
12 *  make tools/qt-faststart
13 * The qt-faststart program will be built in the tools/ directory. If you
14 * do not build the program in this manner, correct results are not
15 * guaranteed, particularly on 64-bit platforms.
16 * Invoke the program with:
17 *  qt-faststart <infile.mov> <outfile.mov>
18 *
19 * Notes: Quicktime files can come in many configurations of top-level
20 * atoms. This utility stipulates that the very last atom in the file needs
21 * to be a moov atom. When given such a file, this utility will rearrange
22 * the top-level atoms by shifting the moov atom from the back of the file
23 * to the front, and patch the chunk offsets along the way. This utility
24 * presently only operates on uncompressed moov atoms.
25 */
26
27#include <stdio.h>
28#include <stdlib.h>
29#include <inttypes.h>
30
31#ifdef __MINGW32__
32#define fseeko(x,y,z)  fseeko64(x,y,z)
33#define ftello(x)      ftello64(x)
34#endif
35
36#define BE_16(x) ((((uint8_t*)(x))[0] << 8) | ((uint8_t*)(x))[1])
37#define BE_32(x) ((((uint8_t*)(x))[0] << 24) | \
38                  (((uint8_t*)(x))[1] << 16) | \
39                  (((uint8_t*)(x))[2] << 8) | \
40                   ((uint8_t*)(x))[3])
41#define BE_64(x) (((uint64_t)(((uint8_t*)(x))[0]) << 56) | \
42                  ((uint64_t)(((uint8_t*)(x))[1]) << 48) | \
43                  ((uint64_t)(((uint8_t*)(x))[2]) << 40) | \
44                  ((uint64_t)(((uint8_t*)(x))[3]) << 32) | \
45                  ((uint64_t)(((uint8_t*)(x))[4]) << 24) | \
46                  ((uint64_t)(((uint8_t*)(x))[5]) << 16) | \
47                  ((uint64_t)(((uint8_t*)(x))[6]) << 8) | \
48                  ((uint64_t)((uint8_t*)(x))[7]))
49
50#define BE_FOURCC( ch0, ch1, ch2, ch3 )             \
51        ( (uint32_t)(unsigned char)(ch3) |          \
52        ( (uint32_t)(unsigned char)(ch2) << 8 ) |   \
53        ( (uint32_t)(unsigned char)(ch1) << 16 ) |  \
54        ( (uint32_t)(unsigned char)(ch0) << 24 ) )
55
56#define QT_ATOM BE_FOURCC
57/* top level atoms */
58#define FREE_ATOM QT_ATOM('f', 'r', 'e', 'e')
59#define JUNK_ATOM QT_ATOM('j', 'u', 'n', 'k')
60#define MDAT_ATOM QT_ATOM('m', 'd', 'a', 't')
61#define MOOV_ATOM QT_ATOM('m', 'o', 'o', 'v')
62#define PNOT_ATOM QT_ATOM('p', 'n', 'o', 't')
63#define SKIP_ATOM QT_ATOM('s', 'k', 'i', 'p')
64#define WIDE_ATOM QT_ATOM('w', 'i', 'd', 'e')
65#define PICT_ATOM QT_ATOM('P', 'I', 'C', 'T')
66#define FTYP_ATOM QT_ATOM('f', 't', 'y', 'p')
67#define UUID_ATOM QT_ATOM('u', 'u', 'i', 'd')
68
69#define CMOV_ATOM QT_ATOM('c', 'm', 'o', 'v')
70#define STCO_ATOM QT_ATOM('s', 't', 'c', 'o')
71#define CO64_ATOM QT_ATOM('c', 'o', '6', '4')
72
73#define ATOM_PREAMBLE_SIZE 8
74#define COPY_BUFFER_SIZE 1024
75
76int main(int argc, char *argv[])
77{
78    FILE *infile;
79    FILE *outfile;
80    unsigned char atom_bytes[ATOM_PREAMBLE_SIZE];
81    uint32_t atom_type = 0;
82    uint64_t atom_size = 0;
83    uint64_t atom_offset = 0;
84    uint64_t last_offset;
85    unsigned char *moov_atom;
86    unsigned char *ftyp_atom = 0;
87    uint64_t moov_atom_size;
88    uint64_t ftyp_atom_size = 0;
89    uint64_t i, j;
90    uint32_t offset_count;
91    uint64_t current_offset;
92    uint64_t start_offset = 0;
93    unsigned char copy_buffer[COPY_BUFFER_SIZE];
94    int bytes_to_copy;
95
96    if (argc != 3) {
97        printf ("Usage: qt-faststart <infile.mov> <outfile.mov>\n");
98        return 0;
99    }
100
101    infile = fopen(argv[1], "rb");
102    if (!infile) {
103        perror(argv[1]);
104        return 1;
105    }
106
107    /* traverse through the atoms in the file to make sure that 'moov' is
108     * at the end */
109    while (!feof(infile)) {
110        if (fread(atom_bytes, ATOM_PREAMBLE_SIZE, 1, infile) != 1) {
111            break;
112        }
113        atom_size = (uint32_t)BE_32(&atom_bytes[0]);
114        atom_type = BE_32(&atom_bytes[4]);
115
116        /* keep ftyp atom */
117        if (atom_type == FTYP_ATOM) {
118            ftyp_atom_size = atom_size;
119            free(ftyp_atom);
120            ftyp_atom = malloc(ftyp_atom_size);
121            if (!ftyp_atom) {
122                printf ("could not allocate %"PRIu64" byte for ftyp atom\n",
123                        atom_size);
124                fclose(infile);
125                return 1;
126            }
127            fseeko(infile, -ATOM_PREAMBLE_SIZE, SEEK_CUR);
128            if (fread(ftyp_atom, atom_size, 1, infile) != 1) {
129                perror(argv[1]);
130                free(ftyp_atom);
131                fclose(infile);
132                return 1;
133            }
134            start_offset = ftello(infile);
135        } else {
136
137        /* 64-bit special case */
138        if (atom_size == 1) {
139            if (fread(atom_bytes, ATOM_PREAMBLE_SIZE, 1, infile) != 1) {
140                break;
141            }
142            atom_size = BE_64(&atom_bytes[0]);
143            fseeko(infile, atom_size - ATOM_PREAMBLE_SIZE * 2, SEEK_CUR);
144        } else {
145            fseeko(infile, atom_size - ATOM_PREAMBLE_SIZE, SEEK_CUR);
146        }
147    }
148        printf("%c%c%c%c %10"PRIu64" %"PRIu64"\n",
149               (atom_type >> 24) & 255,
150               (atom_type >> 16) & 255,
151               (atom_type >>  8) & 255,
152               (atom_type >>  0) & 255,
153               atom_offset,
154               atom_size);
155        if ((atom_type != FREE_ATOM) &&
156            (atom_type != JUNK_ATOM) &&
157            (atom_type != MDAT_ATOM) &&
158            (atom_type != MOOV_ATOM) &&
159            (atom_type != PNOT_ATOM) &&
160            (atom_type != SKIP_ATOM) &&
161            (atom_type != WIDE_ATOM) &&
162            (atom_type != PICT_ATOM) &&
163            (atom_type != UUID_ATOM) &&
164            (atom_type != FTYP_ATOM)) {
165            printf ("encountered non-QT top-level atom (is this a Quicktime file?)\n");
166            break;
167        }
168        atom_offset += atom_size;
169    }
170
171    if (atom_type != MOOV_ATOM) {
172        printf ("last atom in file was not a moov atom\n");
173        free(ftyp_atom);
174        fclose(infile);
175        return 0;
176    }
177
178    /* moov atom was, in fact, the last atom in the chunk; load the whole
179     * moov atom */
180    fseeko(infile, -atom_size, SEEK_END);
181    last_offset = ftello(infile);
182    moov_atom_size = atom_size;
183    moov_atom = malloc(moov_atom_size);
184    if (!moov_atom) {
185        printf ("could not allocate %"PRIu64" byte for moov atom\n",
186            atom_size);
187        free(ftyp_atom);
188        fclose(infile);
189        return 1;
190    }
191    if (fread(moov_atom, atom_size, 1, infile) != 1) {
192        perror(argv[1]);
193        free(moov_atom);
194        free(ftyp_atom);
195        fclose(infile);
196        return 1;
197    }
198
199    /* this utility does not support compressed atoms yet, so disqualify
200     * files with compressed QT atoms */
201    if (BE_32(&moov_atom[12]) == CMOV_ATOM) {
202        printf ("this utility does not support compressed moov atoms yet\n");
203        free(moov_atom);
204        free(ftyp_atom);
205        fclose(infile);
206        return 1;
207    }
208
209    /* close; will be re-opened later */
210    fclose(infile);
211
212    /* crawl through the moov chunk in search of stco or co64 atoms */
213    for (i = 4; i < moov_atom_size - 4; i++) {
214        atom_type = BE_32(&moov_atom[i]);
215        if (atom_type == STCO_ATOM) {
216            printf (" patching stco atom...\n");
217            atom_size = BE_32(&moov_atom[i - 4]);
218            if (i + atom_size - 4 > moov_atom_size) {
219                printf (" bad atom size\n");
220                free(moov_atom);
221                free(ftyp_atom);
222                return 1;
223            }
224            offset_count = BE_32(&moov_atom[i + 8]);
225            for (j = 0; j < offset_count; j++) {
226                current_offset = BE_32(&moov_atom[i + 12 + j * 4]);
227                current_offset += moov_atom_size;
228                moov_atom[i + 12 + j * 4 + 0] = (current_offset >> 24) & 0xFF;
229                moov_atom[i + 12 + j * 4 + 1] = (current_offset >> 16) & 0xFF;
230                moov_atom[i + 12 + j * 4 + 2] = (current_offset >>  8) & 0xFF;
231                moov_atom[i + 12 + j * 4 + 3] = (current_offset >>  0) & 0xFF;
232            }
233            i += atom_size - 4;
234        } else if (atom_type == CO64_ATOM) {
235            printf (" patching co64 atom...\n");
236            atom_size = BE_32(&moov_atom[i - 4]);
237            if (i + atom_size - 4 > moov_atom_size) {
238                printf (" bad atom size\n");
239                free(moov_atom);
240                free(ftyp_atom);
241                return 1;
242            }
243            offset_count = BE_32(&moov_atom[i + 8]);
244            for (j = 0; j < offset_count; j++) {
245                current_offset = BE_64(&moov_atom[i + 12 + j * 8]);
246                current_offset += moov_atom_size;
247                moov_atom[i + 12 + j * 8 + 0] = (current_offset >> 56) & 0xFF;
248                moov_atom[i + 12 + j * 8 + 1] = (current_offset >> 48) & 0xFF;
249                moov_atom[i + 12 + j * 8 + 2] = (current_offset >> 40) & 0xFF;
250                moov_atom[i + 12 + j * 8 + 3] = (current_offset >> 32) & 0xFF;
251                moov_atom[i + 12 + j * 8 + 4] = (current_offset >> 24) & 0xFF;
252                moov_atom[i + 12 + j * 8 + 5] = (current_offset >> 16) & 0xFF;
253                moov_atom[i + 12 + j * 8 + 6] = (current_offset >>  8) & 0xFF;
254                moov_atom[i + 12 + j * 8 + 7] = (current_offset >>  0) & 0xFF;
255            }
256            i += atom_size - 4;
257        }
258    }
259
260    /* re-open the input file and open the output file */
261    infile = fopen(argv[1], "rb");
262    if (!infile) {
263        perror(argv[1]);
264        free(moov_atom);
265        free(ftyp_atom);
266        return 1;
267    }
268
269    if (start_offset > 0) { /* seek after ftyp atom */
270        fseeko(infile, start_offset, SEEK_SET);
271        last_offset -= start_offset;
272    }
273
274    outfile = fopen(argv[2], "wb");
275    if (!outfile) {
276        perror(argv[2]);
277        fclose(outfile);
278        free(moov_atom);
279        free(ftyp_atom);
280        return 1;
281    }
282
283    /* dump the same ftyp atom */
284    if (ftyp_atom_size > 0) {
285        printf (" writing ftyp atom...\n");
286        if (fwrite(ftyp_atom, ftyp_atom_size, 1, outfile) != 1) {
287            perror(argv[2]);
288            goto error_out;
289        }
290    }
291
292    /* dump the new moov atom */
293    printf (" writing moov atom...\n");
294    if (fwrite(moov_atom, moov_atom_size, 1, outfile) != 1) {
295        perror(argv[2]);
296        goto error_out;
297    }
298
299    /* copy the remainder of the infile, from offset 0 -> last_offset - 1 */
300    printf (" copying rest of file...\n");
301    while (last_offset) {
302        if (last_offset > COPY_BUFFER_SIZE)
303            bytes_to_copy = COPY_BUFFER_SIZE;
304        else
305            bytes_to_copy = last_offset;
306
307        if (fread(copy_buffer, bytes_to_copy, 1, infile) != 1) {
308            perror(argv[1]);
309            goto error_out;
310        }
311        if (fwrite(copy_buffer, bytes_to_copy, 1, outfile) != 1) {
312            perror(argv[2]);
313            goto error_out;
314        }
315
316        last_offset -= bytes_to_copy;
317    }
318
319    fclose(infile);
320    fclose(outfile);
321    free(moov_atom);
322    free(ftyp_atom);
323
324    return 0;
325
326error_out:
327    fclose(infile);
328    fclose(outfile);
329    free(moov_atom);
330    free(ftyp_atom);
331    return 1;
332}
333