Statistics
| Branch: | Revision:

chunker-player / chunker_streamer / chunker_streamer.c @ 9cfd1b81

History | View | Annotate | Download (43.4 KB)

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

    
8
#include "chunker_streamer.h"
9
#include <signal.h>
10
#include <math.h>
11
#include <getopt.h>
12
#include <libswscale/swscale.h>
13

    
14
#define STREAMER_MAX(a,b) ((a>b)?(a):(b))
15
#define STREAMER_MIN(a,b) ((a<b)?(a):(b))
16

    
17
//#define DEBUG_AUDIO_FRAMES
18
//#define DEBUG_VIDEO_FRAMES
19
//#define DEBUG_CHUNKER
20
#define DEBUG_ANOMALIES
21
//~ #define DEBUG_TIMESTAMPING
22
#define GET_PSNR(x) ((x==0) ? 0 : (-10.0*log(x)/log(10)))
23

    
24
ChunkerMetadata *cmeta = NULL;
25
int seq_current_chunk = 1; //chunk numbering starts from 1; HINT do i need more bytes?
26

    
27
#define AUDIO_CHUNK 0
28
#define VIDEO_CHUNK 1
29

    
30
void SaveFrame(AVFrame *pFrame, int width, int height);
31
void SaveEncodedFrame(Frame* frame, uint8_t *video_outbuf);
32
int pushChunkTcp(ExternalChunk *echunk);
33
void initTCPPush(char* ip, int port);
34
int update_chunk(ExternalChunk *chunk, Frame *frame, uint8_t *outbuf);
35
void finalizeTCPChunkPusher();
36
void bit32_encoded_push(uint32_t v, uint8_t *p);
37

    
38
int video_record_count = 0;
39
int savedVideoFrames = 0;
40
long int firstSavedVideoFrame = 0;
41
int ChunkerStreamerTestMode = 0;
42

    
43
int pts_anomaly_threshold = -1;
44
int newtime_anomaly_threshold = -1;
45
bool timebank = false;
46
char *outside_world_url = NULL;
47

    
48
int gop_size = 25;
49
int max_b_frames = 3;
50
bool vcopy = false;
51

    
52
long delay_audio = 0; //delay audio by x millisec
53

    
54
// Constant number of frames per chunk
55
int chunkFilledFramesStrategy(ExternalChunk *echunk, int chunkType)
56
{
57
#ifdef DEBUG_CHUNKER
58
        fprintf(stderr, "CHUNKER: check if frames num %d == %d in chunk %d\n", echunk->frames_num, cmeta->framesPerChunk[chunkType], echunk->seq);
59
#endif
60
        if(echunk->frames_num == cmeta->framesPerChunk[chunkType])
61
                return 1;
62

    
63
        return 0;
64
}
65

    
66
// Constant size. Note that for now each chunk will have a size just greater or equal than the required value
67
// It can be considered as constant size.
68
int chunkFilledSizeStrategy(ExternalChunk *echunk, int chunkType)
69
{
70
#ifdef DEBUG_CHUNKER
71
        fprintf(stderr, "CHUNKER: check if chunk size %d >= %d in chunk %d\n", echunk->payload_len, cmeta->targetChunkSize, echunk->seq);
72
#endif
73
        if(echunk->payload_len >= cmeta->targetChunkSize)
74
                return 1;
75
        
76
        return 0;
77
}
78

    
79
// Performace optimization.
80
// The chunkFilled function has been splitted into two functions (one for each strategy).
81
// Instead of continuously check the strategy flag (which is constant),
82
// 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)
83
int (*chunkFilled)(ExternalChunk *echunk, int chunkType);
84

    
85
void initChunk(ExternalChunk *chunk, int *seq_num) {
86
        chunk->seq = (*seq_num)++;
87
        chunk->frames_num = 0;
88
        chunk->payload_len = 0;
89
        chunk->len=0;
90
  if(chunk->data != NULL)
91
    free(chunk->data);
92
        chunk->data = NULL;
93
        chunk->start_time.tv_sec = -1;
94
        chunk->start_time.tv_usec = -1;
95
        chunk->end_time.tv_sec = -1;
96
        chunk->end_time.tv_usec = -1;
97
        chunk->priority = 0;
98
        chunk->category = 0;
99
        chunk->_refcnt = 0;
100
}
101

    
102
int quit = 0;
103

    
104
void sigproc()
105
{
106
        printf("you have pressed ctrl-c, terminating...\n");
107
        quit = 1;
108
}
109

    
110
static void print_usage(int argc, char *argv[])
111
{
112
  fprintf (stderr,
113
    "\nUsage:%s [options]\n"
114
    "\n"
115
    "Mandatory options:\n"
116
    "\t[-i input file]\n"
117
    "\t[-a audio bitrate]\n"
118
    "\t[-v video bitrate]\n\n"
119
    "Other options:\n"
120
    "\t[-F output] (overrides config file)\n"
121
    "\t[-A audioencoder]\n"
122
    "\t[-V videoencoder]\n"
123
    "\t[-s WxH]: force video size.\n"
124
    "\t[-l]: this is a live stream.\n"
125
    "\t[-o]: adjust A/V frame timestamps (deafault off, use it only with flawed containers)\n"
126
    "\t[-p]: pts anomaly threshold (default: -1=off).\n"
127
    "\t[-q]: sync anomaly threshold ((default: -1=off).\n"
128
    "\t[-t]: QoE test mode\n\n"
129
    "Codec options:\n"
130
    "\t[-g GOP]: gop size\n"
131
    "\t[-b frames]: max number of consecutive b frames\n"
132
    "\t[-x extas]: extra video codec options (e.g. -x me_method=hex,flags2=+dct8x8+wpred+bpyrami+mixed_refs)\n"
133
    "\n"
134
    "=======================================================\n", argv[0]
135
    );
136
  }
137

    
138
int sendChunk(ExternalChunk *chunk) {
139
#ifdef HTTPIO
140
                                                return pushChunkHttp(chunk, outside_world_url);
141
#endif
142
#ifdef TCPIO
143
                                                return pushChunkTcp(chunk);
144
#endif
145
#ifdef UDPIO
146
                                                return pushChunkUDP(chunk);
147
#endif
148
}
149

    
150
int main(int argc, char *argv[]) {
151
        signal(SIGINT, sigproc);
152
        
153
        int i=0;
154

    
155
        //output variables
156
        uint8_t *video_outbuf = NULL;
157
        int video_outbuf_size, video_frame_size;
158
        uint8_t *audio_outbuf = NULL;
159
        int audio_outbuf_size, audio_frame_size;
160
        int audio_data_size;
161

    
162
        //numeric identifiers of input streams
163
        int videoStream = -1;
164
        int audioStream = -1;
165

    
166
//        int len1;
167
        int frameFinished;
168
        //frame sequential counters
169
        int contFrameAudio=1, contFrameVideo=0;
170
//        int numBytes;
171

    
172
        //command line parameters
173
        int audio_bitrate = -1;
174
        int video_bitrate = -1;
175
        char *audio_codec = "mp2";
176
        char *video_codec = "mpeg4";
177
        char *codec_options = "";
178
        int live_source = 0; //tells to sleep before reading next frame in not live (i.e. file)
179
        int offset_av = 0; //tells to compensate for offset between audio and video in the file
180
        
181
        //a raw buffer for decoded uncompressed audio samples
182
        int16_t *samples = NULL;
183
        //a raw uncompressed video picture
184
        AVFrame *pFrame = NULL;
185
        AVFrame *scaledFrame = NULL;
186

    
187
        AVFormatContext *pFormatCtx;
188
        AVCodecContext  *pCodecCtx = NULL ,*pCodecCtxEnc = NULL ,*aCodecCtxEnc = NULL ,*aCodecCtx = NULL;
189
        AVCodec         *pCodec = NULL ,*pCodecEnc = NULL ,*aCodec = NULL ,*aCodecEnc = NULL;
190
        AVPacket         packet;
191

    
192
        //stuff needed to compute the right timestamps
193
        short int FirstTimeAudio=1, FirstTimeVideo=1;
194
        short int pts_anomalies_counter=0;
195
        short int newtime_anomalies_counter=0;
196
        long long newTime=0, newTime_audio=0, newTime_video=0, newTime_prev=0;
197
        struct timeval lastAudioSent = {0, 0};
198
        int64_t ptsvideo1=0;
199
        int64_t ptsaudio1=0;
200
        int64_t last_pkt_dts=0, delta_video=0, delta_audio=0, last_pkt_dts_audio=0, target_pts=0;
201

    
202
        //Napa-Wine specific Frame and Chunk structures for transport
203
        Frame *frame = NULL;
204
        ExternalChunk *chunk = NULL;
205
        ExternalChunk *chunkaudio = NULL;
206
        
207
        char av_input[1024];
208
        int dest_width = -1;
209
        int dest_height = -1;
210
        
211
        static struct option long_options[] =
212
        {
213
                /* These options set a flag. */
214
                {"long_option", required_argument, 0, 0},
215
                {0, 0, 0, 0}
216
        };
217
        /* `getopt_long' stores the option index here. */
218
        int option_index = 0, c;
219
        int mandatories = 0;
220
        while ((c = getopt_long (argc, argv, "i:a:v:A:V:s:lop:q:tF:g:b:d:x:", long_options, &option_index)) != -1)
221
        {
222
                switch (c) {
223
                        case 0: //for long options
224
                                break;
225
                        case 'i':
226
                                sprintf(av_input, "%s", optarg);
227
                                mandatories++;
228
                                break;
229
                        case 'a':
230
                                sscanf(optarg, "%d", &audio_bitrate);
231
                                mandatories++;
232
                                break;
233
                        case 'v':
234
                                sscanf(optarg, "%d", &video_bitrate);
235
                                mandatories++;
236
                                break;
237
                        case 'A':
238
                                audio_codec = strdup(optarg);
239
                                break;
240
                        case 'V':
241
                                video_codec = strdup(optarg);
242
                                break;
243
                        case 's':
244
                                sscanf(optarg, "%dx%d", &dest_width, &dest_height);
245
                                break;
246
                        case 'l':
247
                                live_source = 1;
248
                                break;
249
                        case 'o':
250
                                offset_av = 1;
251
                                break;
252
                        case 't':
253
                                ChunkerStreamerTestMode = 1;
254
                                break;
255
                        case 'p':
256
                                sscanf(optarg, "%d", &pts_anomaly_threshold);
257
                                break;
258
                        case 'q':
259
                                sscanf(optarg, "%d", &newtime_anomaly_threshold);
260
                                break;
261
                        case 'F':
262
                                outside_world_url = strdup(optarg);
263
                                break;
264
                        case 'g':
265
                                sscanf(optarg, "%d", &gop_size);
266
                                break;
267
                        case 'b':
268
                                sscanf(optarg, "%d", &max_b_frames);
269
                                break;
270
                        case 'd':
271
                                sscanf(optarg, "%d", &delay_audio);
272
                                break;
273
                        case 'x':
274
                                codec_options = strdup(optarg);
275
                                break;
276
                        default:
277
                                print_usage(argc, argv);
278
                                return -1;
279
                }
280
        }
281
        
282
        if(mandatories < 3) 
283
        {
284
                print_usage(argc, argv);
285
                return -1;
286
        }
287

    
288
#ifdef YUV_RECORD_ENABLED
289
        if(ChunkerStreamerTestMode)
290
        {
291
                DELETE_DIR("yuv_data");
292
                CREATE_DIR("yuv_data");
293
                //FILE* pFile=fopen("yuv_data/streamer_out.yuv", "w");
294
                //fclose(pFile);
295
        }
296
#endif
297

    
298
restart:
299
        // read the configuration file
300
        cmeta = chunkerInit();
301
        if (!outside_world_url) {
302
                outside_world_url = strdup(cmeta->outside_world_url);
303
        }
304
        switch(cmeta->strategy)
305
        {
306
                case 1:
307
                        chunkFilled = chunkFilledSizeStrategy;
308
                        break;
309
                default:
310
                        chunkFilled = chunkFilledFramesStrategy;
311
        }
312
                
313
        if(live_source)
314
                fprintf(stderr, "INIT: Using LIVE SOURCE TimeStamps\n");
315
        if(offset_av)
316
                fprintf(stderr, "INIT: Compensating AV OFFSET in file\n");
317

    
318
        // Register all formats and codecs
319
        av_register_all();
320

    
321
        // Open input file
322
        if(av_open_input_file(&pFormatCtx, av_input, NULL, 0, NULL) != 0) {
323
                fprintf(stdout, "INIT: Couldn't open video file. Exiting.\n");
324
                exit(-1);
325
        }
326

    
327
        // Retrieve stream information
328
        if(av_find_stream_info(pFormatCtx) < 0) {
329
                fprintf(stdout, "INIT: Couldn't find stream information. Exiting.\n");
330
                exit(-1);
331
        }
332

    
333
        // Dump information about file onto standard error
334
        dump_format(pFormatCtx, 0, av_input, 0);
335

    
336
        // Find the video and audio stream numbers
337
        for(i=0; i<pFormatCtx->nb_streams; i++) {
338
                if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_VIDEO && videoStream<0) {
339
                        videoStream=i;
340
                }
341
                if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_AUDIO && audioStream<0) {
342
                        audioStream=i;
343
                }
344
        }
345
        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, pFormatCtx->streams[videoStream]->duration);
346

    
347
        fprintf(stderr, "INIT: Video stream has id : %d\n",videoStream);
348
        fprintf(stderr, "INIT: Audio stream has id : %d\n",audioStream);
349

    
350
        if(videoStream==-1 && audioStream==-1) {
351
                fprintf(stdout, "INIT: Didn't find audio and video streams. Exiting.\n");
352
                exit(-1);
353
        }
354

    
355
        // Get a pointer to the codec context for the input video stream
356
        pCodecCtx=pFormatCtx->streams[videoStream]->codec;
357
        pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
358
        //extract W and H
359
        fprintf(stderr, "INIT: Width:%d Height:%d\n", pCodecCtx->width, pCodecCtx->height);
360

    
361
        // Get a pointer to the codec context for the input audio stream
362
        if(audioStream != -1) {
363
                aCodecCtx=pFormatCtx->streams[audioStream]->codec;
364
                fprintf(stderr, "INIT: AUDIO Codecid: %d channels %d samplerate %d\n", aCodecCtx->codec_id, aCodecCtx->channels, aCodecCtx->sample_rate);
365
        }
366

    
367
        // Figure out size
368
        dest_width = (dest_width > 0) ? dest_width : pCodecCtx->width;
369
        dest_height = (dest_height > 0) ? dest_height : pCodecCtx->height;
370

    
371
        //setup video output encoder
372
 if (strcmp(video_codec, "copy") == 0) {
373
        vcopy = true;
374
 } else {
375
        pCodecEnc = avcodec_find_encoder_by_name(video_codec);
376
        if (pCodecEnc) {
377
                fprintf(stderr, "INIT: Setting VIDEO codecID to: %d\n",pCodecEnc->id);
378
        } else {
379
                fprintf(stderr, "INIT: Unknown OUT VIDEO codec: %s!\n", video_codec);
380
                return -1; // Codec not found
381
        }
382

    
383
        pCodecCtxEnc=avcodec_alloc_context();
384
        pCodecCtxEnc->codec_type = CODEC_TYPE_VIDEO;
385
        pCodecCtxEnc->codec_id = pCodecEnc->id;
386

    
387
        pCodecCtxEnc->bit_rate = video_bitrate;
388
        //~ pCodecCtxEnc->qmin = 30;
389
        //~ pCodecCtxEnc->qmax = 30;
390
        //times 20 follows the defaults, was not needed in previous versions of libavcodec
391
        pCodecCtxEnc->bit_rate_tolerance = video_bitrate*20;
392
//        pCodecCtxEnc->crf = 20.0f;
393
        // resolution must be a multiple of two 
394
        pCodecCtxEnc->width = dest_width;
395
        pCodecCtxEnc->height = dest_height;
396
        // frames per second 
397
        //~ pCodecCtxEnc->time_base= pCodecCtx->time_base;//(AVRational){1,25};
398
        //printf("pCodecCtx->time_base=%d/%d\n", pCodecCtx->time_base.num, pCodecCtx->time_base.den);
399
        pCodecCtxEnc->time_base= pCodecCtx->time_base;//(AVRational){1,25};
400
        pCodecCtxEnc->gop_size = gop_size; // emit one intra frame every gop_size frames 
401
        pCodecCtxEnc->max_b_frames = max_b_frames;
402
        pCodecCtxEnc->pix_fmt = PIX_FMT_YUV420P;
403
        //pCodecCtxEnc->flags = CODEC_FLAG_PSNR;
404
        //~ pCodecCtxEnc->flags |= CODEC_FLAG_QSCALE;
405

    
406
        //some generic quality tuning
407
        pCodecCtxEnc->mb_decision = FF_MB_DECISION_RD;
408

    
409
  switch (pCodecEnc->id) {
410
    case CODEC_ID_H264 :
411
        // Fast Profile
412
        // libx264-fast.ffpreset preset 
413
        pCodecCtxEnc->coder_type = FF_CODER_TYPE_AC; // coder = 1 -> enable CABAC
414
        pCodecCtxEnc->flags |= CODEC_FLAG_LOOP_FILTER; // flags=+loop -> deblock
415
        pCodecCtxEnc->me_cmp|= 1; // cmp=+chroma, where CHROMA = 1
416
        pCodecCtxEnc->partitions |= X264_PART_I8X8|X264_PART_I4X4|X264_PART_P8X8|X264_PART_B8X8;        // partitions=+parti8x8+parti4x4+partp8x8+partb8x8
417
        pCodecCtxEnc->me_method=ME_HEX; // me_method=hex
418
        pCodecCtxEnc->me_subpel_quality = 6; // subq=7
419
        pCodecCtxEnc->me_range = 16; // me_range=16
420
        //pCodecCtxEnc->gop_size = 250; // g=250
421
        //pCodecCtxEnc->keyint_min = 25; // keyint_min=25
422
        pCodecCtxEnc->scenechange_threshold = 40; // sc_threshold=40
423
        pCodecCtxEnc->i_quant_factor = 0.71; // i_qfactor=0.71
424
        pCodecCtxEnc->b_frame_strategy = 1; // b_strategy=1
425
        pCodecCtxEnc->qcompress = 0.6; // qcomp=0.6
426
        pCodecCtxEnc->qmin = 10; // qmin=10
427
        pCodecCtxEnc->qmax = 51; // qmax=51
428
        pCodecCtxEnc->max_qdiff = 4; // qdiff=4
429
        //pCodecCtxEnc->max_b_frames = 3; // bf=3
430
        pCodecCtxEnc->refs = 2; // refs=3
431
        //pCodecCtxEnc->directpred = 1; // directpred=1
432
        pCodecCtxEnc->directpred = 3; // directpred=1 in preset -> "directpred", "direct mv prediction mode - 0 (none), 1 (spatial), 2 (temporal), 3 (auto)"
433
        //pCodecCtxEnc->trellis = 1; // trellis=1
434
        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
435
        pCodecCtxEnc->weighted_p_pred = 2; // wpredp=2
436

    
437
        // libx264-main.ffpreset preset
438
        //pCodecCtxEnc->flags2|=CODEC_FLAG2_8X8DCT;
439
        //pCodecCtxEnc->flags2^=CODEC_FLAG2_8X8DCT; // flags2=-dct8x8
440
        //pCodecCtxEnc->crf = 22;
441

    
442
#ifdef STREAMER_X264_USE_SSIM
443
        pCodecCtxEnc->flags2 |= CODEC_FLAG2_SSIM;
444
#endif
445

    
446
        //pCodecCtxEnc->weighted_p_pred=2; //maps wpredp=2; weighted prediction analysis method
447
        // pCodecCtxEnc->rc_min_rate = 0;
448
        // pCodecCtxEnc->rc_max_rate = video_bitrate*2;
449
        // pCodecCtxEnc->rc_buffer_size = 0;
450
        break;
451
    case CODEC_ID_MPEG4 :
452
        break;
453
    default:
454
        fprintf(stderr, "INIT: Unsupported OUT VIDEO codec: %s!\n", video_codec);
455
  }
456

    
457
  if ((av_set_options_string(pCodecCtxEnc, codec_options, "=", ",")) < 0) {
458
    fprintf(stderr, "Error parsing options string: '%s'\n", codec_options);
459
    exit(1);
460
  }
461

    
462
        fprintf(stderr, "INIT: VIDEO timebase OUT:%d %d IN: %d %d\n", pCodecCtxEnc->time_base.num, pCodecCtxEnc->time_base.den, pCodecCtx->time_base.num, pCodecCtx->time_base.den);
463
 }
464

    
465
        if(pCodec==NULL) {
466
                fprintf(stderr, "INIT: Unsupported IN VIDEO pcodec!\n");
467
                return -1; // Codec not found
468
        }
469
        if(!vcopy && pCodecEnc==NULL) {
470
                fprintf(stderr, "INIT: Unsupported OUT VIDEO pcodecenc!\n");
471
                return -1; // Codec not found
472
        }
473
        if(avcodec_open(pCodecCtx, pCodec)<0) {
474
                fprintf(stderr, "INIT: could not open IN VIDEO codec\n");
475
                return -1; // Could not open codec
476
        }
477
        if(!vcopy && avcodec_open(pCodecCtxEnc, pCodecEnc)<0) {
478
                fprintf(stderr, "INIT: could not open OUT VIDEO codecEnc\n");
479
                return -1; // Could not open codec
480
        }
481
        if(audioStream!=-1) {
482
                //setup audio output encoder
483
                aCodecCtxEnc = avcodec_alloc_context();
484
                aCodecCtxEnc->bit_rate = audio_bitrate; //256000
485
                aCodecCtxEnc->sample_fmt = SAMPLE_FMT_S16;
486
                aCodecCtxEnc->sample_rate = aCodecCtx->sample_rate;
487
                aCodecCtxEnc->channels = aCodecCtx->channels;
488
                fprintf(stderr, "INIT: AUDIO bitrate OUT:%d sample_rate:%d channels:%d\n", aCodecCtxEnc->bit_rate, aCodecCtxEnc->sample_rate, aCodecCtxEnc->channels);
489

    
490
                // Find the decoder for the audio stream
491
                aCodec = avcodec_find_decoder(aCodecCtx->codec_id);
492
                aCodecEnc = avcodec_find_encoder_by_name(audio_codec);
493
                if(aCodec==NULL) {
494
                        fprintf(stderr,"INIT: Unsupported acodec!\n");
495
                        return -1;
496
                }
497
                if(aCodecEnc==NULL) {
498
                        fprintf(stderr,"INIT: Unsupported acodecEnc!\n");
499
                        return -1;
500
                }
501
        
502
                if(avcodec_open(aCodecCtx, aCodec)<0) {
503
                        fprintf(stderr, "INIT: could not open IN AUDIO codec\n");
504
                        return -1; // Could not open codec
505
                }
506
                if(avcodec_open(aCodecCtxEnc, aCodecEnc)<0) {
507
                        fprintf(stderr, "INIT: could not open OUT AUDIO codec\n");
508
                        return -1; // Could not open codec
509
                }
510
        }
511
        else {
512
                fprintf(stderr,"INIT: NO AUDIO TRACK IN INPUT FILE\n");
513
        }
514

    
515
        // Allocate audio in and out buffers
516
        samples = (int16_t *)av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
517
        if(samples == NULL) {
518
                fprintf(stderr, "INIT: Memory error alloc audio samples!!!\n");
519
                return -1;
520
        }
521
        audio_outbuf_size = STREAMER_MAX_AUDIO_BUFFER_SIZE;
522
        audio_outbuf = av_malloc(audio_outbuf_size);
523
        if(audio_outbuf == NULL) {
524
                fprintf(stderr, "INIT: Memory error alloc audio_outbuf!!!\n");
525
                return -1;
526
        }
527

    
528
        // Allocate video in frame and out buffer
529
        pFrame=avcodec_alloc_frame();
530
        scaledFrame=avcodec_alloc_frame();
531
        if(pFrame==NULL || scaledFrame == NULL) {
532
                fprintf(stderr, "INIT: Memory error alloc video frame!!!\n");
533
                return -1;
534
        }
535
        video_outbuf_size = STREAMER_MAX_VIDEO_BUFFER_SIZE;
536
        video_outbuf = av_malloc(video_outbuf_size);
537
        int scaledFrame_buf_size = avpicture_get_size( PIX_FMT_YUV420P, dest_width, dest_height);
538
        uint8_t* scaledFrame_buffer = (uint8_t *) av_malloc( scaledFrame_buf_size * sizeof( uint8_t ) );
539
        avpicture_fill( (AVPicture*) scaledFrame, scaledFrame_buffer, PIX_FMT_YUV420P, dest_width, dest_height);
540
        if(!video_outbuf || !scaledFrame_buffer) {
541
                fprintf(stderr, "INIT: Memory error alloc video_outbuf!!!\n");
542
                return -1;
543
        }
544

    
545
        //allocate Napa-Wine transport
546
        frame = (Frame *)malloc(sizeof(Frame));
547
        if(!frame) {
548
                fprintf(stderr, "INIT: Memory error alloc Frame!!!\n");
549
                return -1;
550
        }
551
        //create an empty first video chunk
552
        chunk = (ExternalChunk *)malloc(sizeof(ExternalChunk));
553
        if(!chunk) {
554
                fprintf(stderr, "INIT: Memory error alloc chunk!!!\n");
555
                return -1;
556
        }
557
        chunk->data = NULL;
558
        chunk->seq = 0;
559
        //initChunk(chunk, &seq_current_chunk); if i init them now i get out of sequence
560
#ifdef DEBUG_CHUNKER
561
        fprintf(stderr, "INIT: chunk video %d\n", chunk->seq);
562
#endif
563
        //create empty first audio chunk
564
        chunkaudio = (ExternalChunk *)malloc(sizeof(ExternalChunk));
565
        if(!chunkaudio) {
566
                fprintf(stderr, "INIT: Memory error alloc chunkaudio!!!\n");
567
                return -1;
568
        }
569
  chunkaudio->data=NULL;
570
        chunkaudio->seq = 0;
571
        //initChunk(chunkaudio, &seq_current_chunk);
572
#ifdef DEBUG_CHUNKER
573
        fprintf(stderr, "INIT: chunk audio %d\n", chunkaudio->seq);
574
#endif
575

    
576
#ifdef HTTPIO
577
        /* initialize the HTTP chunk pusher */
578
        initChunkPusher(); //TRIPLO
579
#endif
580

    
581
        long sleep=0;
582
        struct timeval now_tv;
583
        struct timeval tmp_tv;
584
        long long lateTime = 0;
585
        long long maxAudioInterval = 0;
586
        long long maxVDecodeTime = 0;
587
//        unsigned char lastIFrameDistance = 0;
588

    
589
#ifdef TCPIO
590
        static char peer_ip[16];
591
        static int peer_port;
592
        int res = sscanf(outside_world_url, "tcp://%15[0-9.]:%d", peer_ip, &peer_port);
593
        if (res < 2) {
594
                fprintf(stderr,"error parsing output url: %s\n", outside_world_url);
595
                return -2;
596
        }
597
        
598
        initTCPPush(peer_ip, peer_port);
599
#endif
600
#ifdef UDPIO
601
        static char peer_ip[16];
602
        static int peer_port;
603
        int res = sscanf(outside_world_url, "udp://%15[0-9.]:%d", peer_ip, &peer_port);
604
        if (res < 2) {
605
                fprintf(stderr,"error parsing output url: %s\n", outside_world_url);
606
                return -2;
607
        }
608
        
609
        initUDPPush(peer_ip, peer_port);
610
#endif
611
        
612
        char videotrace_filename[255];
613
        char psnr_filename[255];
614
        sprintf(videotrace_filename, "yuv_data/videotrace.log");
615
        sprintf(psnr_filename, "yuv_data/psnrtrace.log");
616
        FILE* videotrace = fopen(videotrace_filename, "w");
617
        FILE* psnrtrace = fopen(psnr_filename, "w");
618

    
619
        //main loop to read from the input file
620
        while((av_read_frame(pFormatCtx, &packet)>=0) && !quit)
621
        {
622
                //detect if a strange number of anomalies is occurring
623
                if(ptsvideo1 < 0 || ptsvideo1 > packet.dts || ptsaudio1 < 0 || ptsaudio1 > packet.dts) {
624
                        pts_anomalies_counter++;
625
#ifdef DEBUG_ANOMALIES
626
                        fprintf(stderr, "READLOOP: pts BASE anomaly detected number %d\n", pts_anomalies_counter);
627
#endif
628
                        if(pts_anomaly_threshold >=0 && live_source) { //reset just in case of live source
629
                                if(pts_anomalies_counter > pts_anomaly_threshold) {
630
#ifdef DEBUG_ANOMALIES
631
                                        fprintf(stderr, "READLOOP: too many pts BASE anomalies. resetting pts base\n");
632
#endif
633
                                        av_free_packet(&packet);
634
                                        goto close;
635
                                }
636
                        }
637
                }
638

    
639
                //newTime_video and _audio are in usec
640
                //if video and audio stamps differ more than 5sec
641
                if( newTime_video - newTime_audio > 5000000 || newTime_video - newTime_audio < -5000000 ) {
642
                        newtime_anomalies_counter++;
643
#ifdef DEBUG_ANOMALIES
644
                        fprintf(stderr, "READLOOP: NEWTIME audio video differ anomaly detected number %d\n", newtime_anomalies_counter);
645
#endif
646
                }
647

    
648
                if(newtime_anomaly_threshold >=0 && newtime_anomalies_counter > newtime_anomaly_threshold) {
649
                        if(live_source) { //restart just in case of live source
650
#ifdef DEBUG_ANOMALIES
651
                                fprintf(stderr, "READLOOP: too many NEGATIVE TIMESTAMPS anomalies. Restarting.\n");
652
#endif
653
                                av_free_packet(&packet);
654
                                goto close;
655
                        }
656
                }
657

    
658
                // Is this a packet from the video stream?
659
                if(packet.stream_index==videoStream)
660
                {
661
                        if(!live_source)
662
                        {
663
                                if(audioStream != -1) { //take this "time bank" method into account only if we have audio track
664
                                        // lateTime < 0 means a positive time account that can be used to decode video frames
665
                                        // if (lateTime + maxVDecodeTime) >= 0 then we may have a negative time account after video transcoding
666
                                        // therefore, it's better to skip the frame
667
                                        if(timebank && (lateTime+maxVDecodeTime) >= 0)
668
                                        {
669
#ifdef DEBUG_ANOMALIES
670
                                                fprintf(stderr, "\n\n\t\t************************* SKIPPING VIDEO FRAME %ld ***********************************\n\n", sleep);
671
#endif
672
                                                av_free_packet(&packet);
673
                                                continue;
674
                                        }
675
                                }
676
                        }
677
                        
678
                        gettimeofday(&tmp_tv, NULL);
679
                        
680
                        //decode the video packet into a raw pFrame
681
                        if(avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished, &packet)>0)
682
                        {
683
                                // usleep(5000);
684
#ifdef DEBUG_VIDEO_FRAMES
685
                                fprintf(stderr, "VIDEOin pkt: dts %lld pts %lld\n", packet.dts, packet.pts);
686
                                fprintf(stderr, "VIDEOdecode: pkt_dts %lld pkt_pts %lld frame.pts %lld\n", pFrame->pkt_dts, pFrame->pkt_pts, pFrame->pts);
687
                                fprintf(stderr, "VIDEOdecode intype %d%s\n", pFrame->pict_type, pFrame->key_frame ? " (key)" : "");
688
#endif
689
                                pFrame->pts = av_rescale_q(pFrame->pkt_pts, pFormatCtx->streams[videoStream]->time_base, pCodecCtxEnc->time_base);
690
                                if(frameFinished)
691
                                { // it must be true all the time else error
692
                                
693
                                        frame->number = ++contFrameVideo;
694

    
695
#ifdef VIDEO_DEINTERLACE
696
                                if (!vcopy) {
697
                                        avpicture_deinterlace(
698
                                                (AVPicture*) pFrame,
699
                                                (const AVPicture*) pFrame,
700
                                                pCodecCtxEnc->pix_fmt,
701
                                                pCodecCtxEnc->width,
702
                                                pCodecCtxEnc->height);
703
                                }
704
#endif
705

    
706
#ifdef DEBUG_VIDEO_FRAMES
707
                                        fprintf(stderr, "VIDEO: finished frame %d dts %lld pts %lld\n", frame->number, packet.dts, packet.pts);
708
#endif
709
                                        if(frame->number==0) {
710
                                                if(packet.dts==AV_NOPTS_VALUE)
711
                                                {
712
                                                        //a Dts with a noPts value is troublesome case for delta calculation based on Dts
713
                                                        contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0);
714
                                                        av_free_packet(&packet);
715
                                                        continue;
716
                                                }
717
                                                last_pkt_dts = packet.dts;
718
                                                newTime = 0;
719
                                        }
720
                                        else {
721
                                                if(packet.dts!=AV_NOPTS_VALUE) {
722
                                                        delta_video = packet.dts-last_pkt_dts;
723
                                                        last_pkt_dts = packet.dts;
724
                                                }
725
                                                else if(delta_video==0)
726
                                                {
727
                                                        //a Dts with a noPts value is troublesome case for delta calculation based on Dts
728
                                                        contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0);
729
                                                        av_free_packet(&packet);
730
                                                        continue;
731
                                                }
732
                                        }
733
#ifdef DEBUG_VIDEO_FRAMES
734
                                        fprintf(stderr, "VIDEO: deltavideo : %d\n", (int)delta_video);
735
#endif
736

    
737
                                        if(vcopy) {
738
                                                video_frame_size = packet.size;
739
                                                if (video_frame_size > video_outbuf_size) {
740
                                                        fprintf(stderr, "VIDEO: error, outbuf too small, SKIPPING\n");;
741
                                                        av_free_packet(&packet);
742
                                                        continue;
743
                                                } else {
744
                                                        memcpy(video_outbuf, packet.data, video_frame_size);
745
                                                }
746
                                        } else if(pCodecCtx->height != pCodecCtxEnc->height || pCodecCtx->width != pCodecCtxEnc->width) {
747
//                                                static AVPicture pict;
748
                                                static struct SwsContext *img_convert_ctx = NULL;
749
                                                
750
                                                pFrame->pict_type = 0;
751
                                                if(img_convert_ctx == NULL)
752
                                                {
753
                                                        img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, PIX_FMT_YUV420P, dest_width, dest_height, PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);
754
                                                        if(img_convert_ctx == NULL) {
755
                                                                fprintf(stderr, "Cannot initialize the conversion context!\n");
756
                                                                exit(1);
757
                                                        }
758
                                                }
759
                                                sws_scale(img_convert_ctx, pFrame->data, pFrame->linesize, 0, pCodecCtx->height, scaledFrame->data, scaledFrame->linesize);
760
                                                scaledFrame->pts = pFrame->pts;
761
                                                scaledFrame->pict_type = 0;
762
                                                video_frame_size = avcodec_encode_video(pCodecCtxEnc, video_outbuf, video_outbuf_size, scaledFrame);
763
                                        } else {
764
                                                pFrame->pict_type = 0;
765
                                                video_frame_size = avcodec_encode_video(pCodecCtxEnc, video_outbuf, video_outbuf_size, pFrame);
766
                                        }
767

    
768
                                        if(video_frame_size <= 0)
769
                                        {
770
                                                contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0);
771
                                                av_free_packet(&packet);
772
                                                continue;
773
                                        }
774

    
775
#ifdef DEBUG_VIDEO_FRAMES
776
                                        if(!vcopy && pCodecCtxEnc->coded_frame) {
777
                                                fprintf(stderr, "VIDEOout: pkt_dts %lld pkt_pts %lld frame.pts %lld\n", pCodecCtxEnc->coded_frame->pkt_dts, pCodecCtxEnc->coded_frame->pkt_pts, pCodecCtxEnc->coded_frame->pts);
778
                                                fprintf(stderr, "VIDEOout: outtype: %d%s\n",
779
                                                        pCodecCtxEnc->coded_frame->pict_type, pCodecCtxEnc->coded_frame->key_frame ? " (key)" : "");
780
                                        }
781
#endif
782

    
783
                                        //use pts if dts is invalid
784
                                        if(pCodecCtxEnc->coded_frame->pts!=AV_NOPTS_VALUE)
785
                                                target_pts = av_rescale_q(pCodecCtxEnc->coded_frame->pts, pCodecCtxEnc->time_base, pFormatCtx->streams[videoStream]->time_base);
786
                                        else
787
                                        {
788
                                                fprintf(stderr, "VIDEOout: pts error\n");
789
                                                exit(1);
790
                                        }
791

    
792
                                        if(offset_av)
793
                                        {
794
                                                if(FirstTimeVideo && target_pts>0) {
795
                                                        ptsvideo1 = target_pts;
796
                                                        FirstTimeVideo = 0;
797
#ifdef DEBUG_VIDEO_FRAMES
798
                                                        fprintf(stderr, "VIDEO: SET PTS BASE OFFSET %lld\n", ptsvideo1);
799
#endif
800
                                                }
801
                                        }
802
                                        else //we want to compensate audio and video offset for this source
803
                                        {
804
                                                if(FirstTimeVideo && target_pts>0) {
805
                                                        //maintain the offset between audio pts and video pts
806
                                                        //because in case of live source they have the same numbering
807
                                                        if(ptsaudio1 > 0) //if we have already seen some audio frames...
808
                                                                ptsvideo1 = ptsaudio1;
809
                                                        else
810
                                                                ptsvideo1 = target_pts;
811
                                                        FirstTimeVideo = 0;
812
#ifdef DEBUG_VIDEO_FRAMES
813
                                                        fprintf(stderr, "VIDEO LIVE: SET PTS BASE OFFSET %lld\n", ptsvideo1);
814
#endif
815
                                                }
816
                                        }
817
                                        //compute the new video timestamp in milliseconds
818
                                        if(frame->number>0) {
819
                                                newTime = (target_pts - ptsvideo1) * 1000 * pFormatCtx->streams[videoStream]->time_base.num / pFormatCtx->streams[videoStream]->time_base.den;
820
                                                // store timestamp in useconds for next frame sleep
821
                                                newTime_video = newTime*1000;
822
                                        }
823
#ifdef DEBUG_TIMESTAMPING
824
                                        fprintf(stderr, "VIDEO: NEWTIMESTAMP %ld\n", newTime);
825
#endif
826
                                        if(newTime<0) {
827
#ifdef DEBUG_VIDEO_FRAMES
828
                                                fprintf(stderr, "VIDEO: SKIPPING FRAME\n");
829
#endif
830
                                                newtime_anomalies_counter++;
831
#ifdef DEBUG_ANOMALIES
832
                                                fprintf(stderr, "READLOOP: NEWTIME negative video timestamp anomaly detected number %d\n", newtime_anomalies_counter);
833
#endif
834
                                                contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0);
835
                                                av_free_packet(&packet);
836
                                                continue; //SKIP THIS FRAME, bad timestamp
837
                                        }
838
                                        
839
                                        //~ printf("pCodecCtxEnc->error[0]=%lld\n", pFrame->error[0]);
840
        
841
                                        frame->timestamp.tv_sec = (long long)newTime/1000;
842
                                        frame->timestamp.tv_usec = newTime%1000;
843
                                        frame->size = video_frame_size;
844
                                        /* pict_type maybe 1 (I), 2 (P), 3 (B), 5 (AUDIO)*/
845
                                        frame->type = vcopy ? pFrame->pict_type : (unsigned char)pCodecCtxEnc->coded_frame->pict_type;
846

    
847
#ifdef DEBUG_VIDEO_FRAMES
848
                                        if (!vcopy) fprintf(stderr, "VIDEO: original codec frame number %d vs. encoded %d vs. packed %d\n", pCodecCtx->frame_number, pCodecCtxEnc->frame_number, frame->number);
849
                                        if (!vcopy) fprintf(stderr, "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);
850
#endif
851

    
852
#ifdef YUV_RECORD_ENABLED
853
                                        if(!vcopy && ChunkerStreamerTestMode)
854
                                        {
855
                                                if(videotrace)
856
                                                        fprintf(videotrace, "%d %d %d\n", frame->number, pFrame->pict_type, frame->size);
857

    
858
                                                if(pCodecCtx->height != pCodecCtxEnc->height || pCodecCtx->width != pCodecCtxEnc->width)
859
                                                        SaveFrame(scaledFrame, dest_width, dest_height);
860
                                                else
861
                                                        SaveFrame(pFrame, dest_width, dest_height);
862

    
863
                                                ++savedVideoFrames;
864
                                                SaveEncodedFrame(frame, video_outbuf);
865

    
866
                                                if(!firstSavedVideoFrame)
867
                                                        firstSavedVideoFrame = frame->number;
868
                                                
869
                                                char tmp_filename[255];
870
                                                sprintf(tmp_filename, "yuv_data/streamer_out_context.txt");
871
                                                FILE* tmp = fopen(tmp_filename, "w");
872
                                                if(tmp)
873
                                                {
874
                                                        fprintf(tmp, "width = %d\nheight = %d\ntotal_frames_saved = %d\ntotal_frames_decoded = %d\nfirst_frame_number = %ld\nlast_frame_number = %d\n"
875
                                                                ,dest_width, dest_height
876
                                                                ,savedVideoFrames, savedVideoFrames, firstSavedVideoFrame, frame->number);
877
                                                        fclose(tmp);
878
                                                }
879
                                        }
880
#endif
881

    
882
#ifdef DEBUG_VIDEO_FRAMES
883
                                        fprintf(stderr, "VIDEO: encapsulated frame size:%d type:%d\n", frame->size, frame->type);
884
                                        fprintf(stderr, "VIDEO: timestamped sec %d usec:%d\n", frame->timestamp.tv_sec, frame->timestamp.tv_usec);
885
#endif
886
                                        //contFrameVideo++; //lets increase the numbering of the frames
887

    
888
                                        if(update_chunk(chunk, frame, video_outbuf) == -1) {
889
                                                fprintf(stderr, "VIDEO: unable to update chunk %d. Exiting.\n", chunk->seq);
890
                                                exit(-1);
891
                                        }
892

    
893
                                        if(chunkFilled(chunk, VIDEO_CHUNK)) { // is chunk filled using current strategy?
894
                                                //calculate priority
895
                                                chunk->priority /= chunk->frames_num;
896

    
897
                                                //SAVE ON FILE
898
                                                //saveChunkOnFile(chunk);
899
                                                //Send the chunk to an external transport/player
900
                                                sendChunk(chunk);
901
#ifdef DEBUG_CHUNKER
902
                                                fprintf(stderr, "VIDEO: sent chunk video %d, prio:%f\n", chunk->seq, chunk->priority);
903
#endif
904
                                                chunk->seq = 0; //signal that we need an increase
905
                                                //initChunk(chunk, &seq_current_chunk);
906
                                        }
907

    
908
                                        //compute how long it took to encode video frame
909
                                        gettimeofday(&now_tv, NULL);
910
                                        long long usec = (now_tv.tv_sec-tmp_tv.tv_sec)*1000000;
911
                                        usec+=(now_tv.tv_usec-tmp_tv.tv_usec);
912
                                        if(usec > maxVDecodeTime)
913
                                                maxVDecodeTime = usec;
914

    
915
                                        //we DONT have an audio track, so we compute timings and determine
916
                                        //how much time we have to sleep at next VIDEO frame taking
917
                                        //also into account how much time was needed to encode the current
918
                                        //video frame
919
                                        //all this in case the video source is not live, i.e. not self-timing
920
                                        //and only in case there is no audio track
921
                                        if(audioStream == -1) {
922
                                                if(!live_source) {
923
                                                        if(newTime_prev != 0) {
924
                                                                //how much delay between video frames ideally
925
                                                                long long maxDelay = newTime_video - newTime_prev;
926
                                                                sleep = (maxDelay - usec);
927
#ifdef DEBUG_ANOMALIES
928
                                                                printf("\tmaxDelay=%ld\n", ((long)maxDelay));
929
                                                                printf("\tlast video frame interval=%ld; sleep time=%ld\n", ((long)usec), ((long)sleep));
930
#endif
931
                                                        }
932
                                                        else
933
                                                                sleep = 0;
934

    
935
                                                        //update and store counters
936
                                                        newTime_prev = newTime_video;
937

    
938
                                                        //i can also sleep now instead of at the beginning of
939
                                                        //the next frame because in this case we only have video
940
                                                        //frames, hence it would immediately be the next thing to do
941
                                                        if(sleep > 0) {
942
#ifdef DEBUG_ANOMALIES
943
                                                                fprintf(stderr, "\n\tREADLOOP: going to sleep for %ld microseconds\n", sleep);
944
#endif
945
                                                                usleep(sleep);
946
                                                        }
947

    
948
                                                }
949
                                        }
950

    
951
                                }
952
                        }
953
                }
954
                else if(packet.stream_index==audioStream)
955
                {
956
                        if(sleep > 0)
957
                        {
958
#ifdef DEBUG_ANOMALIES
959
                                fprintf(stderr, "\n\tREADLOOP: going to sleep for %ld microseconds\n", sleep);
960
#endif
961
                                usleep(sleep);
962
                        }
963
                        
964
                        audio_data_size = AVCODEC_MAX_AUDIO_FRAME_SIZE;
965
                        //decode the audio packet into a raw audio source buffer
966
                        if(avcodec_decode_audio3(aCodecCtx, samples, &audio_data_size, &packet)>0)
967
                        {
968
#ifdef DEBUG_AUDIO_FRAMES
969
                                fprintf(stderr, "\n-------AUDIO FRAME\n");
970
                                fprintf(stderr, "AUDIO: newTimeaudioSTART : %lf\n", (double)(packet.pts)*av_q2d(pFormatCtx->streams[audioStream]->time_base));
971
#endif
972
                                if(audio_data_size>0) {
973
#ifdef DEBUG_AUDIO_FRAMES
974
                                        fprintf(stderr, "AUDIO: datasizeaudio:%d\n", audio_data_size);
975
#endif
976
                                        /* if a frame has been decoded, output it */
977
                                        //fwrite(samples, 1, audio_data_size, outfileaudio);
978
                                }
979
                                else {
980
                                        av_free_packet(&packet);
981
                                        continue;
982
                                }
983
        
984
                                audio_frame_size = avcodec_encode_audio(aCodecCtxEnc, audio_outbuf, audio_data_size, samples);
985
                                if(audio_frame_size <= 0) {
986
                                        av_free_packet(&packet);
987
                                        continue;
988
                                }
989
                                
990
                                frame->number = contFrameAudio;
991

    
992
                                if(frame->number==0) {
993
                                        if(packet.dts==AV_NOPTS_VALUE) {
994
                                                av_free_packet(&packet);
995
                                                continue;
996
                                        }
997
                                        last_pkt_dts_audio = packet.dts;
998
                                        newTime = 0;
999
                                }
1000
                                else {
1001
                                        if(packet.dts!=AV_NOPTS_VALUE) {
1002
                                                delta_audio = packet.dts-last_pkt_dts_audio;
1003
                                                last_pkt_dts_audio = packet.dts;
1004
                                        }
1005
                                        else if(delta_audio==0) {
1006
                                                av_free_packet(&packet);
1007
                                                continue;
1008
                                        }
1009
                                }
1010
#ifdef DEBUG_AUDIO_FRAMES
1011
                                fprintf(stderr, "AUDIO: original codec frame number %d vs. encoded %d vs. packed %d\n", aCodecCtx->frame_number, aCodecCtxEnc->frame_number, frame->number);
1012
#endif
1013
                                //use pts if dts is invalid
1014
                                if(packet.dts!=AV_NOPTS_VALUE)
1015
                                        target_pts = packet.dts;
1016
                                else if(packet.pts!=AV_NOPTS_VALUE) {
1017
                                        target_pts = packet.pts;
1018
                                } else  {
1019
                                        av_free_packet(&packet);
1020
                                        continue;
1021
                                }
1022

    
1023
                                if(offset_av)
1024
                                {
1025
                                        if(FirstTimeAudio && packet.dts>0) {
1026
                                                ptsaudio1 = packet.dts;
1027
                                                FirstTimeAudio = 0;
1028
#ifdef DEBUG_AUDIO_FRAMES
1029
                                                fprintf(stderr, "AUDIO: SET PTS BASE OFFSET %lld\n", ptsaudio1);
1030
#endif
1031
                                        }
1032
                                }
1033
                                else //we want to compensate audio and video offset for this source
1034
                                {
1035
                                        if(FirstTimeAudio && packet.dts>0) {
1036
                                                //maintain the offset between audio pts and video pts
1037
                                                //because in case of live source they have the same numbering
1038
                                                if(ptsvideo1 > 0) //if we have already seen some video frames...
1039
                                                        ptsaudio1 = ptsvideo1;
1040
                                                else
1041
                                                        ptsaudio1 = packet.dts;
1042
                                                FirstTimeAudio = 0;
1043
#ifdef DEBUG_AUDIO_FRAMES
1044
                                                fprintf(stderr, "AUDIO LIVE: SET PTS BASE OFFSET %f\n", ptsaudio1);
1045
#endif
1046
                                        }
1047
                                }
1048
                                //compute the new audio timestamps in milliseconds
1049
                                if(frame->number>0) {
1050
                                        newTime = ((target_pts-ptsaudio1)*1000.0*((double)av_q2d(pFormatCtx->streams[audioStream]->time_base)));//*(double)delta_audio;
1051
                                        // store timestamp in useconds for next frame sleep
1052
                                        newTime_audio = newTime*1000;
1053
                                }
1054
#ifdef DEBUG_TIMESTAMPING
1055
                                fprintf(stderr, "AUDIO: NEWTIMESTAMP %d\n", newTime);
1056
#endif
1057
                                if(newTime<0) {
1058
#ifdef DEBUG_AUDIO_FRAMES
1059
                                        fprintf(stderr, "AUDIO: SKIPPING FRAME\n");
1060
#endif
1061
                                        newtime_anomalies_counter++;
1062
#ifdef DEBUG_ANOMALIES
1063
                                        fprintf(stderr, "READLOOP: NEWTIME negative audio timestamp anomaly detected number %d\n", newtime_anomalies_counter);
1064
#endif
1065
                                        av_free_packet(&packet);
1066
                                        continue; //SKIP THIS FRAME, bad timestamp
1067
                                }
1068

    
1069
                                frame->timestamp.tv_sec = (unsigned int)(newTime + delay_audio)/1000;
1070
                                frame->timestamp.tv_usec = (newTime + delay_audio)%1000;
1071
                                frame->size = audio_frame_size;
1072
                                frame->type = 5; // 5 is audio type
1073
#ifdef DEBUG_AUDIO_FRAMES
1074
                                fprintf(stderr, "AUDIO: pts %lld duration %d timebase %d %lld dts %d\n", packet.pts, (int)packet.duration, pFormatCtx->streams[audioStream]->time_base.num, pFormatCtx->streams[audioStream]->time_base.den, packet.dts);
1075
                                fprintf(stderr, "AUDIO: timestamp sec:%d usec:%d\n", frame->timestamp.tv_sec, frame->timestamp.tv_usec);
1076
                                fprintf(stderr, "AUDIO: deltaaudio %lld\n", delta_audio);        
1077
#endif
1078
                                contFrameAudio++;
1079

    
1080
                                if(update_chunk(chunkaudio, frame, audio_outbuf) == -1) {
1081
                                        fprintf(stderr, "AUDIO: unable to update chunk %d. Exiting.\n", chunkaudio->seq);
1082
                                        exit(-1);
1083
                                }
1084
                                //set priority
1085
                                chunkaudio->priority = 1;
1086

    
1087
                                if(chunkFilled(chunkaudio, AUDIO_CHUNK)) {
1088
                                        // is chunk filled using current strategy?
1089
                                        //SAVE ON FILE
1090
                                        //saveChunkOnFile(chunkaudio);
1091
                                        //Send the chunk to an external transport/player
1092
                                        sendChunk(chunkaudio);
1093
#ifdef DEBUG_CHUNKER
1094
                                        fprintf(stderr, "AUDIO: just sent chunk audio %d\n", chunkaudio->seq);
1095
#endif
1096
                                        chunkaudio->seq = 0; //signal that we need an increase
1097
                                        //initChunk(chunkaudio, &seq_current_chunk);
1098
                                }
1099

    
1100
                                //we have an audio track, so we compute timings and determine
1101
                                //how much time we have to sleep at next audio frame taking
1102
                                //also into account how much time was needed to encode the
1103
                                //video frames
1104
                                //all this in case the video source is not live, i.e. not self-timing
1105
                                if(!live_source)
1106
                                {
1107
                                        if(newTime_prev != 0)
1108
                                        {
1109
                                                long long maxDelay = newTime_audio - newTime_prev;
1110

    
1111
                                                gettimeofday(&now_tv, NULL);
1112
                                                long long usec = (now_tv.tv_sec-lastAudioSent.tv_sec)*1000000;
1113
                                                usec+=(now_tv.tv_usec-lastAudioSent.tv_usec);
1114

    
1115
                                                if(usec > maxAudioInterval)
1116
                                                        maxAudioInterval = usec;
1117

    
1118
                                                lateTime -= (maxDelay - usec);
1119
#ifdef DEBUG_ANOMALIES
1120
                                                printf("\tmaxDelay=%ld, maxAudioInterval=%ld\n", ((long)maxDelay), ((long) maxAudioInterval));
1121
                                                printf("\tlast audio frame interval=%ld; lateTime=%ld\n", ((long)usec), ((long)lateTime));
1122
#endif
1123

    
1124
                                                if((lateTime+maxAudioInterval) < 0)
1125
                                                        sleep = (lateTime+maxAudioInterval)*-1;
1126
                                                else
1127
                                                        sleep = 0;
1128
                                        }
1129
                                        else
1130
                                                sleep = 0;
1131

    
1132
                                        newTime_prev = newTime_audio;
1133
                                        gettimeofday(&lastAudioSent, NULL);
1134
                                }
1135
                        }
1136
                }
1137
#ifdef DEBUG_CHUNKER
1138
                fprintf(stderr,"Free the packet that was allocated by av_read_frame\n");
1139
#endif
1140
                av_free_packet(&packet);
1141
        }
1142
        
1143
        if(videotrace)
1144
                fclose(videotrace);
1145
        if(psnrtrace)
1146
                fclose(psnrtrace);
1147

    
1148
close:
1149
        if(chunk->seq != 0 && chunk->frames_num>0) {
1150
                //SAVE ON FILE
1151
                //saveChunkOnFile(chunk);
1152
                //Send the chunk to an external transport/player
1153
                sendChunk(chunk);
1154
#ifdef DEBUG_CHUNKER
1155
                fprintf(stderr, "CHUNKER: SENDING LAST VIDEO CHUNK\n");
1156
#endif
1157
                chunk->seq = 0; //signal that we need an increase just in case we will restart
1158
        }
1159
        if(chunkaudio->seq != 0 && chunkaudio->frames_num>0) {
1160
                //SAVE ON FILE     
1161
                //saveChunkOnFile(chunkaudio);
1162
                //Send the chunk via http to an external transport/player
1163
                sendChunk(chunkaudio);
1164
#ifdef DEBUG_CHUNKER
1165
                fprintf(stderr, "CHUNKER: SENDING LAST AUDIO CHUNK\n");
1166
#endif
1167
                chunkaudio->seq = 0; //signal that we need an increase just in case we will restart
1168
        }
1169

    
1170
#ifdef HTTPIO
1171
        /* finalize the HTTP chunk pusher */
1172
        finalizeChunkPusher();
1173
#endif
1174

    
1175
        free(chunk);
1176
        free(chunkaudio);
1177
        free(frame);
1178
        av_free(video_outbuf);
1179
        av_free(scaledFrame_buffer);
1180
        av_free(audio_outbuf);
1181
        free(cmeta);
1182

    
1183
        // Free the YUV frame
1184
        av_free(pFrame);
1185
        av_free(scaledFrame);
1186
        av_free(samples);
1187
  
1188
        // Close the codec
1189
        if (!vcopy) avcodec_close(pCodecCtx);
1190
        if (!vcopy) avcodec_close(pCodecCtxEnc);
1191

    
1192
        if(audioStream!=-1) {
1193
                avcodec_close(aCodecCtx);
1194
                avcodec_close(aCodecCtxEnc);
1195
        }
1196
  
1197
        // Close the video file
1198
        av_close_input_file(pFormatCtx);
1199

    
1200
        if(LOOP_MODE) {
1201
                //we want video to continue, but the av_read_frame stopped
1202
                //lets wait a 5 secs, and cycle in again
1203
                usleep(5000000);
1204
#ifdef DEBUG_CHUNKER
1205
                fprintf(stderr, "CHUNKER: WAITING 5 secs FOR LIVE SOURCE TO SKIP ERRORS AND RESTARTING\n");
1206
#endif
1207
                videoStream = -1;
1208
                audioStream = -1;
1209
                FirstTimeAudio=1;
1210
                FirstTimeVideo=1;
1211
                pts_anomalies_counter=0;
1212
                newtime_anomalies_counter=0;
1213
                newTime=0;
1214
                newTime_audio=0;
1215
                newTime_prev=0;
1216
                ptsvideo1=0;
1217
                ptsaudio1=0;
1218
                last_pkt_dts=0;
1219
                delta_video=0;
1220
                delta_audio=0;
1221
                last_pkt_dts_audio=0;
1222
                target_pts=0;
1223
                i=0;
1224
                //~ contFrameVideo = 0;
1225
                //~ contFrameAudio = 1;
1226
                
1227
#ifdef YUV_RECORD_ENABLED
1228
                if(ChunkerStreamerTestMode)
1229
                {
1230
                        video_record_count++;
1231
                        //~ savedVideoFrames = 0;
1232
                        
1233
                        //~ char tmp_filename[255];
1234
                        //~ sprintf(tmp_filename, "yuv_data/out_%d.yuv", video_record_count);
1235
                        //~ FILE *pFile=fopen(tmp_filename, "w");
1236
                        //~ if(pFile!=NULL)
1237
                                //~ fclose(pFile);
1238
                }
1239
#endif
1240

    
1241
                goto restart;
1242
        }
1243

    
1244
#ifdef TCPIO
1245
        finalizeTCPChunkPusher();
1246
#endif
1247

    
1248
        return 0;
1249
}
1250

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

    
1255
        //moving temp pointer to encode Frame on the wire
1256
        uint8_t *tempdata = NULL;
1257

    
1258
        if(chunk->seq == 0) {
1259
                initChunk(chunk, &seq_current_chunk);
1260
        }
1261
        //add frame priority to chunk priority (to be normalized later on)
1262
        chunk->priority += frame->type + 1; // I:2, P:3, B:4
1263

    
1264
        //HINT on malloc
1265
        chunk->data = (uint8_t *)realloc(chunk->data, sizeof(uint8_t)*(chunk->payload_len + frame->size + sizeFrameHeader));
1266
        if(!chunk->data)  {
1267
                fprintf(stderr, "Memory error in chunk!!!\n");
1268
                return -1;
1269
        }
1270
        chunk->frames_num++; // number of frames in the current chunk
1271

    
1272
/*
1273
        //package the Frame header
1274
        tempdata = chunk->data+chunk->payload_len;
1275
        *((int32_t *)tempdata) = frame->number;
1276
        tempdata+=sizeof(int32_t);
1277
        *((struct timeval *)tempdata) = frame->timestamp;
1278
        tempdata+=sizeof(struct timeval);
1279
        *((int32_t *)tempdata) = frame->size;
1280
        tempdata+=sizeof(int32_t);
1281
        *((int32_t *)tempdata) = frame->type;
1282
        tempdata+=sizeof(int32_t);
1283
*/
1284
        //package the Frame header: network order and platform independent
1285
        tempdata = chunk->data+chunk->payload_len;
1286
        bit32_encoded_push(frame->number, tempdata);
1287
        bit32_encoded_push(frame->timestamp.tv_sec, tempdata + CHUNK_TRANSCODING_INT_SIZE);
1288
        bit32_encoded_push(frame->timestamp.tv_usec, tempdata + CHUNK_TRANSCODING_INT_SIZE*2);
1289
        bit32_encoded_push(frame->size, tempdata + CHUNK_TRANSCODING_INT_SIZE*3);
1290
        bit32_encoded_push(frame->type, tempdata + CHUNK_TRANSCODING_INT_SIZE*4);
1291

    
1292
         //insert the new frame data
1293
        memcpy(chunk->data + chunk->payload_len + sizeFrameHeader, outbuf, frame->size);
1294
        chunk->payload_len += frame->size + sizeFrameHeader; // update payload length
1295
        //chunk lenght is updated just prior to pushing it out because
1296
        //the chunk header len is better calculated there
1297
        //chunk->len = sizeChunkHeader + chunk->payload_len; // update overall length
1298

    
1299
        //update timestamps
1300
        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) {
1301
                                                chunk->start_time.tv_sec = frame->timestamp.tv_sec;
1302
                                                chunk->start_time.tv_usec = frame->timestamp.tv_usec;
1303
        }
1304
        
1305
        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) {
1306
                                                chunk->end_time.tv_sec = frame->timestamp.tv_sec;
1307
                                                chunk->end_time.tv_usec = frame->timestamp.tv_usec;
1308
        }
1309
        return 0;
1310
}
1311

    
1312
void SaveFrame(AVFrame *pFrame, int width, int height)
1313
{
1314
        FILE *pFile;
1315
        int  y;
1316

    
1317
         // Open file
1318
        char tmp_filename[255];
1319
        sprintf(tmp_filename, "yuv_data/streamer_out.yuv");
1320
        pFile=fopen(tmp_filename, "ab");
1321
        if(pFile==NULL)
1322
                return;
1323

    
1324
        // Write header
1325
        //fprintf(pFile, "P5\n%d %d\n255\n", width, height);
1326
  
1327
        // Write Y data
1328
        for(y=0; y<height; y++)
1329
                  if(fwrite(pFrame->data[0]+y*pFrame->linesize[0], 1, width, pFile) != width)
1330
                {
1331
                        printf("errno = %d\n", errno);
1332
                        exit(1);
1333
                }
1334
        // Write U data
1335
        for(y=0; y<height/2; y++)
1336
                  if(fwrite(pFrame->data[1]+y*pFrame->linesize[1], 1, width/2, pFile) != width/2)
1337
                  {
1338
                        printf("errno = %d\n", errno);
1339
                        exit(1);
1340
                }
1341
        // Write V data
1342
        for(y=0; y<height/2; y++)
1343
                  if(fwrite(pFrame->data[2]+y*pFrame->linesize[2], 1, width/2, pFile) != width/2)
1344
                  {
1345
                        printf("errno = %d\n", errno);
1346
                        exit(1);
1347
                }
1348
  
1349
        // Close file
1350
        fclose(pFile);
1351
}
1352

    
1353
void SaveEncodedFrame(Frame* frame, uint8_t *video_outbuf)
1354
{
1355
        static FILE* pFile = NULL;
1356
        
1357
        pFile=fopen("yuv_data/streamer_out.mpeg4", "ab");
1358
        fwrite(frame, sizeof(Frame), 1, pFile);
1359
        fwrite(video_outbuf, frame->size, 1, pFile);
1360
        fclose(pFile);
1361
}