Statistics
| Branch: | Revision:

chunker-player / chunker_streamer / chunker_streamer.c @ f838b30a

History | View | Annotate | Download (48.4 KB)

1
/*
2
 *  Copyright (c) 2009-2011 Carmelo Daniele, Dario Marchese, Diego Reforgiato, Giuseppe Tropea
3
 *  Copyright (c) 2010-2011 Csaba Kiraly
4
 *  developed for the Napa-Wine EU project. See www.napa-wine.eu
5
 *
6
 *  This is free software; see lgpl-2.1.txt
7
 */
8

    
9
#include "chunker_streamer.h"
10
#include <signal.h>
11
#include <math.h>
12
#include <getopt.h>
13
#include <libswscale/swscale.h>
14
#include <libavutil/opt.h>
15

    
16
#ifdef USE_AVFILTER
17
#include <libavfilter/avfilter.h>
18
#include "chunker_filtering.h"
19
#endif
20

    
21
#include "chunk_pusher.h"
22

    
23
struct outstream {
24
        struct output *output;
25
        ExternalChunk *chunk;
26
        AVCodecContext *pCodecCtxEnc;
27
};
28
struct outstream outstream[2];
29

    
30
#define DEBUG
31
#define DEBUG_AUDIO_FRAMES  false
32
#define DEBUG_VIDEO_FRAMES  false
33
#define DEBUG_CHUNKER false
34
#define DEBUG_ANOMALIES true
35
#define DEBUG_TIMESTAMPING false
36
#include "dbg.h"
37

    
38
#define STREAMER_MAX(a,b) ((a>b)?(a):(b))
39
#define STREAMER_MIN(a,b) ((a<b)?(a):(b))
40

    
41
//#define DISPLAY_PSNR
42
#define GET_PSNR(x) ((x==0) ? 0 : (-10.0*log(x)/log(10)))
43

    
44
ChunkerMetadata *cmeta = NULL;
45
int seq_current_chunk = 1; //chunk numbering starts from 1; HINT do i need more bytes?
46

    
47
#define AUDIO_CHUNK 0
48
#define VIDEO_CHUNK 1
49

    
50
void SaveFrame(AVFrame *pFrame, int width, int height);
51
void SaveEncodedFrame(Frame* frame, uint8_t *video_outbuf);
52
int update_chunk(ExternalChunk *chunk, Frame *frame, uint8_t *outbuf);
53
void bit32_encoded_push(uint32_t v, uint8_t *p);
54

    
55
int video_record_count = 0;
56
int savedVideoFrames = 0;
57
long int firstSavedVideoFrame = 0;
58
int ChunkerStreamerTestMode = 0;
59

    
60
int pts_anomaly_threshold = -1;
61
int newtime_anomaly_threshold = -1;
62
bool timebank = false;
63
char *outside_world_url = NULL;
64

    
65
int gop_size = 25;
66
int max_b_frames = 3;
67
bool vcopy = false;
68

    
69
long delay_audio = 0; //delay audio by x millisec
70

    
71
char *avfilter="yadif";
72

    
73
// Constant number of frames per chunk
74
int chunkFilledFramesStrategy(ExternalChunk *echunk, int chunkType)
75
{
76
        dcprintf(DEBUG_CHUNKER, "CHUNKER: check if frames num %d == %d in chunk %d\n", echunk->frames_num, cmeta->framesPerChunk[chunkType], echunk->seq);
77
        if(echunk->frames_num == cmeta->framesPerChunk[chunkType])
78
                return 1;
79

    
80
        return 0;
81
}
82

    
83
// Constant size. Note that for now each chunk will have a size just greater or equal than the required value
84
// It can be considered as constant size.
85
int chunkFilledSizeStrategy(ExternalChunk *echunk, int chunkType)
86
{
87
        dcprintf(DEBUG_CHUNKER, "CHUNKER: check if chunk size %d >= %d in chunk %d\n", echunk->payload_len, cmeta->targetChunkSize, echunk->seq);
88
        if(echunk->payload_len >= cmeta->targetChunkSize)
89
                return 1;
90
        
91
        return 0;
92
}
93

    
94
// Performace optimization.
95
// The chunkFilled function has been splitted into two functions (one for each strategy).
96
// Instead of continuously check the strategy flag (which is constant),
97
// we change the callback just once according to the current strategy (look at the switch statement in the main in which this function pointer is set)
98
int (*chunkFilled)(ExternalChunk *echunk, int chunkType);
99

    
100
void initChunk(ExternalChunk *chunk, int *seq_num) {
101
        chunk->seq = (*seq_num)++;
102
        chunk->frames_num = 0;
103
        chunk->payload_len = 0;
104
        chunk->len=0;
105
  if(chunk->data != NULL)
106
    free(chunk->data);
107
        chunk->data = NULL;
108
        chunk->start_time.tv_sec = -1;
109
        chunk->start_time.tv_usec = -1;
110
        chunk->end_time.tv_sec = -1;
111
        chunk->end_time.tv_usec = -1;
112
        chunk->priority = 0;
113
        chunk->category = 0;
114
        chunk->_refcnt = 0;
115
}
116

    
117
int quit = 0;
118

    
119
void sigproc()
120
{
121
        printf("you have pressed ctrl-c, terminating...\n");
122
        quit = 1;
123
}
124

    
125
static void print_usage(int argc, char *argv[])
126
{
127
  fprintf (stderr,
128
    "\nUsage:%s [options]\n"
129
    "\n"
130
    "Mandatory options:\n"
131
    "\t[-i input file]\n"
132
    "\t[-a audio bitrate]\n"
133
    "\t[-v video bitrate]\n\n"
134
    "Other options:\n"
135
    "\t[-F output] (overrides config file)\n"
136
    "\t[-A audioencoder]\n"
137
    "\t[-V videoencoder]\n"
138
    "\t[-s WxH]: force video size.\n"
139
    "\t[-l]: this is a live stream.\n"
140
    "\t[-o]: adjust A/V frame timestamps (deafault off, use it only with flawed containers)\n"
141
    "\t[-p]: pts anomaly threshold (default: -1=off).\n"
142
    "\t[-q]: sync anomaly threshold ((default: -1=off).\n"
143
    "\t[-t]: QoE test mode\n\n"
144

    
145
    "\t[--video_stream]:set video_stream ID in input\n"
146
    "\t[--audio_stream]:set audio_stream ID in input\n"
147
    "\t[--avfilter]:set input filter (default: yadif\n"
148
    "\n"
149
    "Codec options:\n"
150
    "\t[-g GOP]: gop size\n"
151
    "\t[-b frames]: max number of consecutive b frames\n"
152
    "\t[-x extas]: extra video codec options (e.g. -x me_method=hex,flags2=+dct8x8+wpred+bpyrami+mixed_refs)\n"
153
    "\n"
154
    "=======================================================\n", argv[0]
155
    );
156
  }
157

    
158
int sendChunk(struct output *output, ExternalChunk *chunk) {
159
#ifdef HTTPIO
160
                                                return pushChunkHttp(chunk, outside_world_url);
161
#endif
162
#ifdef TCPIO
163
                                                return pushChunkTcp(output, chunk);
164
#endif
165
#ifdef UDPIO
166
                                                return pushChunkUDP(chunk);
167
#endif
168
}
169

    
170

    
171
int transcodeFrame(uint8_t *video_outbuf, int video_outbuf_size, int64_t *target_pts, AVFrame *pFrame, AVRational time_base, AVCodecContext *pCodecCtx, AVCodecContext *pCodecCtxEnc)
172
{
173
        int video_frame_size = 0;
174
        AVFrame *pFrame2 = NULL;
175
        AVFrame *scaledFrame = NULL;
176
        pFrame2=avcodec_alloc_frame();
177
        scaledFrame=avcodec_alloc_frame();
178
        if(pFrame2==NULL || scaledFrame==NULL) {
179
                fprintf(stderr, "INIT: Memory error alloc video frame!!!\n");
180
                if(pFrame2) av_free(pFrame2);
181
                if(scaledFrame) av_free(scaledFrame);
182
                return -1;
183
        }
184
        int scaledFrame_buf_size = avpicture_get_size( PIX_FMT_YUV420P, pCodecCtxEnc->width, pCodecCtxEnc->height);
185
        uint8_t* scaledFrame_buffer = (uint8_t *) av_malloc( scaledFrame_buf_size * sizeof( uint8_t ) );
186
        avpicture_fill( (AVPicture*) scaledFrame, scaledFrame_buffer, PIX_FMT_YUV420P, pCodecCtxEnc->width, pCodecCtxEnc->height);
187
        if(!video_outbuf || !scaledFrame_buffer) {
188
                fprintf(stderr, "INIT: Memory error alloc video_outbuf!!!\n");
189
                return -1;
190
        }
191

    
192
                                            if (pFrame->pkt_pts != AV_NOPTS_VALUE) {
193
                                                pFrame->pts = av_rescale_q(pFrame->pkt_pts, time_base, pCodecCtxEnc->time_base);
194
                                            } else {        //try to figure out the pts //TODO: review this
195
                                                if (pFrame->pkt_dts != AV_NOPTS_VALUE) {
196
                                                        pFrame->pts = av_rescale_q(pFrame->pkt_dts, time_base, pCodecCtxEnc->time_base);
197
                                                }
198
                                            }
199

    
200
#ifdef VIDEO_DEINTERLACE
201
                                            avpicture_deinterlace(
202
                                                        (AVPicture*) pFrame,
203
                                                        (const AVPicture*) pFrame,
204
                                                        pCodecCtxEnc->pix_fmt,
205
                                                        pCodecCtxEnc->width,
206
                                                        pCodecCtxEnc->height);
207
#endif
208

    
209
#ifdef USE_AVFILTER
210
                                            //apply avfilters
211
                                            filter(pFrame,pFrame2);
212
                                            pFrame = pFrame2;
213
                                            dcprintf(DEBUG_VIDEO_FRAMES, "VIDEOdecode: pkt_dts %"PRId64" pkt_pts %"PRId64" frame.pts %"PRId64"\n", pFrame2->pkt_dts, pFrame2->pkt_pts, pFrame2->pts);
214
                                            dcprintf(DEBUG_VIDEO_FRAMES, "VIDEOdecode intype %d%s\n", pFrame2->pict_type, pFrame2->key_frame ? " (key)" : "");
215
#endif
216

    
217
                                            if(pCodecCtx->height != pCodecCtxEnc->height || pCodecCtx->width != pCodecCtxEnc->width) {
218
//                                                static AVPicture pict;
219
                                                static struct SwsContext *img_convert_ctx = NULL;
220

    
221
                                                pFrame->pict_type = 0;
222
                                                if(img_convert_ctx == NULL)
223
                                                {
224
                                                        img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, PIX_FMT_YUV420P, pCodecCtxEnc->width, pCodecCtxEnc->height, PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);
225
                                                        if(img_convert_ctx == NULL) {
226
                                                                fprintf(stderr, "Cannot initialize the conversion context!\n");
227
                                                                exit(1);
228
                                                        }
229
                                                }
230
                                                sws_scale(img_convert_ctx, pFrame->data, pFrame->linesize, 0, pCodecCtx->height, scaledFrame->data, scaledFrame->linesize);
231
                                                scaledFrame->pts = pFrame->pts;
232
                                                scaledFrame->pict_type = 0;
233
                                                video_frame_size = avcodec_encode_video(pCodecCtxEnc, video_outbuf, video_outbuf_size, scaledFrame);
234
                                            } else {
235
                                                pFrame->pict_type = 0;
236
                                                video_frame_size = avcodec_encode_video(pCodecCtxEnc, video_outbuf, video_outbuf_size, pFrame);
237
                                            }
238

    
239
                                            //use pts if dts is invalid
240
                                            if(pCodecCtxEnc->coded_frame->pts!=AV_NOPTS_VALUE)
241
                                                *target_pts = av_rescale_q(pCodecCtxEnc->coded_frame->pts, pCodecCtxEnc->time_base, time_base);
242
                                            else {        //TODO: review this
243
                                                if(pFrame2) av_free(pFrame2);
244
                                                if(scaledFrame) av_free(scaledFrame);
245
                                                if(scaledFrame_buffer) av_free(scaledFrame_buffer);
246
                                                return -1;
247
                                            }
248

    
249
                                        if(video_frame_size > 0) {
250
                                            if(pCodecCtxEnc->coded_frame) {
251
                                                dcprintf(DEBUG_VIDEO_FRAMES, "VIDEOout: pkt_dts %"PRId64" pkt_pts %"PRId64" frame.pts %"PRId64"\n", pCodecCtxEnc->coded_frame->pkt_dts, pCodecCtxEnc->coded_frame->pkt_pts, pCodecCtxEnc->coded_frame->pts);
252
                                                dcprintf(DEBUG_VIDEO_FRAMES, "VIDEOout: outtype: %d%s\n", pCodecCtxEnc->coded_frame->pict_type, pCodecCtxEnc->coded_frame->key_frame ? " (key)" : "");
253
                                            }
254
#ifdef DISPLAY_PSNR
255
                                            static double ist_psnr = 0;
256
                                            static double cum_psnr = 0;
257
                                            static int psnr_samples = 0;
258
                                            if(pCodecCtxEnc->coded_frame) {
259
                                                if(pCodecCtxEnc->flags&CODEC_FLAG_PSNR) {
260
                                                        ist_psnr = GET_PSNR(pCodecCtxEnc->coded_frame->error[0]/(pCodecCtxEnc->width*pCodecCtxEnc->height*255.0*255.0));
261
                                                        psnr_samples++;
262
                                                        cum_psnr += ist_psnr;
263
                                                        fprintf(stderr, "PSNR: ist %.4f avg: %.4f\n", ist_psnr, cum_psnr / (double)psnr_samples);
264
                                                }
265
                                            }
266
#endif
267
                                        }
268

    
269
        if(pFrame2) av_free(pFrame2);
270
        if(scaledFrame) av_free(scaledFrame);
271
        if(scaledFrame_buffer) av_free(scaledFrame_buffer);
272
        return video_frame_size;
273
}
274

    
275

    
276
void createFrame(struct Frame *frame, long long newTime, int video_frame_size, int pict_type)
277
{
278

    
279
                                        frame->timestamp.tv_sec = (long long)newTime/1000;
280
                                        frame->timestamp.tv_usec = newTime%1000;
281
                                        frame->size = video_frame_size;
282
                                        /* pict_type maybe 1 (I), 2 (P), 3 (B), 5 (AUDIO)*/
283
                                        frame->type = pict_type;
284

    
285

    
286
/* should be on some other place
287
//                                        if (!vcopy) dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO: original codec frame number %d vs. encoded %d vs. packed %d\n", pCodecCtx->frame_number, pCodecCtxEnc->frame_number, frame->number);
288
//                                        if (!vcopy) dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO: duration %d timebase %d %d container timebase %d\n", (int)packet.duration, pCodecCtxEnc->time_base.den, pCodecCtxEnc->time_base.num, pCodecCtx->time_base.den);
289

290
#ifdef YUV_RECORD_ENABLED
291
                                        if(!vcopy && ChunkerStreamerTestMode)
292
                                        {
293
                                                if(videotrace)
294
                                                        fprintf(videotrace, "%d %d %d\n", frame->number, pict_type, frame->size);
295

296
                                                SaveFrame(pFrame, dest_width, dest_height);
297

298
                                                ++savedVideoFrames;
299
                                                SaveEncodedFrame(frame, video_outbuf);
300

301
                                                if(!firstSavedVideoFrame)
302
                                                        firstSavedVideoFrame = frame->number;
303

304
                                                char tmp_filename[255];
305
                                                sprintf(tmp_filename, "yuv_data/streamer_out_context.txt");
306
                                                FILE* tmp = fopen(tmp_filename, "w");
307
                                                if(tmp)
308
                                                {
309
                                                        fprintf(tmp, "width = %d\nheight = %d\ntotal_frames_saved = %d\ntotal_frames_decoded = %d\nfirst_frame_number = %ld\nlast_frame_number = %d\n"
310
                                                                ,dest_width, dest_height
311
                                                                ,savedVideoFrames, savedVideoFrames, firstSavedVideoFrame, frame->number);
312
                                                        fclose(tmp);
313
                                                }
314
                                        }
315
#endif
316
*/
317

    
318
                                        dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO: encapsulated frame size:%d type:%d\n", frame->size, frame->type);
319
                                        dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO: timestamped sec %ld usec:%ld\n", (long)frame->timestamp.tv_sec, (long)frame->timestamp.tv_usec);
320
}
321

    
322

    
323
void addFrameToOutstream(struct outstream *os, Frame *frame, uint8_t *video_outbuf)
324
{
325

    
326
        ExternalChunk *chunk = os->chunk;
327
        struct output *output = os->output;
328

    
329
                                        if(update_chunk(chunk, frame, video_outbuf) == -1) {
330
                                                fprintf(stderr, "VIDEO: unable to update chunk %d. Exiting.\n", chunk->seq);
331
                                                exit(-1);
332
                                        }
333

    
334
                                        if(chunkFilled(chunk, VIDEO_CHUNK)) { // is chunk filled using current strategy?
335
                                                //calculate priority
336
                                                chunk->priority /= chunk->frames_num;
337

    
338
                                                //SAVE ON FILE
339
                                                //saveChunkOnFile(chunk);
340
                                                //Send the chunk to an external transport/player
341
                                                sendChunk(output, chunk);
342
                                                dctprintf(DEBUG_CHUNKER, "VIDEO: sent chunk video %d, prio:%f, size %d\n", chunk->seq, chunk->priority, chunk->len);
343
                                                chunk->seq = 0; //signal that we need an increase
344
                                                //initChunk(chunk, &seq_current_chunk);
345
                                        }
346
}
347

    
348
long long pts2ms(int64_t pts, AVRational time_base)
349
{
350
        return pts * 1000 * time_base.num / time_base.den;
351
}
352

    
353
AVCodecContext *openVideoEncoder(const char *video_codec, int video_bitrate, int dest_width, int dest_height, AVRational time_base, const char *codec_options) {
354

    
355
        AVCodec *pCodecEnc;
356
        AVCodecContext *pCodecCtxEnc;
357

    
358
        //setup video output encoder
359
        if (strcmp(video_codec, "copy") == 0) {
360
                return NULL;
361
        }
362

    
363
        pCodecEnc = avcodec_find_encoder_by_name(video_codec);
364
        if (pCodecEnc) {
365
                fprintf(stderr, "INIT: Setting VIDEO codecID to: %d\n",pCodecEnc->id);
366
        } else {
367
                fprintf(stderr, "INIT: Unknown OUT VIDEO codec: %s!\n", video_codec);
368
                return NULL; // Codec not found
369
        }
370

    
371
        pCodecCtxEnc=avcodec_alloc_context();
372
        pCodecCtxEnc->codec_type = CODEC_TYPE_VIDEO;
373
        pCodecCtxEnc->codec_id = pCodecEnc->id;
374

    
375
        pCodecCtxEnc->bit_rate = video_bitrate;
376
        //~ pCodecCtxEnc->qmin = 30;
377
        //~ pCodecCtxEnc->qmax = 30;
378
        //times 20 follows the defaults, was not needed in previous versions of libavcodec
379
//        pCodecCtxEnc->crf = 20.0f;
380
        // resolution must be a multiple of two 
381
        pCodecCtxEnc->width = dest_width;
382
        pCodecCtxEnc->height = dest_height;
383
        // frames per second 
384
        //~ pCodecCtxEnc->time_base= pCodecCtx->time_base;//(AVRational){1,25};
385
        //printf("pCodecCtx->time_base=%d/%d\n", pCodecCtx->time_base.num, pCodecCtx->time_base.den);
386
        pCodecCtxEnc->time_base= time_base;//(AVRational){1,25};
387
        pCodecCtxEnc->gop_size = gop_size; // emit one intra frame every gop_size frames 
388
        pCodecCtxEnc->max_b_frames = max_b_frames;
389
        pCodecCtxEnc->pix_fmt = PIX_FMT_YUV420P;
390
        pCodecCtxEnc->flags |= CODEC_FLAG_PSNR;
391
        //~ pCodecCtxEnc->flags |= CODEC_FLAG_QSCALE;
392

    
393
        //some generic quality tuning
394
        pCodecCtxEnc->mb_decision = FF_MB_DECISION_RD;
395

    
396
        //some rate control parameters for streaming, taken from ffserver.c
397
        {
398
        /* Bitrate tolerance is less for streaming */
399
        AVCodecContext *av = pCodecCtxEnc;
400
        if (av->bit_rate_tolerance == 0)
401
            av->bit_rate_tolerance = FFMAX(av->bit_rate / 4,
402
                      (int64_t)av->bit_rate*av->time_base.num/av->time_base.den);
403
        //if (av->qmin == 0)
404
        //    av->qmin = 3;
405
        //if (av->qmax == 0)
406
        //    av->qmax = 31;
407
        //if (av->max_qdiff == 0)
408
        //    av->max_qdiff = 3;
409
        //av->qcompress = 0.5;
410
        //av->qblur = 0.5;
411

    
412
        //if (!av->nsse_weight)
413
        //    av->nsse_weight = 8;
414

    
415
        //av->frame_skip_cmp = FF_CMP_DCTMAX;
416
        //if (!av->me_method)
417
        //    av->me_method = ME_EPZS;
418
        //av->rc_buffer_aggressivity = 1.0;
419

    
420
        //if (!av->rc_eq)
421
        //    av->rc_eq = "tex^qComp";
422
        //if (!av->i_quant_factor)
423
        //    av->i_quant_factor = -0.8;
424
        //if (!av->b_quant_factor)
425
        //    av->b_quant_factor = 1.25;
426
        //if (!av->b_quant_offset)
427
        //    av->b_quant_offset = 1.25;
428
        if (!av->rc_max_rate)
429
            av->rc_max_rate = av->bit_rate * 2;
430

    
431
        if (av->rc_max_rate && !av->rc_buffer_size) {
432
            av->rc_buffer_size = av->rc_max_rate;
433
        }
434
        }
435
        //end of code taken fromffserver.c
436

    
437
  switch (pCodecEnc->id) {
438
    case CODEC_ID_H264 :
439
        // Fast Profile
440
        // libx264-fast.ffpreset preset 
441
        pCodecCtxEnc->coder_type = FF_CODER_TYPE_AC; // coder = 1 -> enable CABAC
442
        pCodecCtxEnc->flags |= CODEC_FLAG_LOOP_FILTER; // flags=+loop -> deblock
443
        pCodecCtxEnc->me_cmp|= 1; // cmp=+chroma, where CHROMA = 1
444
        pCodecCtxEnc->partitions |= X264_PART_I8X8|X264_PART_I4X4|X264_PART_P8X8|X264_PART_B8X8;        // partitions=+parti8x8+parti4x4+partp8x8+partb8x8
445
        pCodecCtxEnc->me_method=ME_HEX; // me_method=hex
446
        pCodecCtxEnc->me_subpel_quality = 6; // subq=7
447
        pCodecCtxEnc->me_range = 16; // me_range=16
448
        //pCodecCtxEnc->gop_size = 250; // g=250
449
        //pCodecCtxEnc->keyint_min = 25; // keyint_min=25
450
        pCodecCtxEnc->scenechange_threshold = 40; // sc_threshold=40
451
        pCodecCtxEnc->i_quant_factor = 0.71; // i_qfactor=0.71
452
        pCodecCtxEnc->b_frame_strategy = 1; // b_strategy=1
453
        pCodecCtxEnc->qcompress = 0.6; // qcomp=0.6
454
        pCodecCtxEnc->qmin = 10; // qmin=10
455
        pCodecCtxEnc->qmax = 51; // qmax=51
456
        pCodecCtxEnc->max_qdiff = 4; // qdiff=4
457
        //pCodecCtxEnc->max_b_frames = 3; // bf=3
458
        pCodecCtxEnc->refs = 2; // refs=3
459
        //pCodecCtxEnc->directpred = 1; // directpred=1
460
        pCodecCtxEnc->directpred = 3; // directpred=1 in preset -> "directpred", "direct mv prediction mode - 0 (none), 1 (spatial), 2 (temporal), 3 (auto)"
461
        //pCodecCtxEnc->trellis = 1; // trellis=1
462
        pCodecCtxEnc->flags2 |= CODEC_FLAG2_BPYRAMID|CODEC_FLAG2_MIXED_REFS|CODEC_FLAG2_WPRED|CODEC_FLAG2_8X8DCT|CODEC_FLAG2_FASTPSKIP;        // flags2=+bpyramid+mixed_refs+wpred+dct8x8+fastpskip
463
        pCodecCtxEnc->weighted_p_pred = 2; // wpredp=2
464

    
465
        // libx264-main.ffpreset preset
466
        //pCodecCtxEnc->flags2|=CODEC_FLAG2_8X8DCT;
467
        //pCodecCtxEnc->flags2^=CODEC_FLAG2_8X8DCT; // flags2=-dct8x8
468
        //pCodecCtxEnc->crf = 22;
469

    
470
#ifdef STREAMER_X264_USE_SSIM
471
        pCodecCtxEnc->flags2 |= CODEC_FLAG2_SSIM;
472
#endif
473

    
474
        //pCodecCtxEnc->weighted_p_pred=2; //maps wpredp=2; weighted prediction analysis method
475
        // pCodecCtxEnc->rc_min_rate = 0;
476
        // pCodecCtxEnc->rc_max_rate = video_bitrate*2;
477
        // pCodecCtxEnc->rc_buffer_size = 0;
478
        break;
479
    case CODEC_ID_MPEG4 :
480
        break;
481
    default:
482
        fprintf(stderr, "INIT: Unsupported OUT VIDEO codec: %s!\n", video_codec);
483
  }
484

    
485
  if ((av_set_options_string(pCodecCtxEnc, codec_options, "=", ",")) < 0) {
486
    fprintf(stderr, "Error parsing options string: '%s'\n", codec_options);
487
    return NULL;
488
  }
489

    
490
  if(avcodec_open(pCodecCtxEnc, pCodecEnc)<0) {
491
    fprintf(stderr, "INIT: could not open OUT VIDEO codecEnc\n");
492
    return NULL; // Could not open codec
493
  }
494

    
495
 return pCodecCtxEnc;
496
}
497

    
498

    
499
int main(int argc, char *argv[]) {
500
        signal(SIGINT, sigproc);
501
        
502
        int i=0;
503

    
504
        //output variables
505
        uint8_t *video_outbuf = NULL;
506
        int video_outbuf_size, video_frame_size;
507
        uint8_t *audio_outbuf = NULL;
508
        int audio_outbuf_size, audio_frame_size;
509
        int audio_data_size;
510

    
511
        //numeric identifiers of input streams
512
        int videoStream = -1;
513
        int audioStream = -1;
514

    
515
//        int len1;
516
        int frameFinished;
517
        //frame sequential counters
518
        int contFrameAudio=1, contFrameVideo=0;
519
//        int numBytes;
520

    
521
        //command line parameters
522
        int audio_bitrate = -1;
523
        int video_bitrate = -1;
524
        char *audio_codec = "mp2";
525
        char *video_codec = "mpeg4";
526
        char *codec_options = "";
527
        int live_source = 0; //tells to sleep before reading next frame in not live (i.e. file)
528
        int offset_av = 0; //tells to compensate for offset between audio and video in the file
529
        
530
        //a raw buffer for decoded uncompressed audio samples
531
        int16_t *samples = NULL;
532
        //a raw uncompressed video picture
533
        AVFrame *pFrame1 = NULL;
534

    
535
        AVFormatContext *pFormatCtx;
536
        AVCodecContext  *pCodecCtx = NULL ,*aCodecCtxEnc = NULL ,*aCodecCtx = NULL;
537
        AVCodec         *pCodec = NULL ,*aCodec = NULL ,*aCodecEnc = NULL;
538
        AVPacket         packet;
539

    
540
        //stuff needed to compute the right timestamps
541
        short int FirstTimeAudio=1, FirstTimeVideo=1;
542
        short int pts_anomalies_counter=0;
543
        short int newtime_anomalies_counter=0;
544
        long long newTime=0, newTime_audio=0, newTime_video=0, newTime_prev=0;
545
        struct timeval lastAudioSent = {0, 0};
546
        int64_t ptsvideo1=0;
547
        int64_t ptsaudio1=0;
548
        int64_t last_pkt_dts=0, delta_video=0, delta_audio=0, last_pkt_dts_audio=0, target_pts=0;
549

    
550
        //Napa-Wine specific Frame and Chunk structures for transport
551
        Frame *frame = NULL;
552
        ExternalChunk *chunkaudio = NULL;
553
        
554
        char av_input[1024];
555
        int dest_width = -1;
556
        int dest_height = -1;
557
        
558
        static struct option long_options[] =
559
        {
560
                {"audio_stream", required_argument, 0, 0},
561
                {"video_stream", required_argument, 0, 0},
562
                {"avfilter", required_argument, 0, 0},
563
                {0, 0, 0, 0}
564
        };
565
        /* `getopt_long' stores the option index here. */
566
        int option_index = 0, c;
567
        int mandatories = 0;
568
        while ((c = getopt_long (argc, argv, "i:a:v:A:V:s:lop:q:tF:g:b:d:x:", long_options, &option_index)) != -1)
569
        {
570
                switch (c) {
571
                        case 0: //for long options
572
                                if( strcmp( "audio_stream", long_options[option_index].name ) == 0 ) { audioStream = atoi(optarg); }
573
                                if( strcmp( "video_stream", long_options[option_index].name ) == 0 ) { videoStream = atoi(optarg); }
574
                                if( strcmp( "avfilter", long_options[option_index].name ) == 0 ) { avfilter = strdup(optarg); }
575
                                break;
576
                        case 'i':
577
                                sprintf(av_input, "%s", optarg);
578
                                mandatories++;
579
                                break;
580
                        case 'a':
581
                                sscanf(optarg, "%d", &audio_bitrate);
582
                                mandatories++;
583
                                break;
584
                        case 'v':
585
                                sscanf(optarg, "%d", &video_bitrate);
586
                                mandatories++;
587
                                break;
588
                        case 'A':
589
                                audio_codec = strdup(optarg);
590
                                break;
591
                        case 'V':
592
                                video_codec = strdup(optarg);
593
                                break;
594
                        case 's':
595
                                sscanf(optarg, "%dx%d", &dest_width, &dest_height);
596
                                break;
597
                        case 'l':
598
                                live_source = 1;
599
                                break;
600
                        case 'o':
601
                                offset_av = 1;
602
                                break;
603
                        case 't':
604
                                ChunkerStreamerTestMode = 1;
605
                                break;
606
                        case 'p':
607
                                sscanf(optarg, "%d", &pts_anomaly_threshold);
608
                                break;
609
                        case 'q':
610
                                sscanf(optarg, "%d", &newtime_anomaly_threshold);
611
                                break;
612
                        case 'F':
613
                                outside_world_url = strdup(optarg);
614
                                break;
615
                        case 'g':
616
                                sscanf(optarg, "%d", &gop_size);
617
                                break;
618
                        case 'b':
619
                                sscanf(optarg, "%d", &max_b_frames);
620
                                break;
621
                        case 'd':
622
                                sscanf(optarg, "%ld", &delay_audio);
623
                                break;
624
                        case 'x':
625
                                codec_options = strdup(optarg);
626
                                break;
627
                        default:
628
                                print_usage(argc, argv);
629
                                return -1;
630
                }
631
        }
632
        
633
        if(mandatories < 3) 
634
        {
635
                print_usage(argc, argv);
636
                return -1;
637
        }
638

    
639
#ifdef YUV_RECORD_ENABLED
640
        if(ChunkerStreamerTestMode)
641
        {
642
                DELETE_DIR("yuv_data");
643
                CREATE_DIR("yuv_data");
644
                //FILE* pFile=fopen("yuv_data/streamer_out.yuv", "w");
645
                //fclose(pFile);
646
        }
647
#endif
648

    
649
restart:
650
        // read the configuration file
651
        cmeta = chunkerInit();
652
        if (!outside_world_url) {
653
                outside_world_url = strdup(cmeta->outside_world_url);
654
        }
655
        switch(cmeta->strategy)
656
        {
657
                case 1:
658
                        chunkFilled = chunkFilledSizeStrategy;
659
                        break;
660
                default:
661
                        chunkFilled = chunkFilledFramesStrategy;
662
        }
663
                
664
        if(live_source)
665
                fprintf(stderr, "INIT: Using LIVE SOURCE TimeStamps\n");
666
        if(offset_av)
667
                fprintf(stderr, "INIT: Compensating AV OFFSET in file\n");
668

    
669
        // Register all formats and codecs
670
        av_register_all();
671

    
672
        // Open input file
673
        if(av_open_input_file(&pFormatCtx, av_input, NULL, 0, NULL) != 0) {
674
                fprintf(stdout, "INIT: Couldn't open video file. Exiting.\n");
675
                exit(-1);
676
        }
677

    
678
        // Retrieve stream information
679
        if(av_find_stream_info(pFormatCtx) < 0) {
680
                fprintf(stdout, "INIT: Couldn't find stream information. Exiting.\n");
681
                exit(-1);
682
        }
683

    
684
        // Dump information about file onto standard error
685
        av_dump_format(pFormatCtx, 0, av_input, 0);
686

    
687
        // Find the video and audio stream numbers
688
        for(i=0; i<pFormatCtx->nb_streams; i++) {
689
                if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_VIDEO && videoStream<0) {
690
                        videoStream=i;
691
                }
692
                if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_AUDIO && audioStream<0) {
693
                        audioStream=i;
694
                }
695
        }
696

    
697
        if(videoStream==-1 || audioStream==-1) {        // TODO: refine to work with 1 or the other
698
                fprintf(stdout, "INIT: Didn't find audio and video streams. Exiting.\n");
699
                exit(-1);
700
        }
701

    
702
        fprintf(stderr, "INIT: Num streams : %d TBR: %d %d RFRAMERATE:%d %d Duration:%ld\n", pFormatCtx->nb_streams, pFormatCtx->streams[videoStream]->time_base.num, pFormatCtx->streams[videoStream]->time_base.den, pFormatCtx->streams[videoStream]->r_frame_rate.num, pFormatCtx->streams[videoStream]->r_frame_rate.den, (long int)pFormatCtx->streams[videoStream]->duration);
703

    
704
        fprintf(stderr, "INIT: Video stream has id : %d\n",videoStream);
705
        fprintf(stderr, "INIT: Audio stream has id : %d\n",audioStream);
706

    
707

    
708
        // Get a pointer to the codec context for the input video stream
709
        pCodecCtx=pFormatCtx->streams[videoStream]->codec;
710
        pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
711
        //extract W and H
712
        fprintf(stderr, "INIT: Width:%d Height:%d\n", pCodecCtx->width, pCodecCtx->height);
713

    
714
        // Get a pointer to the codec context for the input audio stream
715
        if(audioStream != -1) {
716
                aCodecCtx=pFormatCtx->streams[audioStream]->codec;
717
                fprintf(stderr, "INIT: AUDIO Codecid: %d channels %d samplerate %d\n", aCodecCtx->codec_id, aCodecCtx->channels, aCodecCtx->sample_rate);
718
        }
719

    
720
        // Figure out size
721
        dest_width = (dest_width > 0) ? dest_width : pCodecCtx->width;
722
        dest_height = (dest_height > 0) ? dest_height : pCodecCtx->height;
723

    
724
        //create an empty first video chunk
725
        outstream[0].chunk = (ExternalChunk *)malloc(sizeof(ExternalChunk));
726
        if(!outstream[0].chunk) {
727
                fprintf(stderr, "INIT: Memory error alloc chunk!!!\n");
728
                return -1;
729
        }
730
        outstream[0].chunk->data = NULL;
731
        outstream[0].chunk->seq = 0;
732
        dcprintf(DEBUG_CHUNKER, "INIT: chunk video %d\n", outstream[0].chunk->seq);
733
        outstream[0].pCodecCtxEnc = NULL;
734

    
735
        outstream[1].chunk = (ExternalChunk *)malloc(sizeof(ExternalChunk));
736
        if(!outstream[1].chunk) {
737
                fprintf(stderr, "INIT: Memory error alloc chunk!!!\n");
738
                return -1;
739
        }
740
        outstream[1].chunk->data = NULL;
741
        outstream[1].chunk->seq = 0;
742
        dcprintf(DEBUG_CHUNKER, "INIT: chunk video %d\n", outstream[1].chunk->seq);
743
        outstream[1].pCodecCtxEnc = openVideoEncoder(video_codec, video_bitrate, dest_width, dest_height, pCodecCtx->time_base, codec_options);
744
        if (!outstream[1].pCodecCtxEnc) {
745
                return -1;
746
        }
747

    
748
        fprintf(stderr, "INIT: VIDEO timebase OUT:%d %d IN: %d %d\n", outstream[1].pCodecCtxEnc->time_base.num, outstream[1].pCodecCtxEnc->time_base.den, pCodecCtx->time_base.num, pCodecCtx->time_base.den);
749

    
750
        if(pCodec==NULL) {
751
                fprintf(stderr, "INIT: Unsupported IN VIDEO pcodec!\n");
752
                return -1; // Codec not found
753
        }
754
        if(avcodec_open(pCodecCtx, pCodec)<0) {
755
                fprintf(stderr, "INIT: could not open IN VIDEO codec\n");
756
                return -1; // Could not open codec
757
        }
758
        if(audioStream!=-1) {
759
                //setup audio output encoder
760
                aCodecCtxEnc = avcodec_alloc_context();
761
                aCodecCtxEnc->bit_rate = audio_bitrate; //256000
762
                aCodecCtxEnc->sample_fmt = SAMPLE_FMT_S16;
763
                aCodecCtxEnc->sample_rate = aCodecCtx->sample_rate;
764
                aCodecCtxEnc->channels = aCodecCtx->channels;
765
                fprintf(stderr, "INIT: AUDIO bitrate OUT:%d sample_rate:%d channels:%d\n", aCodecCtxEnc->bit_rate, aCodecCtxEnc->sample_rate, aCodecCtxEnc->channels);
766

    
767
                // Find the decoder for the audio stream
768
                aCodec = avcodec_find_decoder(aCodecCtx->codec_id);
769
                aCodecEnc = avcodec_find_encoder_by_name(audio_codec);
770
                if(aCodec==NULL) {
771
                        fprintf(stderr,"INIT: Unsupported acodec!\n");
772
                        return -1;
773
                }
774
                if(aCodecEnc==NULL) {
775
                        fprintf(stderr,"INIT: Unsupported acodecEnc!\n");
776
                        return -1;
777
                }
778
        
779
                if(avcodec_open(aCodecCtx, aCodec)<0) {
780
                        fprintf(stderr, "INIT: could not open IN AUDIO codec\n");
781
                        return -1; // Could not open codec
782
                }
783
                if(avcodec_open(aCodecCtxEnc, aCodecEnc)<0) {
784
                        fprintf(stderr, "INIT: could not open OUT AUDIO codec\n");
785
                        return -1; // Could not open codec
786
                }
787
        }
788
        else {
789
                fprintf(stderr,"INIT: NO AUDIO TRACK IN INPUT FILE\n");
790
        }
791

    
792
        // Allocate audio in and out buffers
793
        samples = (int16_t *)av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
794
        if(samples == NULL) {
795
                fprintf(stderr, "INIT: Memory error alloc audio samples!!!\n");
796
                return -1;
797
        }
798
        audio_outbuf_size = STREAMER_MAX_AUDIO_BUFFER_SIZE;
799
        audio_outbuf = av_malloc(audio_outbuf_size);
800
        if(audio_outbuf == NULL) {
801
                fprintf(stderr, "INIT: Memory error alloc audio_outbuf!!!\n");
802
                return -1;
803
        }
804

    
805
        // Allocate video in frame and out buffer
806
        pFrame1=avcodec_alloc_frame();
807
        if(pFrame1==NULL) {
808
                fprintf(stderr, "INIT: Memory error alloc video frame!!!\n");
809
                return -1;
810
        }
811
        video_outbuf_size = STREAMER_MAX_VIDEO_BUFFER_SIZE;
812
        video_outbuf = av_malloc(video_outbuf_size);
813

    
814
        //allocate Napa-Wine transport
815
        frame = (Frame *)malloc(sizeof(Frame));
816
        if(!frame) {
817
                fprintf(stderr, "INIT: Memory error alloc Frame!!!\n");
818
                return -1;
819
        }
820

    
821
        //create empty first audio chunk
822

    
823
        chunkaudio = (ExternalChunk *)malloc(sizeof(ExternalChunk));
824
        if(!chunkaudio) {
825
                fprintf(stderr, "INIT: Memory error alloc chunkaudio!!!\n");
826
                return -1;
827
        }
828
  chunkaudio->data=NULL;
829
        chunkaudio->seq = 0;
830
        //initChunk(chunkaudio, &seq_current_chunk);
831
        dcprintf(DEBUG_CHUNKER, "INIT: chunk audio %d\n", chunkaudio->seq);
832

    
833
#ifdef HTTPIO
834
        /* initialize the HTTP chunk pusher */
835
        initChunkPusher(); //TRIPLO
836
#endif
837

    
838
        long sleep=0;
839
        struct timeval now_tv;
840
        struct timeval tmp_tv;
841
        long long lateTime = 0;
842
        long long maxAudioInterval = 0;
843
        long long maxVDecodeTime = 0;
844
//        unsigned char lastIFrameDistance = 0;
845

    
846
#ifdef TCPIO
847
        static char peer_ip[16];
848
        static int peer_port;
849
        int res = sscanf(outside_world_url, "tcp://%15[0-9.]:%d", peer_ip, &peer_port);
850
        if (res < 2) {
851
                fprintf(stderr,"error parsing output url: %s\n", outside_world_url);
852
                return -2;
853
        }
854
        
855
        outstream[0].output = initTCPPush(peer_ip, peer_port);
856
        if (!outstream[0].output) {
857
                fprintf(stderr, "Error initializing output module, exiting\n");
858
                exit(1);
859
        }
860
        outstream[1].output = initTCPPush(peer_ip, peer_port+1);
861
        if (!outstream[1].output) {
862
                fprintf(stderr, "Error initializing output module, exiting\n");
863
                exit(1);
864
        }
865
#endif
866
#ifdef UDPIO
867
        static char peer_ip[16];
868
        static int peer_port;
869
        int res = sscanf(outside_world_url, "udp://%15[0-9.]:%d", peer_ip, &peer_port);
870
        if (res < 2) {
871
                fprintf(stderr,"error parsing output url: %s\n", outside_world_url);
872
                return -2;
873
        }
874
        
875
        initUDPPush(peer_ip, peer_port);
876
#endif
877
        
878
        char videotrace_filename[255];
879
        char psnr_filename[255];
880
        sprintf(videotrace_filename, "yuv_data/videotrace.log");
881
        sprintf(psnr_filename, "yuv_data/psnrtrace.log");
882
        FILE* videotrace = fopen(videotrace_filename, "w");
883
        FILE* psnrtrace = fopen(psnr_filename, "w");
884

    
885
#ifdef USE_AVFILTER
886
        //init AVFilter
887
        avfilter_register_all();
888
        init_filters(avfilter, pCodecCtx);
889
#endif
890

    
891
        //main loop to read from the input file
892
        while((av_read_frame(pFormatCtx, &packet)>=0) && !quit)
893
        {
894
                //detect if a strange number of anomalies is occurring
895
                if(ptsvideo1 < 0 || ptsvideo1 > packet.dts || ptsaudio1 < 0 || ptsaudio1 > packet.dts) {
896
                        pts_anomalies_counter++;
897
                        dcprintf(DEBUG_ANOMALIES, "READLOOP: pts BASE anomaly detected number %d\n", pts_anomalies_counter);
898
                        if(pts_anomaly_threshold >=0 && live_source) { //reset just in case of live source
899
                                if(pts_anomalies_counter > pts_anomaly_threshold) {
900
                                        dcprintf(DEBUG_ANOMALIES, "READLOOP: too many pts BASE anomalies. resetting pts base\n");
901
                                        av_free_packet(&packet);
902
                                        goto close;
903
                                }
904
                        }
905
                }
906

    
907
                //newTime_video and _audio are in usec
908
                //if video and audio stamps differ more than 5sec
909
                if( newTime_video - newTime_audio > 5000000 || newTime_video - newTime_audio < -5000000 ) {
910
                        newtime_anomalies_counter++;
911
                        dcprintf(DEBUG_ANOMALIES, "READLOOP: NEWTIME audio video differ anomaly detected number %d\n", newtime_anomalies_counter);
912
                }
913

    
914
                if(newtime_anomaly_threshold >=0 && newtime_anomalies_counter > newtime_anomaly_threshold) {
915
                        if(live_source) { //restart just in case of live source
916
                                dcprintf(DEBUG_ANOMALIES, "READLOOP: too many NEGATIVE TIMESTAMPS anomalies. Restarting.\n");
917
                                av_free_packet(&packet);
918
                                goto close;
919
                        }
920
                }
921

    
922
                // Is this a packet from the video stream?
923
                if(packet.stream_index==videoStream)
924
                {
925
                        if(!live_source)
926
                        {
927
                                if(audioStream != -1) { //take this "time bank" method into account only if we have audio track
928
                                        // lateTime < 0 means a positive time account that can be used to decode video frames
929
                                        // if (lateTime + maxVDecodeTime) >= 0 then we may have a negative time account after video transcoding
930
                                        // therefore, it's better to skip the frame
931
                                        if(timebank && (lateTime+maxVDecodeTime) >= 0)
932
                                        {
933
                                                dcprintf(DEBUG_ANOMALIES, "\n\n\t\t************************* SKIPPING VIDEO FRAME %ld ***********************************\n\n", sleep);
934
                                                av_free_packet(&packet);
935
                                                continue;
936
                                        }
937
                                }
938
                        }
939
                        
940
                        gettimeofday(&tmp_tv, NULL);
941
                        
942
                        //decode the video packet into a raw pFrame
943
                        if(avcodec_decode_video2(pCodecCtx, pFrame1, &frameFinished, &packet)>0)
944
                        {
945
                                AVFrame *pFrame;
946
                                pFrame = pFrame1;
947

    
948
                                // usleep(5000);
949
                                dcprintf(DEBUG_VIDEO_FRAMES, "VIDEOin pkt: dts %"PRId64" pts %"PRId64" pts-dts %"PRId64"\n", packet.dts, packet.pts, packet.pts-packet.dts );
950
                                dcprintf(DEBUG_VIDEO_FRAMES, "VIDEOdecode: pkt_dts %"PRId64" pkt_pts %"PRId64" frame.pts %"PRId64"\n", pFrame->pkt_dts, pFrame->pkt_pts, pFrame->pts);
951
                                dcprintf(DEBUG_VIDEO_FRAMES, "VIDEOdecode intype %d%s\n", pFrame->pict_type, pFrame->key_frame ? " (key)" : "");
952
                                if(frameFinished)
953
                                { // it must be true all the time else error
954
                                
955
                                        frame->number = ++contFrameVideo;
956

    
957

    
958

    
959
                                        dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO: finished frame %d dts %"PRId64" pts %"PRId64"\n", frame->number, packet.dts, packet.pts);
960
                                        if(frame->number==0) {
961
                                                if(packet.dts==AV_NOPTS_VALUE)
962
                                                {
963
                                                        //a Dts with a noPts value is troublesome case for delta calculation based on Dts
964
                                                        contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0);
965
                                                        av_free_packet(&packet);
966
                                                        continue;
967
                                                }
968
                                                last_pkt_dts = packet.dts;
969
                                                newTime = 0;
970
                                        }
971
                                        else {
972
                                                if(packet.dts!=AV_NOPTS_VALUE) {
973
                                                        delta_video = packet.dts-last_pkt_dts;
974
                                                        last_pkt_dts = packet.dts;
975
                                                }
976
                                                else if(delta_video==0)
977
                                                {
978
                                                        //a Dts with a noPts value is troublesome case for delta calculation based on Dts
979
                                                        contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0);
980
                                                        av_free_packet(&packet);
981
                                                        continue;
982
                                                }
983
                                        }
984
                                        dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO: deltavideo : %d\n", (int)delta_video);
985

    
986
                                        //set initial timestamp
987
                                        if(FirstTimeVideo && pFrame->pkt_pts>0) {
988
                                                if(offset_av) {
989
                                                        ptsvideo1 = pFrame->pkt_pts;
990
                                                        FirstTimeVideo = 0;
991
                                                        dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO: SET PTS BASE OFFSET %"PRId64"\n", ptsvideo1);
992
                                                } else { //we want to compensate audio and video offset for this source
993
                                                        //maintain the offset between audio pts and video pts
994
                                                        //because in case of live source they have the same numbering
995
                                                        if(ptsaudio1 > 0) //if we have already seen some audio frames...
996
                                                                ptsvideo1 = ptsaudio1;
997
                                                        else
998
                                                                ptsvideo1 = pFrame->pkt_pts;
999
                                                        FirstTimeVideo = 0;
1000
                                                        dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO LIVE: SET PTS BASE OFFSET %"PRId64"\n", ptsvideo1);
1001
                                                }
1002
                                        }
1003

    
1004
                                        // store timestamp in useconds for next frame sleep
1005
                                        newTime_video = pts2ms(pFrame->pkt_pts - ptsvideo1, pFormatCtx->streams[videoStream]->time_base)*1000;
1006

    
1007
                                        if(true) {
1008
                                                video_frame_size = packet.size;
1009
                                                if (video_frame_size > video_outbuf_size) {
1010
                                                        fprintf(stderr, "VIDEO: error, outbuf too small, SKIPPING\n");;
1011
                                                        av_free_packet(&packet);
1012
                                                        continue;
1013
                                                } else {
1014
                                                        memcpy(video_outbuf, packet.data, video_frame_size);
1015
                                                }
1016

    
1017
                                                if (pFrame->pkt_pts != AV_NOPTS_VALUE) {
1018
                                                        target_pts = pFrame->pkt_pts;
1019
                                                }else {        //TODO: review this
1020
                                                        target_pts = pFrame->pkt_dts;
1021
                                                }
1022
                                                createFrame(frame, pts2ms(target_pts - ptsvideo1, pFormatCtx->streams[videoStream]->time_base), video_frame_size, 
1023
                                                    pFrame->pict_type);
1024
                                                addFrameToOutstream(&outstream[0], frame, video_outbuf);
1025
                                        }
1026
                                        if(true) {
1027
                                                video_frame_size = transcodeFrame(video_outbuf, video_outbuf_size, &target_pts, pFrame, pFormatCtx->streams[videoStream]->time_base, pCodecCtx, outstream[1].pCodecCtxEnc);
1028
                                                if (video_frame_size <= 0) {
1029
                                                        av_free_packet(&packet);
1030
                                                        contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0);
1031
                                                        continue;
1032
                                                }
1033
                                                createFrame(frame, pts2ms(target_pts - ptsvideo1, pFormatCtx->streams[videoStream]->time_base), video_frame_size, 
1034
                                                    (unsigned char)outstream[1].pCodecCtxEnc->coded_frame->pict_type);
1035
                                                addFrameToOutstream(&outstream[1], frame, video_outbuf);
1036
                                        }
1037

    
1038

    
1039
                                        //compute how long it took to encode video frame
1040
                                        gettimeofday(&now_tv, NULL);
1041
                                        long long usec = (now_tv.tv_sec-tmp_tv.tv_sec)*1000000;
1042
                                        usec+=(now_tv.tv_usec-tmp_tv.tv_usec);
1043
                                        if(usec > maxVDecodeTime)
1044
                                                maxVDecodeTime = usec;
1045

    
1046
                                        //we DONT have an audio track, so we compute timings and determine
1047
                                        //how much time we have to sleep at next VIDEO frame taking
1048
                                        //also into account how much time was needed to encode the current
1049
                                        //video frame
1050
                                        //all this in case the video source is not live, i.e. not self-timing
1051
                                        //and only in case there is no audio track
1052
                                        if(audioStream == -1) {
1053
                                                if(!live_source) {
1054
                                                        if(newTime_prev != 0) {
1055
                                                                //how much delay between video frames ideally
1056
                                                                long long maxDelay = newTime_video - newTime_prev;
1057
                                                                sleep = (maxDelay - usec);
1058
                                                                dcprintf(DEBUG_ANOMALIES,"\tmaxDelay=%ld\n", ((long)maxDelay));
1059
                                                                dcprintf(DEBUG_ANOMALIES,"\tlast video frame interval=%ld; sleep time=%ld\n", ((long)usec), ((long)sleep));
1060
                                                        }
1061
                                                        else
1062
                                                                sleep = 0;
1063

    
1064
                                                        //update and store counters
1065
                                                        newTime_prev = newTime_video;
1066

    
1067
                                                        //i can also sleep now instead of at the beginning of
1068
                                                        //the next frame because in this case we only have video
1069
                                                        //frames, hence it would immediately be the next thing to do
1070
                                                        if(sleep > 0) {
1071
                                                                dcprintf(DEBUG_TIMESTAMPING,"\n\tREADLOOP: going to sleep for %ld microseconds\n", sleep);
1072
                                                                usleep(sleep);
1073
                                                        }
1074

    
1075
                                                }
1076
                                        }
1077
                                }
1078
                        }
1079
                } else if(packet.stream_index==audioStream) {
1080
                        if(sleep > 0)
1081
                        {
1082
                                dcprintf(DEBUG_TIMESTAMPING, "\n\tREADLOOP: going to sleep for %ld microseconds\n", sleep);
1083
                                usleep(sleep);
1084
                        }
1085
                        
1086
                        audio_data_size = AVCODEC_MAX_AUDIO_FRAME_SIZE;
1087
                        //decode the audio packet into a raw audio source buffer
1088
                        if(avcodec_decode_audio3(aCodecCtx, samples, &audio_data_size, &packet)>0)
1089
                        {
1090
                                dcprintf(DEBUG_AUDIO_FRAMES, "\n-------AUDIO FRAME\n");
1091
                                dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO: newTimeaudioSTART : %lf\n", (double)(packet.pts)*av_q2d(pFormatCtx->streams[audioStream]->time_base));
1092
                                if(audio_data_size>0) {
1093
                                        dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO: datasizeaudio:%d\n", audio_data_size);
1094
                                        /* if a frame has been decoded, output it */
1095
                                        //fwrite(samples, 1, audio_data_size, outfileaudio);
1096
                                }
1097
                                else {
1098
                                        av_free_packet(&packet);
1099
                                        continue;
1100
                                }
1101
        
1102
                                audio_frame_size = avcodec_encode_audio(aCodecCtxEnc, audio_outbuf, audio_data_size, samples);
1103
                                if(audio_frame_size <= 0) {
1104
                                        av_free_packet(&packet);
1105
                                        continue;
1106
                                }
1107
                                
1108
                                frame->number = contFrameAudio;
1109

    
1110
                                if(frame->number==0) {
1111
                                        if(packet.dts==AV_NOPTS_VALUE) {
1112
                                                av_free_packet(&packet);
1113
                                                continue;
1114
                                        }
1115
                                        last_pkt_dts_audio = packet.dts;
1116
                                        newTime = 0;
1117
                                }
1118
                                else {
1119
                                        if(packet.dts!=AV_NOPTS_VALUE) {
1120
                                                delta_audio = packet.dts-last_pkt_dts_audio;
1121
                                                last_pkt_dts_audio = packet.dts;
1122
                                        }
1123
                                        else if(delta_audio==0) {
1124
                                                av_free_packet(&packet);
1125
                                                continue;
1126
                                        }
1127
                                }
1128
                                dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO: original codec frame number %d vs. encoded %d vs. packed %d\n", aCodecCtx->frame_number, aCodecCtxEnc->frame_number, frame->number);
1129
                                //use pts if dts is invalid
1130
                                if(packet.dts!=AV_NOPTS_VALUE)
1131
                                        target_pts = packet.dts;
1132
                                else if(packet.pts!=AV_NOPTS_VALUE) {
1133
                                        target_pts = packet.pts;
1134
                                } else  {
1135
                                        av_free_packet(&packet);
1136
                                        continue;
1137
                                }
1138

    
1139
                                if(offset_av)
1140
                                {
1141
                                        if(FirstTimeAudio && packet.dts>0) {
1142
                                                ptsaudio1 = packet.dts;
1143
                                                FirstTimeAudio = 0;
1144
                                                dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO: SET PTS BASE OFFSET %"PRId64"\n", ptsaudio1);
1145
                                        }
1146
                                }
1147
                                else //we want to compensate audio and video offset for this source
1148
                                {
1149
                                        if(FirstTimeAudio && packet.dts>0) {
1150
                                                //maintain the offset between audio pts and video pts
1151
                                                //because in case of live source they have the same numbering
1152
                                                if(ptsvideo1 > 0) //if we have already seen some video frames...
1153
                                                        ptsaudio1 = ptsvideo1;
1154
                                                else
1155
                                                        ptsaudio1 = packet.dts;
1156
                                                FirstTimeAudio = 0;
1157
                                                dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO LIVE: SET PTS BASE OFFSET %"PRId64"\n", ptsaudio1);
1158
                                        }
1159
                                }
1160
                                //compute the new audio timestamps in milliseconds
1161
                                if(frame->number>0) {
1162
                                        newTime = ((target_pts-ptsaudio1)*1000.0*((double)av_q2d(pFormatCtx->streams[audioStream]->time_base)));//*(double)delta_audio;
1163
                                        // store timestamp in useconds for next frame sleep
1164
                                        newTime_audio = newTime*1000;
1165
                                }
1166
                                dcprintf(DEBUG_TIMESTAMPING, "AUDIO: NEWTIMESTAMP %lld\n", newTime);
1167
                                if(newTime<0) {
1168
                                        dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO: SKIPPING FRAME\n");
1169
                                        newtime_anomalies_counter++;
1170
                                        dcprintf(DEBUG_ANOMALIES, "READLOOP: NEWTIME negative audio timestamp anomaly detected number %d\n", newtime_anomalies_counter);
1171
                                        av_free_packet(&packet);
1172
                                        continue; //SKIP THIS FRAME, bad timestamp
1173
                                }
1174

    
1175
                                frame->timestamp.tv_sec = (unsigned int)(newTime + delay_audio)/1000;
1176
                                frame->timestamp.tv_usec = (newTime + delay_audio)%1000;
1177
                                frame->size = audio_frame_size;
1178
                                frame->type = 5; // 5 is audio type
1179
                                dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO: pts %"PRId64" duration %d timebase %d %d dts %"PRId64"\n", packet.pts, packet.duration, pFormatCtx->streams[audioStream]->time_base.num, pFormatCtx->streams[audioStream]->time_base.den, packet.dts);
1180
                                dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO: timestamp sec:%ld usec:%ld\n", (long)frame->timestamp.tv_sec, (long)frame->timestamp.tv_usec);
1181
                                dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO: deltaaudio %"PRId64"\n", delta_audio);        
1182
                                contFrameAudio++;
1183

    
1184
                                if(update_chunk(chunkaudio, frame, audio_outbuf) == -1) {
1185
                                        fprintf(stderr, "AUDIO: unable to update chunk %d. Exiting.\n", chunkaudio->seq);
1186
                                        exit(-1);
1187
                                }
1188
                                //set priority
1189
                                chunkaudio->priority = 1;
1190

    
1191
                                if(chunkFilled(chunkaudio, AUDIO_CHUNK)) {
1192
                                        // is chunk filled using current strategy?
1193
                                        //SAVE ON FILE
1194
                                        //saveChunkOnFile(chunkaudio);
1195
                                        //Send the chunk to an external transport/player
1196
                                        sendChunk(outstream[0].output, chunkaudio);
1197
                                        sendChunk(outstream[1].output, chunkaudio);
1198
                                        dctprintf(DEBUG_CHUNKER, "AUDIO: just sent chunk audio %d\n", chunkaudio->seq);
1199
                                        chunkaudio->seq = 0; //signal that we need an increase
1200
                                        //initChunk(chunkaudio, &seq_current_chunk);
1201
                                }
1202

    
1203
                                //we have an audio track, so we compute timings and determine
1204
                                //how much time we have to sleep at next audio frame taking
1205
                                //also into account how much time was needed to encode the
1206
                                //video frames
1207
                                //all this in case the video source is not live, i.e. not self-timing
1208
                                if(!live_source)
1209
                                {
1210
                                        if(newTime_prev != 0)
1211
                                        {
1212
                                                long long maxDelay = newTime_audio - newTime_prev;
1213

    
1214
                                                gettimeofday(&now_tv, NULL);
1215
                                                long long usec = (now_tv.tv_sec-lastAudioSent.tv_sec)*1000000;
1216
                                                usec+=(now_tv.tv_usec-lastAudioSent.tv_usec);
1217

    
1218
                                                if(usec > maxAudioInterval)
1219
                                                        maxAudioInterval = usec;
1220

    
1221
                                                lateTime -= (maxDelay - usec);
1222
                                                dcprintf(DEBUG_TIMESTAMPING,"\tmaxDelay=%ld, maxAudioInterval=%ld\n", ((long)maxDelay), ((long) maxAudioInterval));
1223
                                                dcprintf(DEBUG_TIMESTAMPING,"\tlast audio frame interval=%ld; lateTime=%ld\n", ((long)usec), ((long)lateTime));
1224

    
1225
                                                if((lateTime+maxAudioInterval) < 0)
1226
                                                        sleep = (lateTime+maxAudioInterval)*-1;
1227
                                                else
1228
                                                        sleep = 0;
1229
                                        }
1230
                                        else
1231
                                                sleep = 0;
1232

    
1233
                                        newTime_prev = newTime_audio;
1234
                                        gettimeofday(&lastAudioSent, NULL);
1235
                                }
1236
                        }
1237
                }
1238
                dcprintf(DEBUG_CHUNKER,"Free the packet that was allocated by av_read_frame\n");
1239
                av_free_packet(&packet);
1240
        }
1241
        
1242
        if(videotrace)
1243
                fclose(videotrace);
1244
        if(psnrtrace)
1245
                fclose(psnrtrace);
1246

    
1247
close:
1248
        if(outstream[0].chunk->seq != 0 && outstream[0].chunk->frames_num>0) {
1249
                //SAVE ON FILE
1250
                //saveChunkOnFile(chunk);
1251
                //Send the chunk to an external transport/player
1252
                sendChunk(outstream[0].output, outstream[0].chunk);
1253
                dcprintf(DEBUG_CHUNKER, "CHUNKER: SENDING LAST VIDEO CHUNK\n");
1254
                outstream[0].chunk->seq = 0; //signal that we need an increase just in case we will restart
1255
        }
1256
        if(chunkaudio->seq != 0 && chunkaudio->frames_num>0) {
1257
                //SAVE ON FILE     
1258
                //saveChunkOnFile(chunkaudio);
1259
                //Send the chunk via http to an external transport/player
1260
                sendChunk(outstream[0].output, chunkaudio);
1261
                dcprintf(DEBUG_CHUNKER, "CHUNKER: SENDING LAST AUDIO CHUNK\n");
1262
                chunkaudio->seq = 0; //signal that we need an increase just in case we will restart
1263
        }
1264

    
1265
#ifdef HTTPIO
1266
        /* finalize the HTTP chunk pusher */
1267
        finalizeChunkPusher();
1268
#endif
1269

    
1270
        free(outstream[0].chunk);
1271
        free(chunkaudio);
1272
        free(frame);
1273
        av_free(video_outbuf);
1274
        av_free(audio_outbuf);
1275
        free(cmeta);
1276

    
1277
        // Free the YUV frame
1278
        av_free(pFrame1);
1279
        av_free(samples);
1280
  
1281
        // Close the codec
1282
        avcodec_close(pCodecCtx);
1283
        avcodec_close(outstream[1].pCodecCtxEnc);
1284

    
1285
        if(audioStream!=-1) {
1286
                avcodec_close(aCodecCtx);
1287
                avcodec_close(aCodecCtxEnc);
1288
        }
1289
  
1290
        // Close the video file
1291
        av_close_input_file(pFormatCtx);
1292

    
1293
        if(LOOP_MODE) {
1294
                //we want video to continue, but the av_read_frame stopped
1295
                //lets wait a 5 secs, and cycle in again
1296
                usleep(5000000);
1297
                dcprintf(DEBUG_CHUNKER, "CHUNKER: WAITING 5 secs FOR LIVE SOURCE TO SKIP ERRORS AND RESTARTING\n");
1298
                videoStream = -1;
1299
                audioStream = -1;
1300
                FirstTimeAudio=1;
1301
                FirstTimeVideo=1;
1302
                pts_anomalies_counter=0;
1303
                newtime_anomalies_counter=0;
1304
                newTime=0;
1305
                newTime_audio=0;
1306
                newTime_prev=0;
1307
                ptsvideo1=0;
1308
                ptsaudio1=0;
1309
                last_pkt_dts=0;
1310
                delta_video=0;
1311
                delta_audio=0;
1312
                last_pkt_dts_audio=0;
1313
                target_pts=0;
1314
                i=0;
1315
                //~ contFrameVideo = 0;
1316
                //~ contFrameAudio = 1;
1317
                
1318
#ifdef YUV_RECORD_ENABLED
1319
                if(ChunkerStreamerTestMode)
1320
                {
1321
                        video_record_count++;
1322
                        //~ savedVideoFrames = 0;
1323
                        
1324
                        //~ char tmp_filename[255];
1325
                        //~ sprintf(tmp_filename, "yuv_data/out_%d.yuv", video_record_count);
1326
                        //~ FILE *pFile=fopen(tmp_filename, "w");
1327
                        //~ if(pFile!=NULL)
1328
                                //~ fclose(pFile);
1329
                }
1330
#endif
1331

    
1332
                goto restart;
1333
        }
1334

    
1335
#ifdef TCPIO
1336
        finalizeTCPChunkPusher(outstream[0].output);
1337
        finalizeTCPChunkPusher(outstream[1].output);
1338
#endif
1339

    
1340
#ifdef USE_AVFILTER
1341
        close_filters();
1342
#endif
1343

    
1344
        return 0;
1345
}
1346

    
1347
int update_chunk(ExternalChunk *chunk, Frame *frame, uint8_t *outbuf) {
1348
        //the frame.h gets encoded into 5 slots of 32bits (3 ints plus 2 more for the timeval struct
1349
        static int sizeFrameHeader = 5*sizeof(int32_t);
1350

    
1351
        //moving temp pointer to encode Frame on the wire
1352
        uint8_t *tempdata = NULL;
1353

    
1354
        if(chunk->seq == 0) {
1355
                initChunk(chunk, &seq_current_chunk);
1356
        }
1357
        //add frame priority to chunk priority (to be normalized later on)
1358
        chunk->priority += frame->type + 1; // I:2, P:3, B:4
1359

    
1360
        //HINT on malloc
1361
        chunk->data = (uint8_t *)realloc(chunk->data, sizeof(uint8_t)*(chunk->payload_len + frame->size + sizeFrameHeader));
1362
        if(!chunk->data)  {
1363
                fprintf(stderr, "Memory error in chunk!!!\n");
1364
                return -1;
1365
        }
1366
        chunk->frames_num++; // number of frames in the current chunk
1367

    
1368
/*
1369
        //package the Frame header
1370
        tempdata = chunk->data+chunk->payload_len;
1371
        *((int32_t *)tempdata) = frame->number;
1372
        tempdata+=sizeof(int32_t);
1373
        *((struct timeval *)tempdata) = frame->timestamp;
1374
        tempdata+=sizeof(struct timeval);
1375
        *((int32_t *)tempdata) = frame->size;
1376
        tempdata+=sizeof(int32_t);
1377
        *((int32_t *)tempdata) = frame->type;
1378
        tempdata+=sizeof(int32_t);
1379
*/
1380
        //package the Frame header: network order and platform independent
1381
        tempdata = chunk->data+chunk->payload_len;
1382
        bit32_encoded_push(frame->number, tempdata);
1383
        bit32_encoded_push(frame->timestamp.tv_sec, tempdata + CHUNK_TRANSCODING_INT_SIZE);
1384
        bit32_encoded_push(frame->timestamp.tv_usec, tempdata + CHUNK_TRANSCODING_INT_SIZE*2);
1385
        bit32_encoded_push(frame->size, tempdata + CHUNK_TRANSCODING_INT_SIZE*3);
1386
        bit32_encoded_push(frame->type, tempdata + CHUNK_TRANSCODING_INT_SIZE*4);
1387

    
1388
         //insert the new frame data
1389
        memcpy(chunk->data + chunk->payload_len + sizeFrameHeader, outbuf, frame->size);
1390
        chunk->payload_len += frame->size + sizeFrameHeader; // update payload length
1391
        //chunk lenght is updated just prior to pushing it out because
1392
        //the chunk header len is better calculated there
1393
        //chunk->len = sizeChunkHeader + chunk->payload_len; // update overall length
1394

    
1395
        //update timestamps
1396
        if(((int)frame->timestamp.tv_sec < (int)chunk->start_time.tv_sec) || ((int)frame->timestamp.tv_sec==(int)chunk->start_time.tv_sec && (int)frame->timestamp.tv_usec < (int)chunk->start_time.tv_usec) || (int)chunk->start_time.tv_sec==-1) {
1397
                                                chunk->start_time.tv_sec = frame->timestamp.tv_sec;
1398
                                                chunk->start_time.tv_usec = frame->timestamp.tv_usec;
1399
        }
1400
        
1401
        if(((int)frame->timestamp.tv_sec > (int)chunk->end_time.tv_sec) || ((int)frame->timestamp.tv_sec==(int)chunk->end_time.tv_sec && (int)frame->timestamp.tv_usec > (int)chunk->end_time.tv_usec) || (int)chunk->end_time.tv_sec==-1) {
1402
                                                chunk->end_time.tv_sec = frame->timestamp.tv_sec;
1403
                                                chunk->end_time.tv_usec = frame->timestamp.tv_usec;
1404
        }
1405
        return 0;
1406
}
1407

    
1408
void SaveFrame(AVFrame *pFrame, int width, int height)
1409
{
1410
        FILE *pFile;
1411
        int  y;
1412

    
1413
         // Open file
1414
        char tmp_filename[255];
1415
        sprintf(tmp_filename, "yuv_data/streamer_out.yuv");
1416
        pFile=fopen(tmp_filename, "ab");
1417
        if(pFile==NULL)
1418
                return;
1419

    
1420
        // Write header
1421
        //fprintf(pFile, "P5\n%d %d\n255\n", width, height);
1422
  
1423
        // Write Y data
1424
        for(y=0; y<height; y++)
1425
                  if(fwrite(pFrame->data[0]+y*pFrame->linesize[0], 1, width, pFile) != width)
1426
                {
1427
                        printf("errno = %d\n", errno);
1428
                        exit(1);
1429
                }
1430
        // Write U data
1431
        for(y=0; y<height/2; y++)
1432
                  if(fwrite(pFrame->data[1]+y*pFrame->linesize[1], 1, width/2, pFile) != width/2)
1433
                  {
1434
                        printf("errno = %d\n", errno);
1435
                        exit(1);
1436
                }
1437
        // Write V data
1438
        for(y=0; y<height/2; y++)
1439
                  if(fwrite(pFrame->data[2]+y*pFrame->linesize[2], 1, width/2, pFile) != width/2)
1440
                  {
1441
                        printf("errno = %d\n", errno);
1442
                        exit(1);
1443
                }
1444
  
1445
        // Close file
1446
        fclose(pFile);
1447
}
1448

    
1449
void SaveEncodedFrame(Frame* frame, uint8_t *video_outbuf)
1450
{
1451
        static FILE* pFile = NULL;
1452
        
1453
        pFile=fopen("yuv_data/streamer_out.mpeg4", "ab");
1454
        fwrite(frame, sizeof(Frame), 1, pFile);
1455
        fwrite(video_outbuf, frame->size, 1, pFile);
1456
        fclose(pFile);
1457
}