Statistics
| Branch: | Revision:

chunker-player / chunker_streamer / chunker_streamer.c @ 45d5641e

History | View | Annotate | Download (44.9 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 DEBUG
15
#define DEBUG_AUDIO_FRAMES  false
16
#define DEBUG_VIDEO_FRAMES  false
17
#define DEBUG_CHUNKER false
18
#define DEBUG_ANOMALIES true
19
#define DEBUG_TIMESTAMPING false
20
#include "dbg.h"
21

    
22
#define STREAMER_MAX(a,b) ((a>b)?(a):(b))
23
#define STREAMER_MIN(a,b) ((a<b)?(a):(b))
24

    
25
//#define DISPLAY_PSNR
26
#define GET_PSNR(x) ((x==0) ? 0 : (-10.0*log(x)/log(10)))
27

    
28
ChunkerMetadata *cmeta = NULL;
29
int seq_current_chunk = 1; //chunk numbering starts from 1; HINT do i need more bytes?
30

    
31
#define AUDIO_CHUNK 0
32
#define VIDEO_CHUNK 1
33

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

    
42
int video_record_count = 0;
43
int savedVideoFrames = 0;
44
long int firstSavedVideoFrame = 0;
45
int ChunkerStreamerTestMode = 0;
46

    
47
int pts_anomaly_threshold = -1;
48
int newtime_anomaly_threshold = -1;
49
bool timebank = false;
50
char *outside_world_url = NULL;
51

    
52
int gop_size = 25;
53
int max_b_frames = 3;
54
bool vcopy = false;
55

    
56
long delay_audio = 0; //delay audio by x millisec
57

    
58
// Constant number of frames per chunk
59
int chunkFilledFramesStrategy(ExternalChunk *echunk, int chunkType)
60
{
61
        dcprintf(DEBUG_CHUNKER, "CHUNKER: check if frames num %d == %d in chunk %d\n", echunk->frames_num, cmeta->framesPerChunk[chunkType], echunk->seq);
62
        if(echunk->frames_num == cmeta->framesPerChunk[chunkType])
63
                return 1;
64

    
65
        return 0;
66
}
67

    
68
// Constant size. Note that for now each chunk will have a size just greater or equal than the required value
69
// It can be considered as constant size.
70
int chunkFilledSizeStrategy(ExternalChunk *echunk, int chunkType)
71
{
72
        dcprintf(DEBUG_CHUNKER, "CHUNKER: check if chunk size %d >= %d in chunk %d\n", echunk->payload_len, cmeta->targetChunkSize, echunk->seq);
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
                {"audio_stream", required_argument, 0, 0},
215
                {"video_stream", required_argument, 0, 0},
216
                {0, 0, 0, 0}
217
        };
218
        /* `getopt_long' stores the option index here. */
219
        int option_index = 0, c;
220
        int mandatories = 0;
221
        while ((c = getopt_long (argc, argv, "i:a:v:A:V:s:lop:q:tF:g:b:d:x:", long_options, &option_index)) != -1)
222
        {
223
                switch (c) {
224
                        case 0: //for long options
225
                                if( strcmp( "audio_stream", long_options[option_index].name ) == 0 ) { audioStream = atoi(optarg); }
226
                                if( strcmp( "video_stream", long_options[option_index].name ) == 0 ) { videoStream = atoi(optarg); }
227
                                break;
228
                        case 'i':
229
                                sprintf(av_input, "%s", optarg);
230
                                mandatories++;
231
                                break;
232
                        case 'a':
233
                                sscanf(optarg, "%d", &audio_bitrate);
234
                                mandatories++;
235
                                break;
236
                        case 'v':
237
                                sscanf(optarg, "%d", &video_bitrate);
238
                                mandatories++;
239
                                break;
240
                        case 'A':
241
                                audio_codec = strdup(optarg);
242
                                break;
243
                        case 'V':
244
                                video_codec = strdup(optarg);
245
                                break;
246
                        case 's':
247
                                sscanf(optarg, "%dx%d", &dest_width, &dest_height);
248
                                break;
249
                        case 'l':
250
                                live_source = 1;
251
                                break;
252
                        case 'o':
253
                                offset_av = 1;
254
                                break;
255
                        case 't':
256
                                ChunkerStreamerTestMode = 1;
257
                                break;
258
                        case 'p':
259
                                sscanf(optarg, "%d", &pts_anomaly_threshold);
260
                                break;
261
                        case 'q':
262
                                sscanf(optarg, "%d", &newtime_anomaly_threshold);
263
                                break;
264
                        case 'F':
265
                                outside_world_url = strdup(optarg);
266
                                break;
267
                        case 'g':
268
                                sscanf(optarg, "%d", &gop_size);
269
                                break;
270
                        case 'b':
271
                                sscanf(optarg, "%d", &max_b_frames);
272
                                break;
273
                        case 'd':
274
                                sscanf(optarg, "%ld", &delay_audio);
275
                                break;
276
                        case 'x':
277
                                codec_options = strdup(optarg);
278
                                break;
279
                        default:
280
                                print_usage(argc, argv);
281
                                return -1;
282
                }
283
        }
284
        
285
        if(mandatories < 3) 
286
        {
287
                print_usage(argc, argv);
288
                return -1;
289
        }
290

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

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

    
321
        // Register all formats and codecs
322
        av_register_all();
323

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

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

    
336
        // Dump information about file onto standard error
337
        av_dump_format(pFormatCtx, 0, av_input, 0);
338

    
339
        // Find the video and audio stream numbers
340
        for(i=0; i<pFormatCtx->nb_streams; i++) {
341
                if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_VIDEO && videoStream<0) {
342
                        videoStream=i;
343
                }
344
                if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_AUDIO && audioStream<0) {
345
                        audioStream=i;
346
                }
347
        }
348

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

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

    
356
        fprintf(stderr, "INIT: Video stream has id : %d\n",videoStream);
357
        fprintf(stderr, "INIT: Audio stream has id : %d\n",audioStream);
358

    
359

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

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

    
372
        // Figure out size
373
        dest_width = (dest_width > 0) ? dest_width : pCodecCtx->width;
374
        dest_height = (dest_height > 0) ? dest_height : pCodecCtx->height;
375

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

    
388
        pCodecCtxEnc=avcodec_alloc_context();
389
        pCodecCtxEnc->codec_type = CODEC_TYPE_VIDEO;
390
        pCodecCtxEnc->codec_id = pCodecEnc->id;
391

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

    
410
        //some generic quality tuning
411
        pCodecCtxEnc->mb_decision = FF_MB_DECISION_RD;
412

    
413
        //some rate control parameters for streaming, taken from ffserver.c
414
        {
415
        /* Bitrate tolerance is less for streaming */
416
        AVCodecContext *av = pCodecCtxEnc;
417
        if (av->bit_rate_tolerance == 0)
418
            av->bit_rate_tolerance = FFMAX(av->bit_rate / 4,
419
                      (int64_t)av->bit_rate*av->time_base.num/av->time_base.den);
420
        //if (av->qmin == 0)
421
        //    av->qmin = 3;
422
        //if (av->qmax == 0)
423
        //    av->qmax = 31;
424
        //if (av->max_qdiff == 0)
425
        //    av->max_qdiff = 3;
426
        //av->qcompress = 0.5;
427
        //av->qblur = 0.5;
428

    
429
        //if (!av->nsse_weight)
430
        //    av->nsse_weight = 8;
431

    
432
        //av->frame_skip_cmp = FF_CMP_DCTMAX;
433
        //if (!av->me_method)
434
        //    av->me_method = ME_EPZS;
435
        //av->rc_buffer_aggressivity = 1.0;
436

    
437
        //if (!av->rc_eq)
438
        //    av->rc_eq = "tex^qComp";
439
        //if (!av->i_quant_factor)
440
        //    av->i_quant_factor = -0.8;
441
        //if (!av->b_quant_factor)
442
        //    av->b_quant_factor = 1.25;
443
        //if (!av->b_quant_offset)
444
        //    av->b_quant_offset = 1.25;
445
        if (!av->rc_max_rate)
446
            av->rc_max_rate = av->bit_rate * 2;
447

    
448
        if (av->rc_max_rate && !av->rc_buffer_size) {
449
            av->rc_buffer_size = av->rc_max_rate;
450
        }
451
        }
452
        //end of code taken fromffserver.c
453

    
454
  switch (pCodecEnc->id) {
455
    case CODEC_ID_H264 :
456
        // Fast Profile
457
        // libx264-fast.ffpreset preset 
458
        pCodecCtxEnc->coder_type = FF_CODER_TYPE_AC; // coder = 1 -> enable CABAC
459
        pCodecCtxEnc->flags |= CODEC_FLAG_LOOP_FILTER; // flags=+loop -> deblock
460
        pCodecCtxEnc->me_cmp|= 1; // cmp=+chroma, where CHROMA = 1
461
        pCodecCtxEnc->partitions |= X264_PART_I8X8|X264_PART_I4X4|X264_PART_P8X8|X264_PART_B8X8;        // partitions=+parti8x8+parti4x4+partp8x8+partb8x8
462
        pCodecCtxEnc->me_method=ME_HEX; // me_method=hex
463
        pCodecCtxEnc->me_subpel_quality = 6; // subq=7
464
        pCodecCtxEnc->me_range = 16; // me_range=16
465
        //pCodecCtxEnc->gop_size = 250; // g=250
466
        //pCodecCtxEnc->keyint_min = 25; // keyint_min=25
467
        pCodecCtxEnc->scenechange_threshold = 40; // sc_threshold=40
468
        pCodecCtxEnc->i_quant_factor = 0.71; // i_qfactor=0.71
469
        pCodecCtxEnc->b_frame_strategy = 1; // b_strategy=1
470
        pCodecCtxEnc->qcompress = 0.6; // qcomp=0.6
471
        pCodecCtxEnc->qmin = 10; // qmin=10
472
        pCodecCtxEnc->qmax = 51; // qmax=51
473
        pCodecCtxEnc->max_qdiff = 4; // qdiff=4
474
        //pCodecCtxEnc->max_b_frames = 3; // bf=3
475
        pCodecCtxEnc->refs = 2; // refs=3
476
        //pCodecCtxEnc->directpred = 1; // directpred=1
477
        pCodecCtxEnc->directpred = 3; // directpred=1 in preset -> "directpred", "direct mv prediction mode - 0 (none), 1 (spatial), 2 (temporal), 3 (auto)"
478
        //pCodecCtxEnc->trellis = 1; // trellis=1
479
        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
480
        pCodecCtxEnc->weighted_p_pred = 2; // wpredp=2
481

    
482
        // libx264-main.ffpreset preset
483
        //pCodecCtxEnc->flags2|=CODEC_FLAG2_8X8DCT;
484
        //pCodecCtxEnc->flags2^=CODEC_FLAG2_8X8DCT; // flags2=-dct8x8
485
        //pCodecCtxEnc->crf = 22;
486

    
487
#ifdef STREAMER_X264_USE_SSIM
488
        pCodecCtxEnc->flags2 |= CODEC_FLAG2_SSIM;
489
#endif
490

    
491
        //pCodecCtxEnc->weighted_p_pred=2; //maps wpredp=2; weighted prediction analysis method
492
        // pCodecCtxEnc->rc_min_rate = 0;
493
        // pCodecCtxEnc->rc_max_rate = video_bitrate*2;
494
        // pCodecCtxEnc->rc_buffer_size = 0;
495
        break;
496
    case CODEC_ID_MPEG4 :
497
        break;
498
    default:
499
        fprintf(stderr, "INIT: Unsupported OUT VIDEO codec: %s!\n", video_codec);
500
  }
501

    
502
  if ((av_set_options_string(pCodecCtxEnc, codec_options, "=", ",")) < 0) {
503
    fprintf(stderr, "Error parsing options string: '%s'\n", codec_options);
504
    exit(1);
505
  }
506

    
507
        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);
508
 }
509

    
510
        if(pCodec==NULL) {
511
                fprintf(stderr, "INIT: Unsupported IN VIDEO pcodec!\n");
512
                return -1; // Codec not found
513
        }
514
        if(!vcopy && pCodecEnc==NULL) {
515
                fprintf(stderr, "INIT: Unsupported OUT VIDEO pcodecenc!\n");
516
                return -1; // Codec not found
517
        }
518
        if(avcodec_open(pCodecCtx, pCodec)<0) {
519
                fprintf(stderr, "INIT: could not open IN VIDEO codec\n");
520
                return -1; // Could not open codec
521
        }
522
        if(!vcopy && avcodec_open(pCodecCtxEnc, pCodecEnc)<0) {
523
                fprintf(stderr, "INIT: could not open OUT VIDEO codecEnc\n");
524
                return -1; // Could not open codec
525
        }
526
        if(audioStream!=-1) {
527
                //setup audio output encoder
528
                aCodecCtxEnc = avcodec_alloc_context();
529
                aCodecCtxEnc->bit_rate = audio_bitrate; //256000
530
                aCodecCtxEnc->sample_fmt = SAMPLE_FMT_S16;
531
                aCodecCtxEnc->sample_rate = aCodecCtx->sample_rate;
532
                aCodecCtxEnc->channels = aCodecCtx->channels;
533
                fprintf(stderr, "INIT: AUDIO bitrate OUT:%d sample_rate:%d channels:%d\n", aCodecCtxEnc->bit_rate, aCodecCtxEnc->sample_rate, aCodecCtxEnc->channels);
534

    
535
                // Find the decoder for the audio stream
536
                aCodec = avcodec_find_decoder(aCodecCtx->codec_id);
537
                aCodecEnc = avcodec_find_encoder_by_name(audio_codec);
538
                if(aCodec==NULL) {
539
                        fprintf(stderr,"INIT: Unsupported acodec!\n");
540
                        return -1;
541
                }
542
                if(aCodecEnc==NULL) {
543
                        fprintf(stderr,"INIT: Unsupported acodecEnc!\n");
544
                        return -1;
545
                }
546
        
547
                if(avcodec_open(aCodecCtx, aCodec)<0) {
548
                        fprintf(stderr, "INIT: could not open IN AUDIO codec\n");
549
                        return -1; // Could not open codec
550
                }
551
                if(avcodec_open(aCodecCtxEnc, aCodecEnc)<0) {
552
                        fprintf(stderr, "INIT: could not open OUT AUDIO codec\n");
553
                        return -1; // Could not open codec
554
                }
555
        }
556
        else {
557
                fprintf(stderr,"INIT: NO AUDIO TRACK IN INPUT FILE\n");
558
        }
559

    
560
        // Allocate audio in and out buffers
561
        samples = (int16_t *)av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
562
        if(samples == NULL) {
563
                fprintf(stderr, "INIT: Memory error alloc audio samples!!!\n");
564
                return -1;
565
        }
566
        audio_outbuf_size = STREAMER_MAX_AUDIO_BUFFER_SIZE;
567
        audio_outbuf = av_malloc(audio_outbuf_size);
568
        if(audio_outbuf == NULL) {
569
                fprintf(stderr, "INIT: Memory error alloc audio_outbuf!!!\n");
570
                return -1;
571
        }
572

    
573
        // Allocate video in frame and out buffer
574
        pFrame=avcodec_alloc_frame();
575
        scaledFrame=avcodec_alloc_frame();
576
        if(pFrame==NULL || scaledFrame == NULL) {
577
                fprintf(stderr, "INIT: Memory error alloc video frame!!!\n");
578
                return -1;
579
        }
580
        video_outbuf_size = STREAMER_MAX_VIDEO_BUFFER_SIZE;
581
        video_outbuf = av_malloc(video_outbuf_size);
582
        int scaledFrame_buf_size = avpicture_get_size( PIX_FMT_YUV420P, dest_width, dest_height);
583
        uint8_t* scaledFrame_buffer = (uint8_t *) av_malloc( scaledFrame_buf_size * sizeof( uint8_t ) );
584
        avpicture_fill( (AVPicture*) scaledFrame, scaledFrame_buffer, PIX_FMT_YUV420P, dest_width, dest_height);
585
        if(!video_outbuf || !scaledFrame_buffer) {
586
                fprintf(stderr, "INIT: Memory error alloc video_outbuf!!!\n");
587
                return -1;
588
        }
589

    
590
        //allocate Napa-Wine transport
591
        frame = (Frame *)malloc(sizeof(Frame));
592
        if(!frame) {
593
                fprintf(stderr, "INIT: Memory error alloc Frame!!!\n");
594
                return -1;
595
        }
596
        //create an empty first video chunk
597
        chunk = (ExternalChunk *)malloc(sizeof(ExternalChunk));
598
        if(!chunk) {
599
                fprintf(stderr, "INIT: Memory error alloc chunk!!!\n");
600
                return -1;
601
        }
602
        chunk->data = NULL;
603
        chunk->seq = 0;
604
        //initChunk(chunk, &seq_current_chunk); if i init them now i get out of sequence
605
        dcprintf(DEBUG_CHUNKER, "INIT: chunk video %d\n", chunk->seq);
606
        //create empty first audio chunk
607
        chunkaudio = (ExternalChunk *)malloc(sizeof(ExternalChunk));
608
        if(!chunkaudio) {
609
                fprintf(stderr, "INIT: Memory error alloc chunkaudio!!!\n");
610
                return -1;
611
        }
612
  chunkaudio->data=NULL;
613
        chunkaudio->seq = 0;
614
        //initChunk(chunkaudio, &seq_current_chunk);
615
        dcprintf(DEBUG_CHUNKER, "INIT: chunk audio %d\n", chunkaudio->seq);
616

    
617
#ifdef HTTPIO
618
        /* initialize the HTTP chunk pusher */
619
        initChunkPusher(); //TRIPLO
620
#endif
621

    
622
        long sleep=0;
623
        struct timeval now_tv;
624
        struct timeval tmp_tv;
625
        long long lateTime = 0;
626
        long long maxAudioInterval = 0;
627
        long long maxVDecodeTime = 0;
628
//        unsigned char lastIFrameDistance = 0;
629

    
630
#ifdef TCPIO
631
        static char peer_ip[16];
632
        static int peer_port;
633
        int res = sscanf(outside_world_url, "tcp://%15[0-9.]:%d", peer_ip, &peer_port);
634
        if (res < 2) {
635
                fprintf(stderr,"error parsing output url: %s\n", outside_world_url);
636
                return -2;
637
        }
638
        
639
        initTCPPush(peer_ip, peer_port);
640
#endif
641
#ifdef UDPIO
642
        static char peer_ip[16];
643
        static int peer_port;
644
        int res = sscanf(outside_world_url, "udp://%15[0-9.]:%d", peer_ip, &peer_port);
645
        if (res < 2) {
646
                fprintf(stderr,"error parsing output url: %s\n", outside_world_url);
647
                return -2;
648
        }
649
        
650
        initUDPPush(peer_ip, peer_port);
651
#endif
652
        
653
        char videotrace_filename[255];
654
        char psnr_filename[255];
655
        sprintf(videotrace_filename, "yuv_data/videotrace.log");
656
        sprintf(psnr_filename, "yuv_data/psnrtrace.log");
657
        FILE* videotrace = fopen(videotrace_filename, "w");
658
        FILE* psnrtrace = fopen(psnr_filename, "w");
659

    
660
        //main loop to read from the input file
661
        while((av_read_frame(pFormatCtx, &packet)>=0) && !quit)
662
        {
663
                //detect if a strange number of anomalies is occurring
664
                if(ptsvideo1 < 0 || ptsvideo1 > packet.dts || ptsaudio1 < 0 || ptsaudio1 > packet.dts) {
665
                        pts_anomalies_counter++;
666
                        dcprintf(DEBUG_ANOMALIES, "READLOOP: pts BASE anomaly detected number %d\n", pts_anomalies_counter);
667
                        if(pts_anomaly_threshold >=0 && live_source) { //reset just in case of live source
668
                                if(pts_anomalies_counter > pts_anomaly_threshold) {
669
                                        dcprintf(DEBUG_ANOMALIES, "READLOOP: too many pts BASE anomalies. resetting pts base\n");
670
                                        av_free_packet(&packet);
671
                                        goto close;
672
                                }
673
                        }
674
                }
675

    
676
                //newTime_video and _audio are in usec
677
                //if video and audio stamps differ more than 5sec
678
                if( newTime_video - newTime_audio > 5000000 || newTime_video - newTime_audio < -5000000 ) {
679
                        newtime_anomalies_counter++;
680
                        dcprintf(DEBUG_ANOMALIES, "READLOOP: NEWTIME audio video differ anomaly detected number %d\n", newtime_anomalies_counter);
681
                }
682

    
683
                if(newtime_anomaly_threshold >=0 && newtime_anomalies_counter > newtime_anomaly_threshold) {
684
                        if(live_source) { //restart just in case of live source
685
                                dcprintf(DEBUG_ANOMALIES, "READLOOP: too many NEGATIVE TIMESTAMPS anomalies. Restarting.\n");
686
                                av_free_packet(&packet);
687
                                goto close;
688
                        }
689
                }
690

    
691
                // Is this a packet from the video stream?
692
                if(packet.stream_index==videoStream)
693
                {
694
                        if(!live_source)
695
                        {
696
                                if(audioStream != -1) { //take this "time bank" method into account only if we have audio track
697
                                        // lateTime < 0 means a positive time account that can be used to decode video frames
698
                                        // if (lateTime + maxVDecodeTime) >= 0 then we may have a negative time account after video transcoding
699
                                        // therefore, it's better to skip the frame
700
                                        if(timebank && (lateTime+maxVDecodeTime) >= 0)
701
                                        {
702
                                                dcprintf(DEBUG_ANOMALIES, "\n\n\t\t************************* SKIPPING VIDEO FRAME %ld ***********************************\n\n", sleep);
703
                                                av_free_packet(&packet);
704
                                                continue;
705
                                        }
706
                                }
707
                        }
708
                        
709
                        gettimeofday(&tmp_tv, NULL);
710
                        
711
                        //decode the video packet into a raw pFrame
712
                        if(avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished, &packet)>0)
713
                        {
714
                                // usleep(5000);
715
                                dcprintf(DEBUG_VIDEO_FRAMES, "VIDEOin pkt: dts %lld pts %lld pts-dts %lld\n", packet.dts, packet.pts, packet.pts-packet.dts );
716
                                dcprintf(DEBUG_VIDEO_FRAMES, "VIDEOdecode: pkt_dts %lld pkt_pts %lld frame.pts %lld\n", pFrame->pkt_dts, pFrame->pkt_pts, pFrame->pts);
717
                                dcprintf(DEBUG_VIDEO_FRAMES, "VIDEOdecode intype %d%s\n", pFrame->pict_type, pFrame->key_frame ? " (key)" : "");
718
                                pFrame->pts = av_rescale_q(pFrame->pkt_pts, pFormatCtx->streams[videoStream]->time_base, pCodecCtxEnc->time_base);
719
                                if(frameFinished)
720
                                { // it must be true all the time else error
721
                                
722
                                        frame->number = ++contFrameVideo;
723

    
724
#ifdef VIDEO_DEINTERLACE
725
                                if (!vcopy) {
726
                                        avpicture_deinterlace(
727
                                                (AVPicture*) pFrame,
728
                                                (const AVPicture*) pFrame,
729
                                                pCodecCtxEnc->pix_fmt,
730
                                                pCodecCtxEnc->width,
731
                                                pCodecCtxEnc->height);
732
                                }
733
#endif
734

    
735
                                        dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO: finished frame %d dts %lld pts %lld\n", frame->number, packet.dts, packet.pts);
736
                                        if(frame->number==0) {
737
                                                if(packet.dts==AV_NOPTS_VALUE)
738
                                                {
739
                                                        //a Dts with a noPts value is troublesome case for delta calculation based on Dts
740
                                                        contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0);
741
                                                        av_free_packet(&packet);
742
                                                        continue;
743
                                                }
744
                                                last_pkt_dts = packet.dts;
745
                                                newTime = 0;
746
                                        }
747
                                        else {
748
                                                if(packet.dts!=AV_NOPTS_VALUE) {
749
                                                        delta_video = packet.dts-last_pkt_dts;
750
                                                        last_pkt_dts = packet.dts;
751
                                                }
752
                                                else if(delta_video==0)
753
                                                {
754
                                                        //a Dts with a noPts value is troublesome case for delta calculation based on Dts
755
                                                        contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0);
756
                                                        av_free_packet(&packet);
757
                                                        continue;
758
                                                }
759
                                        }
760
                                        dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO: deltavideo : %d\n", (int)delta_video);
761

    
762
                                        if(vcopy) {
763
                                                video_frame_size = packet.size;
764
                                                if (video_frame_size > video_outbuf_size) {
765
                                                        fprintf(stderr, "VIDEO: error, outbuf too small, SKIPPING\n");;
766
                                                        av_free_packet(&packet);
767
                                                        continue;
768
                                                } else {
769
                                                        memcpy(video_outbuf, packet.data, video_frame_size);
770
                                                }
771
                                        } else if(pCodecCtx->height != pCodecCtxEnc->height || pCodecCtx->width != pCodecCtxEnc->width) {
772
//                                                static AVPicture pict;
773
                                                static struct SwsContext *img_convert_ctx = NULL;
774
                                                
775
                                                pFrame->pict_type = 0;
776
                                                if(img_convert_ctx == NULL)
777
                                                {
778
                                                        img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, PIX_FMT_YUV420P, dest_width, dest_height, PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);
779
                                                        if(img_convert_ctx == NULL) {
780
                                                                fprintf(stderr, "Cannot initialize the conversion context!\n");
781
                                                                exit(1);
782
                                                        }
783
                                                }
784
                                                sws_scale(img_convert_ctx, pFrame->data, pFrame->linesize, 0, pCodecCtx->height, scaledFrame->data, scaledFrame->linesize);
785
                                                scaledFrame->pts = pFrame->pts;
786
                                                scaledFrame->pict_type = 0;
787
                                                video_frame_size = avcodec_encode_video(pCodecCtxEnc, video_outbuf, video_outbuf_size, scaledFrame);
788
                                        } else {
789
                                                pFrame->pict_type = 0;
790
                                                video_frame_size = avcodec_encode_video(pCodecCtxEnc, video_outbuf, video_outbuf_size, pFrame);
791
                                        }
792

    
793
                                        if(video_frame_size <= 0)
794
                                        {
795
                                                contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0);
796
                                                av_free_packet(&packet);
797
                                                continue;
798
                                        }
799

    
800
                                        if(!vcopy && pCodecCtxEnc->coded_frame) {
801
                                                dcprintf(DEBUG_VIDEO_FRAMES, "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);
802
                                                dcprintf(DEBUG_VIDEO_FRAMES, "VIDEOout: outtype: %d%s\n", pCodecCtxEnc->coded_frame->pict_type, pCodecCtxEnc->coded_frame->key_frame ? " (key)" : "");
803
                                        }
804
#ifdef DISPLAY_PSNR
805
                                        static double ist_psnr = 0;
806
                                        static double cum_psnr = 0;
807
                                        static int psnr_samples = 0;
808
                                        if(!vcopy && pCodecCtxEnc->coded_frame) {
809
                                                if(pCodecCtxEnc->flags&CODEC_FLAG_PSNR) {
810
                                                        ist_psnr = GET_PSNR(pCodecCtxEnc->coded_frame->error[0]/(pCodecCtxEnc->width*pCodecCtxEnc->height*255.0*255.0));
811
                                                        psnr_samples++;
812
                                                        cum_psnr += ist_psnr;
813
                                                        fprintf(stderr, "PSNR: ist %.4f avg: %.4f\n", ist_psnr, cum_psnr / (double)psnr_samples);
814
                                                }
815
                                        }
816
#endif
817

    
818
                                        //use pts if dts is invalid
819
                                        if(pCodecCtxEnc->coded_frame->pts!=AV_NOPTS_VALUE)
820
                                                target_pts = av_rescale_q(pCodecCtxEnc->coded_frame->pts, pCodecCtxEnc->time_base, pFormatCtx->streams[videoStream]->time_base);
821
                                        else
822
                                        {
823
                                                fprintf(stderr, "VIDEOout: pts error\n");
824
                                                exit(1);
825
                                        }
826

    
827
                                        if(offset_av)
828
                                        {
829
                                                if(FirstTimeVideo && target_pts>0) {
830
                                                        ptsvideo1 = target_pts;
831
                                                        FirstTimeVideo = 0;
832
                                                        dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO: SET PTS BASE OFFSET %lld\n", ptsvideo1);
833
                                                }
834
                                        }
835
                                        else //we want to compensate audio and video offset for this source
836
                                        {
837
                                                if(FirstTimeVideo && target_pts>0) {
838
                                                        //maintain the offset between audio pts and video pts
839
                                                        //because in case of live source they have the same numbering
840
                                                        if(ptsaudio1 > 0) //if we have already seen some audio frames...
841
                                                                ptsvideo1 = ptsaudio1;
842
                                                        else
843
                                                                ptsvideo1 = target_pts;
844
                                                        FirstTimeVideo = 0;
845
                                                        dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO LIVE: SET PTS BASE OFFSET %lld\n", ptsvideo1);
846
                                                }
847
                                        }
848
                                        //compute the new video timestamp in milliseconds
849
                                        if(frame->number>0) {
850
                                                newTime = (target_pts - ptsvideo1) * 1000 * pFormatCtx->streams[videoStream]->time_base.num / pFormatCtx->streams[videoStream]->time_base.den;
851
                                                // store timestamp in useconds for next frame sleep
852
                                                newTime_video = newTime*1000;
853
                                        }
854
                                        dcprintf(DEBUG_TIMESTAMPING, "VIDEO: NEWTIMESTAMP %ld\n", newTime);
855
                                        if(newTime<0) {
856
                                                dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO: SKIPPING FRAME\n");
857
                                                newtime_anomalies_counter++;
858
                                                dcprintf(DEBUG_ANOMALIES, "READLOOP: NEWTIME negative video timestamp anomaly detected number %d\n", newtime_anomalies_counter);
859
                                                contFrameVideo = STREAMER_MAX(contFrameVideo-1, 0);
860
                                                av_free_packet(&packet);
861
                                                continue; //SKIP THIS FRAME, bad timestamp
862
                                        }
863
                                        
864
                                        //~ printf("pCodecCtxEnc->error[0]=%lld\n", pFrame->error[0]);
865
        
866
                                        frame->timestamp.tv_sec = (long long)newTime/1000;
867
                                        frame->timestamp.tv_usec = newTime%1000;
868
                                        frame->size = video_frame_size;
869
                                        /* pict_type maybe 1 (I), 2 (P), 3 (B), 5 (AUDIO)*/
870
                                        frame->type = vcopy ? pFrame->pict_type : (unsigned char)pCodecCtxEnc->coded_frame->pict_type;
871

    
872
                                        if (!vcopy) dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO: original codec frame number %d vs. encoded %d vs. packed %d\n", pCodecCtx->frame_number, pCodecCtxEnc->frame_number, frame->number);
873
                                        if (!vcopy) dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO: duration %d timebase %d %d container timebase %d\n", (int)packet.duration, pCodecCtxEnc->time_base.den, pCodecCtxEnc->time_base.num, pCodecCtx->time_base.den);
874

    
875
#ifdef YUV_RECORD_ENABLED
876
                                        if(!vcopy && ChunkerStreamerTestMode)
877
                                        {
878
                                                if(videotrace)
879
                                                        fprintf(videotrace, "%d %d %d\n", frame->number, pFrame->pict_type, frame->size);
880

    
881
                                                if(pCodecCtx->height != pCodecCtxEnc->height || pCodecCtx->width != pCodecCtxEnc->width)
882
                                                        SaveFrame(scaledFrame, dest_width, dest_height);
883
                                                else
884
                                                        SaveFrame(pFrame, dest_width, dest_height);
885

    
886
                                                ++savedVideoFrames;
887
                                                SaveEncodedFrame(frame, video_outbuf);
888

    
889
                                                if(!firstSavedVideoFrame)
890
                                                        firstSavedVideoFrame = frame->number;
891
                                                
892
                                                char tmp_filename[255];
893
                                                sprintf(tmp_filename, "yuv_data/streamer_out_context.txt");
894
                                                FILE* tmp = fopen(tmp_filename, "w");
895
                                                if(tmp)
896
                                                {
897
                                                        fprintf(tmp, "width = %d\nheight = %d\ntotal_frames_saved = %d\ntotal_frames_decoded = %d\nfirst_frame_number = %ld\nlast_frame_number = %d\n"
898
                                                                ,dest_width, dest_height
899
                                                                ,savedVideoFrames, savedVideoFrames, firstSavedVideoFrame, frame->number);
900
                                                        fclose(tmp);
901
                                                }
902
                                        }
903
#endif
904

    
905
                                        dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO: encapsulated frame size:%d type:%d\n", frame->size, frame->type);
906
                                        dcprintf(DEBUG_VIDEO_FRAMES, "VIDEO: timestamped sec %d usec:%d\n", frame->timestamp.tv_sec, frame->timestamp.tv_usec);
907
                                        //contFrameVideo++; //lets increase the numbering of the frames
908

    
909
                                        if(update_chunk(chunk, frame, video_outbuf) == -1) {
910
                                                fprintf(stderr, "VIDEO: unable to update chunk %d. Exiting.\n", chunk->seq);
911
                                                exit(-1);
912
                                        }
913

    
914
                                        if(chunkFilled(chunk, VIDEO_CHUNK)) { // is chunk filled using current strategy?
915
                                                //calculate priority
916
                                                chunk->priority /= chunk->frames_num;
917

    
918
                                                //SAVE ON FILE
919
                                                //saveChunkOnFile(chunk);
920
                                                //Send the chunk to an external transport/player
921
                                                sendChunk(chunk);
922
                                                dcprintf(DEBUG_CHUNKER, "VIDEO: sent chunk video %d, prio:%f\n", chunk->seq, chunk->priority);
923
                                                chunk->seq = 0; //signal that we need an increase
924
                                                //initChunk(chunk, &seq_current_chunk);
925
                                        }
926

    
927
                                        //compute how long it took to encode video frame
928
                                        gettimeofday(&now_tv, NULL);
929
                                        long long usec = (now_tv.tv_sec-tmp_tv.tv_sec)*1000000;
930
                                        usec+=(now_tv.tv_usec-tmp_tv.tv_usec);
931
                                        if(usec > maxVDecodeTime)
932
                                                maxVDecodeTime = usec;
933

    
934
                                        //we DONT have an audio track, so we compute timings and determine
935
                                        //how much time we have to sleep at next VIDEO frame taking
936
                                        //also into account how much time was needed to encode the current
937
                                        //video frame
938
                                        //all this in case the video source is not live, i.e. not self-timing
939
                                        //and only in case there is no audio track
940
                                        if(audioStream == -1) {
941
                                                if(!live_source) {
942
                                                        if(newTime_prev != 0) {
943
                                                                //how much delay between video frames ideally
944
                                                                long long maxDelay = newTime_video - newTime_prev;
945
                                                                sleep = (maxDelay - usec);
946
                                                                dcprintf(DEBUG_ANOMALIES,"\tmaxDelay=%ld\n", ((long)maxDelay));
947
                                                                dcprintf(DEBUG_ANOMALIES,"\tlast video frame interval=%ld; sleep time=%ld\n", ((long)usec), ((long)sleep));
948
                                                        }
949
                                                        else
950
                                                                sleep = 0;
951

    
952
                                                        //update and store counters
953
                                                        newTime_prev = newTime_video;
954

    
955
                                                        //i can also sleep now instead of at the beginning of
956
                                                        //the next frame because in this case we only have video
957
                                                        //frames, hence it would immediately be the next thing to do
958
                                                        if(sleep > 0) {
959
                                                                dcprintf(DEBUG_ANOMALIES, "\n\tREADLOOP: going to sleep for %ld microseconds\n", sleep);
960
                                                                usleep(sleep);
961
                                                        }
962

    
963
                                                }
964
                                        }
965

    
966
                                }
967
                        }
968
                }
969
                else if(packet.stream_index==audioStream)
970
                {
971
                        if(sleep > 0)
972
                        {
973
                                dcprintf(DEBUG_ANOMALIES, "\n\tREADLOOP: going to sleep for %ld microseconds\n", sleep);
974
                                usleep(sleep);
975
                        }
976
                        
977
                        audio_data_size = AVCODEC_MAX_AUDIO_FRAME_SIZE;
978
                        //decode the audio packet into a raw audio source buffer
979
                        if(avcodec_decode_audio3(aCodecCtx, samples, &audio_data_size, &packet)>0)
980
                        {
981
                                dcprintf(DEBUG_AUDIO_FRAMES, "\n-------AUDIO FRAME\n");
982
                                dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO: newTimeaudioSTART : %lf\n", (double)(packet.pts)*av_q2d(pFormatCtx->streams[audioStream]->time_base));
983
                                if(audio_data_size>0) {
984
                                        dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO: datasizeaudio:%d\n", audio_data_size);
985
                                        /* if a frame has been decoded, output it */
986
                                        //fwrite(samples, 1, audio_data_size, outfileaudio);
987
                                }
988
                                else {
989
                                        av_free_packet(&packet);
990
                                        continue;
991
                                }
992
        
993
                                audio_frame_size = avcodec_encode_audio(aCodecCtxEnc, audio_outbuf, audio_data_size, samples);
994
                                if(audio_frame_size <= 0) {
995
                                        av_free_packet(&packet);
996
                                        continue;
997
                                }
998
                                
999
                                frame->number = contFrameAudio;
1000

    
1001
                                if(frame->number==0) {
1002
                                        if(packet.dts==AV_NOPTS_VALUE) {
1003
                                                av_free_packet(&packet);
1004
                                                continue;
1005
                                        }
1006
                                        last_pkt_dts_audio = packet.dts;
1007
                                        newTime = 0;
1008
                                }
1009
                                else {
1010
                                        if(packet.dts!=AV_NOPTS_VALUE) {
1011
                                                delta_audio = packet.dts-last_pkt_dts_audio;
1012
                                                last_pkt_dts_audio = packet.dts;
1013
                                        }
1014
                                        else if(delta_audio==0) {
1015
                                                av_free_packet(&packet);
1016
                                                continue;
1017
                                        }
1018
                                }
1019
                                dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO: original codec frame number %d vs. encoded %d vs. packed %d\n", aCodecCtx->frame_number, aCodecCtxEnc->frame_number, frame->number);
1020
                                //use pts if dts is invalid
1021
                                if(packet.dts!=AV_NOPTS_VALUE)
1022
                                        target_pts = packet.dts;
1023
                                else if(packet.pts!=AV_NOPTS_VALUE) {
1024
                                        target_pts = packet.pts;
1025
                                } else  {
1026
                                        av_free_packet(&packet);
1027
                                        continue;
1028
                                }
1029

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

    
1066
                                frame->timestamp.tv_sec = (unsigned int)(newTime + delay_audio)/1000;
1067
                                frame->timestamp.tv_usec = (newTime + delay_audio)%1000;
1068
                                frame->size = audio_frame_size;
1069
                                frame->type = 5; // 5 is audio type
1070
                                dcprintf(DEBUG_AUDIO_FRAMES, "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);
1071
                                dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO: timestamp sec:%d usec:%d\n", frame->timestamp.tv_sec, frame->timestamp.tv_usec);
1072
                                dcprintf(DEBUG_AUDIO_FRAMES, "AUDIO: deltaaudio %lld\n", delta_audio);        
1073
                                contFrameAudio++;
1074

    
1075
                                if(update_chunk(chunkaudio, frame, audio_outbuf) == -1) {
1076
                                        fprintf(stderr, "AUDIO: unable to update chunk %d. Exiting.\n", chunkaudio->seq);
1077
                                        exit(-1);
1078
                                }
1079
                                //set priority
1080
                                chunkaudio->priority = 1;
1081

    
1082
                                if(chunkFilled(chunkaudio, AUDIO_CHUNK)) {
1083
                                        // is chunk filled using current strategy?
1084
                                        //SAVE ON FILE
1085
                                        //saveChunkOnFile(chunkaudio);
1086
                                        //Send the chunk to an external transport/player
1087
                                        sendChunk(chunkaudio);
1088
                                        dcprintf(DEBUG_CHUNKER, "AUDIO: just sent chunk audio %d\n", chunkaudio->seq);
1089
                                        chunkaudio->seq = 0; //signal that we need an increase
1090
                                        //initChunk(chunkaudio, &seq_current_chunk);
1091
                                }
1092

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

    
1104
                                                gettimeofday(&now_tv, NULL);
1105
                                                long long usec = (now_tv.tv_sec-lastAudioSent.tv_sec)*1000000;
1106
                                                usec+=(now_tv.tv_usec-lastAudioSent.tv_usec);
1107

    
1108
                                                if(usec > maxAudioInterval)
1109
                                                        maxAudioInterval = usec;
1110

    
1111
                                                lateTime -= (maxDelay - usec);
1112
                                                dcprintf(DEBUG_ANOMALIES,"\tmaxDelay=%ld, maxAudioInterval=%ld\n", ((long)maxDelay), ((long) maxAudioInterval));
1113
                                                dcprintf(DEBUG_ANOMALIES,"\tlast audio frame interval=%ld; lateTime=%ld\n", ((long)usec), ((long)lateTime));
1114

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

    
1123
                                        newTime_prev = newTime_audio;
1124
                                        gettimeofday(&lastAudioSent, NULL);
1125
                                }
1126
                        }
1127
                }
1128
                dcprintf(DEBUG_CHUNKER,"Free the packet that was allocated by av_read_frame\n");
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
                dcprintf(DEBUG_CHUNKER, "CHUNKER: SENDING LAST VIDEO CHUNK\n");
1144
                chunk->seq = 0; //signal that we need an increase just in case we will restart
1145
        }
1146
        if(chunkaudio->seq != 0 && chunkaudio->frames_num>0) {
1147
                //SAVE ON FILE     
1148
                //saveChunkOnFile(chunkaudio);
1149
                //Send the chunk via http to an external transport/player
1150
                sendChunk(chunkaudio);
1151
                dcprintf(DEBUG_CHUNKER, "CHUNKER: SENDING LAST AUDIO CHUNK\n");
1152
                chunkaudio->seq = 0; //signal that we need an increase just in case we will restart
1153
        }
1154

    
1155
#ifdef HTTPIO
1156
        /* finalize the HTTP chunk pusher */
1157
        finalizeChunkPusher();
1158
#endif
1159

    
1160
        free(chunk);
1161
        free(chunkaudio);
1162
        free(frame);
1163
        av_free(video_outbuf);
1164
        av_free(scaledFrame_buffer);
1165
        av_free(audio_outbuf);
1166
        free(cmeta);
1167

    
1168
        // Free the YUV frame
1169
        av_free(pFrame);
1170
        av_free(scaledFrame);
1171
        av_free(samples);
1172
  
1173
        // Close the codec
1174
        if (!vcopy) avcodec_close(pCodecCtx);
1175
        if (!vcopy) avcodec_close(pCodecCtxEnc);
1176

    
1177
        if(audioStream!=-1) {
1178
                avcodec_close(aCodecCtx);
1179
                avcodec_close(aCodecCtxEnc);
1180
        }
1181
  
1182
        // Close the video file
1183
        av_close_input_file(pFormatCtx);
1184

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

    
1224
                goto restart;
1225
        }
1226

    
1227
#ifdef TCPIO
1228
        finalizeTCPChunkPusher();
1229
#endif
1230

    
1231
        return 0;
1232
}
1233

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

    
1238
        //moving temp pointer to encode Frame on the wire
1239
        uint8_t *tempdata = NULL;
1240

    
1241
        if(chunk->seq == 0) {
1242
                initChunk(chunk, &seq_current_chunk);
1243
        }
1244
        //add frame priority to chunk priority (to be normalized later on)
1245
        chunk->priority += frame->type + 1; // I:2, P:3, B:4
1246

    
1247
        //HINT on malloc
1248
        chunk->data = (uint8_t *)realloc(chunk->data, sizeof(uint8_t)*(chunk->payload_len + frame->size + sizeFrameHeader));
1249
        if(!chunk->data)  {
1250
                fprintf(stderr, "Memory error in chunk!!!\n");
1251
                return -1;
1252
        }
1253
        chunk->frames_num++; // number of frames in the current chunk
1254

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

    
1275
         //insert the new frame data
1276
        memcpy(chunk->data + chunk->payload_len + sizeFrameHeader, outbuf, frame->size);
1277
        chunk->payload_len += frame->size + sizeFrameHeader; // update payload length
1278
        //chunk lenght is updated just prior to pushing it out because
1279
        //the chunk header len is better calculated there
1280
        //chunk->len = sizeChunkHeader + chunk->payload_len; // update overall length
1281

    
1282
        //update timestamps
1283
        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) {
1284
                                                chunk->start_time.tv_sec = frame->timestamp.tv_sec;
1285
                                                chunk->start_time.tv_usec = frame->timestamp.tv_usec;
1286
        }
1287
        
1288
        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) {
1289
                                                chunk->end_time.tv_sec = frame->timestamp.tv_sec;
1290
                                                chunk->end_time.tv_usec = frame->timestamp.tv_usec;
1291
        }
1292
        return 0;
1293
}
1294

    
1295
void SaveFrame(AVFrame *pFrame, int width, int height)
1296
{
1297
        FILE *pFile;
1298
        int  y;
1299

    
1300
         // Open file
1301
        char tmp_filename[255];
1302
        sprintf(tmp_filename, "yuv_data/streamer_out.yuv");
1303
        pFile=fopen(tmp_filename, "ab");
1304
        if(pFile==NULL)
1305
                return;
1306

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

    
1336
void SaveEncodedFrame(Frame* frame, uint8_t *video_outbuf)
1337
{
1338
        static FILE* pFile = NULL;
1339
        
1340
        pFile=fopen("yuv_data/streamer_out.mpeg4", "ab");
1341
        fwrite(frame, sizeof(Frame), 1, pFile);
1342
        fwrite(video_outbuf, frame->size, 1, pFile);
1343
        fclose(pFile);
1344
}