Statistics
| Branch: | Revision:

chunker-player / chunker_streamer / chunker_streamer.c @ 046e7b49

History | View | Annotate | Download (43 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\n"
132
    "=======================================================\n", argv[0]
133
    );
134
  }
135

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

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

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

    
160
        //numeric identifiers of input streams
161
        int videoStream = -1;
162
        int audioStream = -1;
163

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

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

    
184
        AVFormatContext *pFormatCtx;
185
        AVCodecContext  *pCodecCtx = NULL ,*pCodecCtxEnc = NULL ,*aCodecCtxEnc = NULL ,*aCodecCtx = NULL;
186
        AVCodec         *pCodec = NULL ,*pCodecEnc = NULL ,*aCodec = NULL ,*aCodecEnc = NULL;
187
        AVPacket         packet;
188

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

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

    
282
#ifdef YUV_RECORD_ENABLED
283
        if(ChunkerStreamerTestMode)
284
        {
285
                DELETE_DIR("yuv_data");
286
                CREATE_DIR("yuv_data");
287
                //FILE* pFile=fopen("yuv_data/streamer_out.yuv", "w");
288
                //fclose(pFile);
289
        }
290
#endif
291

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

    
312
        // Register all formats and codecs
313
        av_register_all();
314

    
315
        // Open input file
316
        if(av_open_input_file(&pFormatCtx, av_input, NULL, 0, NULL) != 0) {
317
                fprintf(stdout, "INIT: Couldn't open video file. Exiting.\n");
318
                exit(-1);
319
        }
320

    
321
        // Retrieve stream information
322
        if(av_find_stream_info(pFormatCtx) < 0) {
323
                fprintf(stdout, "INIT: Couldn't find stream information. Exiting.\n");
324
                exit(-1);
325
        }
326

    
327
        // Dump information about file onto standard error
328
        dump_format(pFormatCtx, 0, av_input, 0);
329

    
330
        // Find the video and audio stream numbers
331
        for(i=0; i<pFormatCtx->nb_streams; i++) {
332
                if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_VIDEO && videoStream<0) {
333
                        videoStream=i;
334
                }
335
                if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_AUDIO && audioStream<0) {
336
                        audioStream=i;
337
                }
338
        }
339
        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);
340

    
341
        fprintf(stderr, "INIT: Video stream has id : %d\n",videoStream);
342
        fprintf(stderr, "INIT: Audio stream has id : %d\n",audioStream);
343

    
344
        if(videoStream==-1 && audioStream==-1) {
345
                fprintf(stdout, "INIT: Didn't find audio and video streams. Exiting.\n");
346
                exit(-1);
347
        }
348

    
349
        // Get a pointer to the codec context for the input video stream
350
        pCodecCtx=pFormatCtx->streams[videoStream]->codec;
351
        pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
352
        //extract W and H
353
        fprintf(stderr, "INIT: Width:%d Height:%d\n", pCodecCtx->width, pCodecCtx->height);
354

    
355
        // Get a pointer to the codec context for the input audio stream
356
        if(audioStream != -1) {
357
                aCodecCtx=pFormatCtx->streams[audioStream]->codec;
358
                fprintf(stderr, "INIT: AUDIO Codecid: %d channels %d samplerate %d\n", aCodecCtx->codec_id, aCodecCtx->channels, aCodecCtx->sample_rate);
359
        }
360

    
361
        // Figure out size
362
        dest_width = (dest_width > 0) ? dest_width : pCodecCtx->width;
363
        dest_height = (dest_height > 0) ? dest_height : pCodecCtx->height;
364

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

    
377
        pCodecCtxEnc=avcodec_alloc_context();
378
        pCodecCtxEnc->codec_type = CODEC_TYPE_VIDEO;
379
        pCodecCtxEnc->codec_id = pCodecEnc->id;
380

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

    
400
        //some generic quality tuning
401
        pCodecCtxEnc->mb_decision = FF_MB_DECISION_RD;
402

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

    
431
        // libx264-main.ffpreset preset
432
        //pCodecCtxEnc->flags2|=CODEC_FLAG2_8X8DCT;
433
        //pCodecCtxEnc->flags2^=CODEC_FLAG2_8X8DCT; // flags2=-dct8x8
434
        //pCodecCtxEnc->crf = 22;
435

    
436
#ifdef STREAMER_X264_USE_SSIM
437
        pCodecCtxEnc->flags2 |= CODEC_FLAG2_SSIM;
438
#endif
439

    
440
        //pCodecCtxEnc->weighted_p_pred=2; //maps wpredp=2; weighted prediction analysis method
441
        // pCodecCtxEnc->rc_min_rate = 0;
442
        // pCodecCtxEnc->rc_max_rate = video_bitrate*2;
443
        // pCodecCtxEnc->rc_buffer_size = 0;
444
        break;
445
    case CODEC_ID_MPEG4 :
446
        break;
447
    default:
448
        fprintf(stderr, "INIT: Unsupported OUT VIDEO codec: %s!\n", video_codec);
449
  }
450
 
451
        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);
452
 }
453

    
454
        if(pCodec==NULL) {
455
                fprintf(stderr, "INIT: Unsupported IN VIDEO pcodec!\n");
456
                return -1; // Codec not found
457
        }
458
        if(!vcopy && pCodecEnc==NULL) {
459
                fprintf(stderr, "INIT: Unsupported OUT VIDEO pcodecenc!\n");
460
                return -1; // Codec not found
461
        }
462
        if(avcodec_open(pCodecCtx, pCodec)<0) {
463
                fprintf(stderr, "INIT: could not open IN VIDEO codec\n");
464
                return -1; // Could not open codec
465
        }
466
        if(!vcopy && avcodec_open(pCodecCtxEnc, pCodecEnc)<0) {
467
                fprintf(stderr, "INIT: could not open OUT VIDEO codecEnc\n");
468
                return -1; // Could not open codec
469
        }
470
        if(audioStream!=-1) {
471
                //setup audio output encoder
472
                aCodecCtxEnc = avcodec_alloc_context();
473
                aCodecCtxEnc->bit_rate = audio_bitrate; //256000
474
                aCodecCtxEnc->sample_fmt = SAMPLE_FMT_S16;
475
                aCodecCtxEnc->sample_rate = aCodecCtx->sample_rate;
476
                aCodecCtxEnc->channels = aCodecCtx->channels;
477
                fprintf(stderr, "INIT: AUDIO bitrate OUT:%d sample_rate:%d channels:%d\n", aCodecCtxEnc->bit_rate, aCodecCtxEnc->sample_rate, aCodecCtxEnc->channels);
478

    
479
                // Find the decoder for the audio stream
480
                aCodec = avcodec_find_decoder(aCodecCtx->codec_id);
481
                aCodecEnc = avcodec_find_encoder_by_name(audio_codec);
482
                if(aCodec==NULL) {
483
                        fprintf(stderr,"INIT: Unsupported acodec!\n");
484
                        return -1;
485
                }
486
                if(aCodecEnc==NULL) {
487
                        fprintf(stderr,"INIT: Unsupported acodecEnc!\n");
488
                        return -1;
489
                }
490
        
491
                if(avcodec_open(aCodecCtx, aCodec)<0) {
492
                        fprintf(stderr, "INIT: could not open IN AUDIO codec\n");
493
                        return -1; // Could not open codec
494
                }
495
                if(avcodec_open(aCodecCtxEnc, aCodecEnc)<0) {
496
                        fprintf(stderr, "INIT: could not open OUT AUDIO codec\n");
497
                        return -1; // Could not open codec
498
                }
499
        }
500
        else {
501
                fprintf(stderr,"INIT: NO AUDIO TRACK IN INPUT FILE\n");
502
        }
503

    
504
        // Allocate audio in and out buffers
505
        samples = (int16_t *)av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
506
        if(samples == NULL) {
507
                fprintf(stderr, "INIT: Memory error alloc audio samples!!!\n");
508
                return -1;
509
        }
510
        audio_outbuf_size = STREAMER_MAX_AUDIO_BUFFER_SIZE;
511
        audio_outbuf = av_malloc(audio_outbuf_size);
512
        if(audio_outbuf == NULL) {
513
                fprintf(stderr, "INIT: Memory error alloc audio_outbuf!!!\n");
514
                return -1;
515
        }
516

    
517
        // Allocate video in frame and out buffer
518
        pFrame=avcodec_alloc_frame();
519
        scaledFrame=avcodec_alloc_frame();
520
        if(pFrame==NULL || scaledFrame == NULL) {
521
                fprintf(stderr, "INIT: Memory error alloc video frame!!!\n");
522
                return -1;
523
        }
524
        video_outbuf_size = STREAMER_MAX_VIDEO_BUFFER_SIZE;
525
        video_outbuf = av_malloc(video_outbuf_size);
526
        int scaledFrame_buf_size = avpicture_get_size( PIX_FMT_YUV420P, dest_width, dest_height);
527
        uint8_t* scaledFrame_buffer = (uint8_t *) av_malloc( scaledFrame_buf_size * sizeof( uint8_t ) );
528
        avpicture_fill( (AVPicture*) scaledFrame, scaledFrame_buffer, PIX_FMT_YUV420P, dest_width, dest_height);
529
        if(!video_outbuf || !scaledFrame_buffer) {
530
                fprintf(stderr, "INIT: Memory error alloc video_outbuf!!!\n");
531
                return -1;
532
        }
533

    
534
        //allocate Napa-Wine transport
535
        frame = (Frame *)malloc(sizeof(Frame));
536
        if(!frame) {
537
                fprintf(stderr, "INIT: Memory error alloc Frame!!!\n");
538
                return -1;
539
        }
540
        //create an empty first video chunk
541
        chunk = (ExternalChunk *)malloc(sizeof(ExternalChunk));
542
        if(!chunk) {
543
                fprintf(stderr, "INIT: Memory error alloc chunk!!!\n");
544
                return -1;
545
        }
546
        chunk->data = NULL;
547
        chunk->seq = 0;
548
        //initChunk(chunk, &seq_current_chunk); if i init them now i get out of sequence
549
#ifdef DEBUG_CHUNKER
550
        fprintf(stderr, "INIT: chunk video %d\n", chunk->seq);
551
#endif
552
        //create empty first audio chunk
553
        chunkaudio = (ExternalChunk *)malloc(sizeof(ExternalChunk));
554
        if(!chunkaudio) {
555
                fprintf(stderr, "INIT: Memory error alloc chunkaudio!!!\n");
556
                return -1;
557
        }
558
  chunkaudio->data=NULL;
559
        chunkaudio->seq = 0;
560
        //initChunk(chunkaudio, &seq_current_chunk);
561
#ifdef DEBUG_CHUNKER
562
        fprintf(stderr, "INIT: chunk audio %d\n", chunkaudio->seq);
563
#endif
564

    
565
#ifdef HTTPIO
566
        /* initialize the HTTP chunk pusher */
567
        initChunkPusher(); //TRIPLO
568
#endif
569

    
570
        long sleep=0;
571
        struct timeval now_tv;
572
        struct timeval tmp_tv;
573
        long long lateTime = 0;
574
        long long maxAudioInterval = 0;
575
        long long maxVDecodeTime = 0;
576
//        unsigned char lastIFrameDistance = 0;
577

    
578
#ifdef TCPIO
579
        static char peer_ip[16];
580
        static int peer_port;
581
        int res = sscanf(outside_world_url, "tcp://%15[0-9.]:%d", peer_ip, &peer_port);
582
        if (res < 2) {
583
                fprintf(stderr,"error parsing output url: %s\n", outside_world_url);
584
                return -2;
585
        }
586
        
587
        initTCPPush(peer_ip, peer_port);
588
#endif
589
#ifdef UDPIO
590
        static char peer_ip[16];
591
        static int peer_port;
592
        int res = sscanf(outside_world_url, "udp://%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
        initUDPPush(peer_ip, peer_port);
599
#endif
600
        
601
        char videotrace_filename[255];
602
        char psnr_filename[255];
603
        sprintf(videotrace_filename, "yuv_data/videotrace.log");
604
        sprintf(psnr_filename, "yuv_data/psnrtrace.log");
605
        FILE* videotrace = fopen(videotrace_filename, "w");
606
        FILE* psnrtrace = fopen(psnr_filename, "w");
607

    
608
        //main loop to read from the input file
609
        while((av_read_frame(pFormatCtx, &packet)>=0) && !quit)
610
        {
611
                //detect if a strange number of anomalies is occurring
612
                if(ptsvideo1 < 0 || ptsvideo1 > packet.dts || ptsaudio1 < 0 || ptsaudio1 > packet.dts) {
613
                        pts_anomalies_counter++;
614
#ifdef DEBUG_ANOMALIES
615
                        fprintf(stderr, "READLOOP: pts BASE anomaly detected number %d\n", pts_anomalies_counter);
616
#endif
617
                        if(pts_anomaly_threshold >=0 && live_source) { //reset just in case of live source
618
                                if(pts_anomalies_counter > pts_anomaly_threshold) {
619
#ifdef DEBUG_ANOMALIES
620
                                        fprintf(stderr, "READLOOP: too many pts BASE anomalies. resetting pts base\n");
621
#endif
622
                                        av_free_packet(&packet);
623
                                        goto close;
624
                                }
625
                        }
626
                }
627

    
628
                //newTime_video and _audio are in usec
629
                //if video and audio stamps differ more than 5sec
630
                if( newTime_video - newTime_audio > 5000000 || newTime_video - newTime_audio < -5000000 ) {
631
                        newtime_anomalies_counter++;
632
#ifdef DEBUG_ANOMALIES
633
                        fprintf(stderr, "READLOOP: NEWTIME audio video differ anomaly detected number %d\n", newtime_anomalies_counter);
634
#endif
635
                }
636

    
637
                if(newtime_anomaly_threshold >=0 && newtime_anomalies_counter > newtime_anomaly_threshold) {
638
                        if(live_source) { //restart just in case of live source
639
#ifdef DEBUG_ANOMALIES
640
                                fprintf(stderr, "READLOOP: too many NEGATIVE TIMESTAMPS anomalies. Restarting.\n");
641
#endif
642
                                av_free_packet(&packet);
643
                                goto close;
644
                        }
645
                }
646

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

    
684
#ifdef VIDEO_DEINTERLACE
685
                                if (!vcopy) {
686
                                        avpicture_deinterlace(
687
                                                (AVPicture*) pFrame,
688
                                                (const AVPicture*) pFrame,
689
                                                pCodecCtxEnc->pix_fmt,
690
                                                pCodecCtxEnc->width,
691
                                                pCodecCtxEnc->height);
692
                                }
693
#endif
694

    
695
#ifdef DEBUG_VIDEO_FRAMES
696
                                        fprintf(stderr, "VIDEO: finished frame %d dts %lld pts %lld\n", frame->number, packet.dts, packet.pts);
697
#endif
698
                                        if(frame->number==0) {
699
                                                if(packet.dts==AV_NOPTS_VALUE)
700
                                                {
701
                                                        //a Dts with a noPts value is troublesome case for delta calculation based on Dts
702
                                                        contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0);
703
                                                        av_free_packet(&packet);
704
                                                        continue;
705
                                                }
706
                                                last_pkt_dts = packet.dts;
707
                                                newTime = 0;
708
                                        }
709
                                        else {
710
                                                if(packet.dts!=AV_NOPTS_VALUE) {
711
                                                        delta_video = packet.dts-last_pkt_dts;
712
                                                        last_pkt_dts = packet.dts;
713
                                                }
714
                                                else if(delta_video==0)
715
                                                {
716
                                                        //a Dts with a noPts value is troublesome case for delta calculation based on Dts
717
                                                        contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0);
718
                                                        av_free_packet(&packet);
719
                                                        continue;
720
                                                }
721
                                        }
722
#ifdef DEBUG_VIDEO_FRAMES
723
                                        fprintf(stderr, "VIDEO: deltavideo : %d\n", (int)delta_video);
724
#endif
725

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

    
757
                                        if(video_frame_size <= 0)
758
                                        {
759
                                                contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0);
760
                                                av_free_packet(&packet);
761
                                                continue;
762
                                        }
763

    
764
#ifdef DEBUG_VIDEO_FRAMES
765
                                        if(!vcopy && pCodecCtxEnc->coded_frame) {
766
                                                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);
767
                                                fprintf(stderr, "VIDEOout: outtype: %d%s\n",
768
                                                        pCodecCtxEnc->coded_frame->pict_type, pCodecCtxEnc->coded_frame->key_frame ? " (key)" : "");
769
                                        }
770
#endif
771

    
772
                                        //use pts if dts is invalid
773
                                        if(pCodecCtxEnc->coded_frame->pts!=AV_NOPTS_VALUE)
774
                                                target_pts = av_rescale_q(pCodecCtxEnc->coded_frame->pts, pCodecCtxEnc->time_base, pFormatCtx->streams[videoStream]->time_base);
775
                                        else
776
                                        {
777
                                                fprintf(stderr, "VIDEOout: pts error\n");
778
                                                exit(1);
779
                                        }
780

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

    
836
#ifdef DEBUG_VIDEO_FRAMES
837
                                        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);
838
                                        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);
839
#endif
840

    
841
#ifdef YUV_RECORD_ENABLED
842
                                        if(!vcopy && ChunkerStreamerTestMode)
843
                                        {
844
                                                if(videotrace)
845
                                                        fprintf(videotrace, "%d %d %d\n", frame->number, pFrame->pict_type, frame->size);
846

    
847
                                                if(pCodecCtx->height != pCodecCtxEnc->height || pCodecCtx->width != pCodecCtxEnc->width)
848
                                                        SaveFrame(scaledFrame, dest_width, dest_height);
849
                                                else
850
                                                        SaveFrame(pFrame, dest_width, dest_height);
851

    
852
                                                ++savedVideoFrames;
853
                                                SaveEncodedFrame(frame, video_outbuf);
854

    
855
                                                if(!firstSavedVideoFrame)
856
                                                        firstSavedVideoFrame = frame->number;
857
                                                
858
                                                char tmp_filename[255];
859
                                                sprintf(tmp_filename, "yuv_data/streamer_out_context.txt");
860
                                                FILE* tmp = fopen(tmp_filename, "w");
861
                                                if(tmp)
862
                                                {
863
                                                        fprintf(tmp, "width = %d\nheight = %d\ntotal_frames_saved = %d\ntotal_frames_decoded = %d\nfirst_frame_number = %ld\nlast_frame_number = %d\n"
864
                                                                ,dest_width, dest_height
865
                                                                ,savedVideoFrames, savedVideoFrames, firstSavedVideoFrame, frame->number);
866
                                                        fclose(tmp);
867
                                                }
868
                                        }
869
#endif
870

    
871
#ifdef DEBUG_VIDEO_FRAMES
872
                                        fprintf(stderr, "VIDEO: encapsulated frame size:%d type:%d\n", frame->size, frame->type);
873
                                        fprintf(stderr, "VIDEO: timestamped sec %d usec:%d\n", frame->timestamp.tv_sec, frame->timestamp.tv_usec);
874
#endif
875
                                        //contFrameVideo++; //lets increase the numbering of the frames
876

    
877
                                        if(update_chunk(chunk, frame, video_outbuf) == -1) {
878
                                                fprintf(stderr, "VIDEO: unable to update chunk %d. Exiting.\n", chunk->seq);
879
                                                exit(-1);
880
                                        }
881

    
882
                                        if(chunkFilled(chunk, VIDEO_CHUNK)) { // is chunk filled using current strategy?
883
                                                //calculate priority
884
                                                chunk->priority /= chunk->frames_num;
885

    
886
                                                //SAVE ON FILE
887
                                                //saveChunkOnFile(chunk);
888
                                                //Send the chunk to an external transport/player
889
                                                sendChunk(chunk);
890
#ifdef DEBUG_CHUNKER
891
                                                fprintf(stderr, "VIDEO: sent chunk video %d, prio:%f\n", chunk->seq, chunk->priority);
892
#endif
893
                                                chunk->seq = 0; //signal that we need an increase
894
                                                //initChunk(chunk, &seq_current_chunk);
895
                                        }
896

    
897
                                        //compute how long it took to encode video frame
898
                                        gettimeofday(&now_tv, NULL);
899
                                        long long usec = (now_tv.tv_sec-tmp_tv.tv_sec)*1000000;
900
                                        usec+=(now_tv.tv_usec-tmp_tv.tv_usec);
901
                                        if(usec > maxVDecodeTime)
902
                                                maxVDecodeTime = usec;
903

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

    
924
                                                        //update and store counters
925
                                                        newTime_prev = newTime_video;
926

    
927
                                                        //i can also sleep now instead of at the beginning of
928
                                                        //the next frame because in this case we only have video
929
                                                        //frames, hence it would immediately be the next thing to do
930
                                                        if(sleep > 0) {
931
#ifdef DEBUG_ANOMALIES
932
                                                                fprintf(stderr, "\n\tREADLOOP: going to sleep for %ld microseconds\n", sleep);
933
#endif
934
                                                                usleep(sleep);
935
                                                        }
936

    
937
                                                }
938
                                        }
939

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

    
981
                                if(frame->number==0) {
982
                                        if(packet.dts==AV_NOPTS_VALUE) {
983
                                                av_free_packet(&packet);
984
                                                continue;
985
                                        }
986
                                        last_pkt_dts_audio = packet.dts;
987
                                        newTime = 0;
988
                                }
989
                                else {
990
                                        if(packet.dts!=AV_NOPTS_VALUE) {
991
                                                delta_audio = packet.dts-last_pkt_dts_audio;
992
                                                last_pkt_dts_audio = packet.dts;
993
                                        }
994
                                        else if(delta_audio==0) {
995
                                                av_free_packet(&packet);
996
                                                continue;
997
                                        }
998
                                }
999
#ifdef DEBUG_AUDIO_FRAMES
1000
                                fprintf(stderr, "AUDIO: original codec frame number %d vs. encoded %d vs. packed %d\n", aCodecCtx->frame_number, aCodecCtxEnc->frame_number, frame->number);
1001
#endif
1002
                                //use pts if dts is invalid
1003
                                if(packet.dts!=AV_NOPTS_VALUE)
1004
                                        target_pts = packet.dts;
1005
                                else if(packet.pts!=AV_NOPTS_VALUE) {
1006
                                        target_pts = packet.pts;
1007
                                } else  {
1008
                                        av_free_packet(&packet);
1009
                                        continue;
1010
                                }
1011

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

    
1058
                                frame->timestamp.tv_sec = (unsigned int)(newTime + delay_audio)/1000;
1059
                                frame->timestamp.tv_usec = (newTime + delay_audio)%1000;
1060
                                frame->size = audio_frame_size;
1061
                                frame->type = 5; // 5 is audio type
1062
#ifdef DEBUG_AUDIO_FRAMES
1063
                                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);
1064
                                fprintf(stderr, "AUDIO: timestamp sec:%d usec:%d\n", frame->timestamp.tv_sec, frame->timestamp.tv_usec);
1065
                                fprintf(stderr, "AUDIO: deltaaudio %lld\n", delta_audio);        
1066
#endif
1067
                                contFrameAudio++;
1068

    
1069
                                if(update_chunk(chunkaudio, frame, audio_outbuf) == -1) {
1070
                                        fprintf(stderr, "AUDIO: unable to update chunk %d. Exiting.\n", chunkaudio->seq);
1071
                                        exit(-1);
1072
                                }
1073
                                //set priority
1074
                                chunkaudio->priority = 1;
1075

    
1076
                                if(chunkFilled(chunkaudio, AUDIO_CHUNK)) {
1077
                                        // is chunk filled using current strategy?
1078
                                        //SAVE ON FILE
1079
                                        //saveChunkOnFile(chunkaudio);
1080
                                        //Send the chunk to an external transport/player
1081
                                        sendChunk(chunkaudio);
1082
#ifdef DEBUG_CHUNKER
1083
                                        fprintf(stderr, "AUDIO: just sent chunk audio %d\n", chunkaudio->seq);
1084
#endif
1085
                                        chunkaudio->seq = 0; //signal that we need an increase
1086
                                        //initChunk(chunkaudio, &seq_current_chunk);
1087
                                }
1088

    
1089
                                //we have an audio track, so we compute timings and determine
1090
                                //how much time we have to sleep at next audio frame taking
1091
                                //also into account how much time was needed to encode the
1092
                                //video frames
1093
                                //all this in case the video source is not live, i.e. not self-timing
1094
                                if(!live_source)
1095
                                {
1096
                                        if(newTime_prev != 0)
1097
                                        {
1098
                                                long long maxDelay = newTime_audio - newTime_prev;
1099

    
1100
                                                gettimeofday(&now_tv, NULL);
1101
                                                long long usec = (now_tv.tv_sec-lastAudioSent.tv_sec)*1000000;
1102
                                                usec+=(now_tv.tv_usec-lastAudioSent.tv_usec);
1103

    
1104
                                                if(usec > maxAudioInterval)
1105
                                                        maxAudioInterval = usec;
1106

    
1107
                                                lateTime -= (maxDelay - usec);
1108
#ifdef DEBUG_ANOMALIES
1109
                                                printf("\tmaxDelay=%ld, maxAudioInterval=%ld\n", ((long)maxDelay), ((long) maxAudioInterval));
1110
                                                printf("\tlast audio frame interval=%ld; lateTime=%ld\n", ((long)usec), ((long)lateTime));
1111
#endif
1112

    
1113
                                                if((lateTime+maxAudioInterval) < 0)
1114
                                                        sleep = (lateTime+maxAudioInterval)*-1;
1115
                                                else
1116
                                                        sleep = 0;
1117
                                        }
1118
                                        else
1119
                                                sleep = 0;
1120

    
1121
                                        newTime_prev = newTime_audio;
1122
                                        gettimeofday(&lastAudioSent, NULL);
1123
                                }
1124
                        }
1125
                }
1126
#ifdef DEBUG_CHUNKER
1127
                fprintf(stderr,"Free the packet that was allocated by av_read_frame\n");
1128
#endif
1129
                av_free_packet(&packet);
1130
        }
1131
        
1132
        if(videotrace)
1133
                fclose(videotrace);
1134
        if(psnrtrace)
1135
                fclose(psnrtrace);
1136

    
1137
close:
1138
        if(chunk->seq != 0 && chunk->frames_num>0) {
1139
                //SAVE ON FILE
1140
                //saveChunkOnFile(chunk);
1141
                //Send the chunk to an external transport/player
1142
                sendChunk(chunk);
1143
#ifdef DEBUG_CHUNKER
1144
                fprintf(stderr, "CHUNKER: SENDING LAST VIDEO CHUNK\n");
1145
#endif
1146
                chunk->seq = 0; //signal that we need an increase just in case we will restart
1147
        }
1148
        if(chunkaudio->seq != 0 && chunkaudio->frames_num>0) {
1149
                //SAVE ON FILE     
1150
                //saveChunkOnFile(chunkaudio);
1151
                //Send the chunk via http to an external transport/player
1152
                sendChunk(chunkaudio);
1153
#ifdef DEBUG_CHUNKER
1154
                fprintf(stderr, "CHUNKER: SENDING LAST AUDIO CHUNK\n");
1155
#endif
1156
                chunkaudio->seq = 0; //signal that we need an increase just in case we will restart
1157
        }
1158

    
1159
#ifdef HTTPIO
1160
        /* finalize the HTTP chunk pusher */
1161
        finalizeChunkPusher();
1162
#endif
1163

    
1164
        free(chunk);
1165
        free(chunkaudio);
1166
        free(frame);
1167
        av_free(video_outbuf);
1168
        av_free(scaledFrame_buffer);
1169
        av_free(audio_outbuf);
1170
        free(cmeta);
1171

    
1172
        // Free the YUV frame
1173
        av_free(pFrame);
1174
        av_free(scaledFrame);
1175
        av_free(samples);
1176
  
1177
        // Close the codec
1178
        if (!vcopy) avcodec_close(pCodecCtx);
1179
        if (!vcopy) avcodec_close(pCodecCtxEnc);
1180

    
1181
        if(audioStream!=-1) {
1182
                avcodec_close(aCodecCtx);
1183
                avcodec_close(aCodecCtxEnc);
1184
        }
1185
  
1186
        // Close the video file
1187
        av_close_input_file(pFormatCtx);
1188

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

    
1230
                goto restart;
1231
        }
1232

    
1233
#ifdef TCPIO
1234
        finalizeTCPChunkPusher();
1235
#endif
1236

    
1237
        return 0;
1238
}
1239

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

    
1244
        //moving temp pointer to encode Frame on the wire
1245
        uint8_t *tempdata = NULL;
1246

    
1247
        if(chunk->seq == 0) {
1248
                initChunk(chunk, &seq_current_chunk);
1249
        }
1250
        //add frame priority to chunk priority (to be normalized later on)
1251
        chunk->priority += frame->type + 1; // I:2, P:3, B:4
1252

    
1253
        //HINT on malloc
1254
        chunk->data = (uint8_t *)realloc(chunk->data, sizeof(uint8_t)*(chunk->payload_len + frame->size + sizeFrameHeader));
1255
        if(!chunk->data)  {
1256
                fprintf(stderr, "Memory error in chunk!!!\n");
1257
                return -1;
1258
        }
1259
        chunk->frames_num++; // number of frames in the current chunk
1260

    
1261
/*
1262
        //package the Frame header
1263
        tempdata = chunk->data+chunk->payload_len;
1264
        *((int32_t *)tempdata) = frame->number;
1265
        tempdata+=sizeof(int32_t);
1266
        *((struct timeval *)tempdata) = frame->timestamp;
1267
        tempdata+=sizeof(struct timeval);
1268
        *((int32_t *)tempdata) = frame->size;
1269
        tempdata+=sizeof(int32_t);
1270
        *((int32_t *)tempdata) = frame->type;
1271
        tempdata+=sizeof(int32_t);
1272
*/
1273
        //package the Frame header: network order and platform independent
1274
        tempdata = chunk->data+chunk->payload_len;
1275
        bit32_encoded_push(frame->number, tempdata);
1276
        bit32_encoded_push(frame->timestamp.tv_sec, tempdata + CHUNK_TRANSCODING_INT_SIZE);
1277
        bit32_encoded_push(frame->timestamp.tv_usec, tempdata + CHUNK_TRANSCODING_INT_SIZE*2);
1278
        bit32_encoded_push(frame->size, tempdata + CHUNK_TRANSCODING_INT_SIZE*3);
1279
        bit32_encoded_push(frame->type, tempdata + CHUNK_TRANSCODING_INT_SIZE*4);
1280

    
1281
         //insert the new frame data
1282
        memcpy(chunk->data + chunk->payload_len + sizeFrameHeader, outbuf, frame->size);
1283
        chunk->payload_len += frame->size + sizeFrameHeader; // update payload length
1284
        //chunk lenght is updated just prior to pushing it out because
1285
        //the chunk header len is better calculated there
1286
        //chunk->len = sizeChunkHeader + chunk->payload_len; // update overall length
1287

    
1288
        //update timestamps
1289
        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) {
1290
                                                chunk->start_time.tv_sec = frame->timestamp.tv_sec;
1291
                                                chunk->start_time.tv_usec = frame->timestamp.tv_usec;
1292
        }
1293
        
1294
        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) {
1295
                                                chunk->end_time.tv_sec = frame->timestamp.tv_sec;
1296
                                                chunk->end_time.tv_usec = frame->timestamp.tv_usec;
1297
        }
1298
        return 0;
1299
}
1300

    
1301
void SaveFrame(AVFrame *pFrame, int width, int height)
1302
{
1303
        FILE *pFile;
1304
        int  y;
1305

    
1306
         // Open file
1307
        char tmp_filename[255];
1308
        sprintf(tmp_filename, "yuv_data/streamer_out.yuv");
1309
        pFile=fopen(tmp_filename, "ab");
1310
        if(pFile==NULL)
1311
                return;
1312

    
1313
        // Write header
1314
        //fprintf(pFile, "P5\n%d %d\n255\n", width, height);
1315
  
1316
        // Write Y data
1317
        for(y=0; y<height; y++)
1318
                  if(fwrite(pFrame->data[0]+y*pFrame->linesize[0], 1, width, pFile) != width)
1319
                {
1320
                        printf("errno = %d\n", errno);
1321
                        exit(1);
1322
                }
1323
        // Write U data
1324
        for(y=0; y<height/2; y++)
1325
                  if(fwrite(pFrame->data[1]+y*pFrame->linesize[1], 1, width/2, pFile) != width/2)
1326
                  {
1327
                        printf("errno = %d\n", errno);
1328
                        exit(1);
1329
                }
1330
        // Write V data
1331
        for(y=0; y<height/2; y++)
1332
                  if(fwrite(pFrame->data[2]+y*pFrame->linesize[2], 1, width/2, pFile) != width/2)
1333
                  {
1334
                        printf("errno = %d\n", errno);
1335
                        exit(1);
1336
                }
1337
  
1338
        // Close file
1339
        fclose(pFile);
1340
}
1341

    
1342
void SaveEncodedFrame(Frame* frame, uint8_t *video_outbuf)
1343
{
1344
        static FILE* pFile = NULL;
1345
        
1346
        pFile=fopen("yuv_data/streamer_out.mpeg4", "ab");
1347
        fwrite(frame, sizeof(Frame), 1, pFile);
1348
        fwrite(video_outbuf, frame->size, 1, pFile);
1349
        fclose(pFile);
1350
}