about summary refs log tree commit diff
path: root/converter/ppm/ppmtompeg/combine.c
blob: c00f9c7108cabb9c2e60102d910a5fcdb2399cd6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
/*===========================================================================*
 * combine.c
 *
 *  Procedures to combine frames or GOPS into an MPEG sequence
 *
 *===========================================================================*/

/*
 * Copyright (c) 1995 The Regents of the University of California.
 * All rights reserved.
 *
 * Permission to use, copy, modify, and distribute this software and its
 * documentation for any purpose, without fee, and without written agreement is
 * hereby granted, provided that the above copyright notice and the following
 * two paragraphs appear in all copies of this software.
 *
 * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
 * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
 * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
 * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
 * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
 * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
 */

/*==============*
 * HEADER FILES *
 *==============*/

#include "all.h"
#include <time.h>
#include <errno.h>
#include <unistd.h>

#include "nstring.h"
#include "nsleep.h"

#include "mtypes.h"
#include "frames.h"
#include "frametype.h"
#include "motion_search.h"
#include "mpeg.h"
#include "prototypes.h"
#include "parallel.h"
#include "param.h"
#include "readframe.h"
#include "mheaders.h"
#include "fsize.h"
#include "input.h"
#include "combine.h"


#define READ_ATTEMPTS 5 /* number of times (seconds) to retry an input file */

/*==================*
 * GLOBAL VARIABLES *
 *==================*/
extern int  yuvWidth, yuvHeight;


/*===========================================================================*
 *
 * AppendFile
 *
 *  appends the output file with the contents of the given input file
 *
 * RETURNS: nothing
 *
 * SIDE EFFECTS:    none
 *
 *===========================================================================*/
static void
AppendFile(FILE * const ofP,
           FILE * const ifP) {

    uint8 data[9999];
    unsigned int readItems;

    readItems = 9999;
    while (readItems == 9999) {
        readItems = fread(data, sizeof(uint8), 9999, ifP);
        if (readItems > 0)
            fwrite(data, sizeof(uint8), readItems, ofP);
    }
    fclose(ifP);
}



static void
appendSpecifiedGopFiles(struct inputSource * const inputSourceP,
                        const char *         const currentGopPath,
                        FILE *               const ofP) {

    unsigned int fileSeq;

    for (fileSeq = 0; fileSeq < inputSourceP->numInputFiles; ++fileSeq) {
        const char * inputFileName;
        const char * fileName;
        unsigned int nAttempts;
        FILE * ifP;

        GetNthInputFileName(inputSourceP, fileSeq, &inputFileName);
        pm_asprintf(&fileName, "%s/%s", currentGOPPath, inputFileName);

        for (nAttempts = 0, ifP = NULL;
             nAttempts < READ_ATTEMPTS && !ifP;
             ++nAttempts) {

            ifP = fopen(fileName, "rb");
            if (ifP == NULL)
                pm_message("ERROR:  Couldn't read file '%s'.  retry %u", 
                           fileName, nAttempts);
        }
        if (ifP) {
            if (!realQuiet)
                pm_message("Appending file %u '%s'", fileSeq, fileName);
            AppendFile(ofP, ifP);
        } else
            pm_error("Unable to read file '%s' after %u attempts.",
                     fileName, READ_ATTEMPTS);
        pm_strfree(fileName);
        pm_strfree(inputFileName);
    }
} 



static void
appendDefaultGopFiles(const char * const outputFileName,
                      FILE *       const ofP) {

    unsigned int fileSeq;
    bool endOfFiles;
    
    for (fileSeq = 0, endOfFiles = FALSE; !endOfFiles; ++fileSeq) {
        const char * fileName;
        FILE * ifP;

        pm_asprintf(&fileName, "%s.gop.%u", outputFileName, fileSeq);
        
        ifP = fopen(fileName, "rb");
        if (ifP == NULL)
            endOfFiles = TRUE;
        else {
            if (!realQuiet)
                pm_message("appending file:  %s", fileName);
            
            AppendFile(ofP, ifP);
        }
        pm_strfree(fileName);
    }
}



void
GOPsToMPEG(struct inputSource * const inputSourceP,
           const char *         const outputFileName, 
           FILE *               const ofP) {
/*----------------------------------------------------------------------------
   Combine individual GOPs (one per file) into a single MPEG sequence file.
-----------------------------------------------------------------------------*/
    BitBucket * bb;

    {
        /* Why is this reset called? */
        int x=Fsize_x, y=Fsize_y;
        Fsize_Reset();
        Fsize_Note(0, yuvWidth, yuvHeight);
        if (Fsize_x == 0 || Fsize_y == 0)
            Fsize_Note(0, x, y);
    }
    
    bb = Bitio_New(ofP);

    Mhead_GenSequenceHeader(bb, Fsize_x, Fsize_y, /* pratio */ aspectRatio,
                            /* pict_rate */ frameRate, /* bit_rate */ -1,
                            /* buf_size */ -1, /*c_param_flag */ 1,
                            /* iq_matrix */ customQtable, 
                            /* niq_matrix */ customNIQtable,
                            /* ext_data */ NULL, /* ext_data_size */ 0,
                            /* user_data */ NULL, /* user_data_size */ 0);

    /* it's byte-padded, so we can dump it now */
    Bitio_Flush(bb);

    if (inputSourceP->stdinUsed)
        AppendFile(ofP, stdin);
    else {
        if (inputSourceP->numInputFiles > 0)
            appendSpecifiedGopFiles(inputSourceP, currentGOPPath, ofP);
        else
            appendDefaultGopFiles(outputFileName, ofP);
    }
    bb = Bitio_New(ofP);

    /* SEQUENCE END CODE */
    Mhead_GenSequenceEnder(bb);

    Bitio_Flush(bb);

    fclose(ofP);
}



static void
makeGOPHeader(FILE *       const outputFileP,
              unsigned int const totalFramesSent,
              unsigned int const frameNumber,
              unsigned int const seqWithinGop) {

    boolean closed = (totalFramesSent == frameNumber);

    BitBucket * bbP;

    if (!realQuiet)
        fprintf(stdout, "Creating new GOP (closed = %d) after %d frames\n",
                closed, seqWithinGop);

    /* new GOP */
    bbP = Bitio_New(outputFileP);
    Mhead_GenGOPHeader(bbP, /* drop_frame_flag */ 0,
                       tc_hrs, tc_min, tc_sec, tc_pict,
                       closed, /* broken_link */ 0,
                       /* ext_data */ NULL, /* ext_data_size */ 0,
                       /* user_data */ NULL, 
                       /* user_data_size */ 0);
    Bitio_Flush(bbP);
    SetGOPStartTime(frameNumber);
}        



void
FramesToMPEG(FILE *               const outputFile, 
             void *               const inputHandle,
             fileAcquisitionFn          acquireInputFile,
             fileDispositionFn          disposeInputFile) {
/*----------------------------------------------------------------------------
   Combine a bunch of frames, one per file, into a single MPEG
   sequence file.

   acquireInputFile() opens a file that contains an encoded frame,
   identified by frame number.  It returns NULL when the frame number
   is beyond the frames available.
-----------------------------------------------------------------------------*/
    unsigned int frameNumber;
    BitBucket *bb;
    FILE *inputFile;
    int pastRefNum = -1;
    int futureRefNum = -1;
    boolean inputLeft;
    unsigned int seqWithinGop;
        /* The sequence of the current frame within its GOP.  0 is the
           first frame of a GOP, etc.
        */

    tc_hrs = 0; tc_min = 0; tc_sec = 0; tc_pict = 0; tc_extra = 0;

    {
        /* Why is this reset called? */
        int x=Fsize_x, y=Fsize_y;
        Fsize_Reset();
        Fsize_Note(0, yuvWidth, yuvHeight);
        if (Fsize_x == 0 || Fsize_y == 0)
            Fsize_Note(0, x, y);
    }
    SetBlocksPerSlice();

    bb = Bitio_New(outputFile);
    Mhead_GenSequenceHeader(bb, Fsize_x, Fsize_y, /* pratio */ aspectRatio,
                            /* pict_rate */ frameRate, /* bit_rate */ -1,
                            /* buf_size */ -1, /*c_param_flag */ 1,
                            /* iq_matrix */ qtable, /* niq_matrix */ niqtable,
                            /* ext_data */ NULL, /* ext_data_size */ 0,
                            /* user_data */ NULL, /* user_data_size */ 0);
    /* it's byte-padded, so we can dump it now */
    Bitio_Flush(bb);

    /* need to do these in the right order!!! */
    /* also need to add GOP headers */

    seqWithinGop = 0;
    totalFramesSent = 0;

    inputLeft = TRUE;
    frameNumber = 0;

    makeGOPHeader(outputFile, totalFramesSent, frameNumber, seqWithinGop);
    
    while (inputLeft) {
        if (FType_Type(frameNumber) != 'b') {
            pastRefNum = futureRefNum;
            futureRefNum = frameNumber;

            if ((FType_Type(frameNumber) == 'i') && seqWithinGop >= gopSize) {
                makeGOPHeader(outputFile,
                              totalFramesSent, frameNumber, seqWithinGop);
                seqWithinGop -= gopSize;
            }

            acquireInputFile(inputHandle, frameNumber, &inputFile);
            if (inputFile == NULL)
                inputLeft = FALSE;
            else {
                AppendFile(outputFile, inputFile);

                disposeInputFile(inputHandle, frameNumber);

                ++seqWithinGop;
                IncrementTCTime();

                /* now, output the B-frames */
                if (pastRefNum != -1) {
                    unsigned int bNum;
                    
                    for (bNum = pastRefNum+1; bNum < futureRefNum; ++bNum) {
                        acquireInputFile(inputHandle, bNum, &inputFile);

                        if (inputFile) {
                            AppendFile(outputFile, inputFile);

                            disposeInputFile(inputHandle, bNum);
            
                            ++seqWithinGop;
                            IncrementTCTime();
                        }
                    }
                }
            }
        }
        ++frameNumber;
    }

    if (!realQuiet)
        fprintf(stdout, "Wrote %d frames\n", totalFramesSent);

    bb = Bitio_New(outputFile);

    /* SEQUENCE END CODE */
    Mhead_GenSequenceEnder(bb);

    Bitio_Flush(bb);

    fclose(outputFile);
}