Statistics
| Branch: | Revision:

chunker-player / chunker_player / player_core.c @ 7245fc85

History | View | Annotate | Download (50.1 KB)

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

    
9
#include <libavcodec/avcodec.h>
10
#include <libavformat/avformat.h>
11
#include <libswscale/swscale.h>
12
#include "libav-compat.h"
13

    
14
#include <stdio.h>
15
#include <unistd.h>
16
#include "external_chunk_transcoding.h"
17
#include "frame.h"
18
#include <SDL.h>
19
#include <SDL_thread.h>
20
#include <SDL_mutex.h>
21
// #include <SDL_ttf.h>
22
// #include <SDL_image.h>
23
#include <SDL_video.h>
24
#include <assert.h>
25
#include <time.h>
26

    
27
#include "player_stats.h"
28
#include "player_defines.h"
29
#include "chunker_player.h"
30
#include "player_gui.h"
31
#include "player_core.h"
32
#include "player_stats.h"
33

    
34
#define MAX(A,B)    ((A)>(B) ? (A) : (B))
35
#define MIN(A,B)    ((A)<(B) ? (A) : (B))
36

    
37
SDL_Overlay *YUVOverlay;
38

    
39
typedef struct PacketQueue {
40
        AVPacketList *first_pkt;
41
        AVPacket *minpts_pkt;
42
        AVPacketList *last_pkt;
43
        int nb_packets;
44
        int size;
45
        SDL_mutex *mutex;
46
        short int queueType;
47
        int last_frame_extracted; //HINT THIS SHOULD BE MORE THAN 4 BYTES
48
        //total frames lost, as seen from the queue, since last queue init
49
        int total_lost_frames;
50
        long cumulative_bitrate;
51
        long cumulative_samples;
52

    
53
        SHistory PacketHistory;
54
        
55
        double density;
56
        char stats_message[255];
57
} PacketQueue;
58

    
59
AVCodecContext  *aCodecCtx;
60
SDL_Thread *video_thread;
61
SDL_Thread *stats_thread;
62
uint8_t *outbuf_audio;
63
// short int QueueFillingMode=1;
64
short int QueueStopped;
65
ThreadVal VideoCallbackThreadParams;
66

    
67
int AudioQueueOffset;
68
PacketQueue audioq;
69
PacketQueue videoq;
70
AVPacket AudioPkt, VideoPkt;
71
int AVPlaying;
72
int CurrentAudioFreq;
73
int CurrentAudioSamples;
74
uint8_t CurrentAudioSilence;
75

    
76
int GotSigInt;
77

    
78
long long DeltaTime;
79
short int FirstTimeAudio, FirstTime;
80

    
81
int dimAudioQ;
82
float deltaAudioQ;
83
float deltaAudioQError;
84

    
85
int SaveYUV;
86
char YUVFileName[256];
87
int SaveLoss;
88

    
89
char VideoFrameLossRateLogFilename[256];
90
char VideoFrameSkipRateLogFilename[256];
91

    
92
long int decoded_vframes;
93
long int LastSavedVFrame;
94

    
95
void SaveFrame(AVFrame *pFrame, int width, int height);
96
int VideoCallback(void *valthread);
97
int CollectStatisticsThread(void *params);
98
void AudioCallback(void *userdata, Uint8 *stream, int len);
99
void PacketQueueClearStats(PacketQueue *q);
100

    
101
//int lastCheckedVideoFrame = -1;
102
long int last_video_frame_extracted = -1;
103

    
104
int timeval_subtract(struct timeval* x, struct timeval* y, struct timeval* result)
105
{
106
  // Perform the carry for the later subtraction by updating y.
107
  if (x->tv_usec < y->tv_usec)
108
  {
109
    int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
110
    y->tv_usec -= 1000000 * nsec;
111
    y->tv_sec += nsec;
112
  }
113
  if (x->tv_usec - y->tv_usec > 1000000)
114
  {
115
    int nsec = (x->tv_usec - y->tv_usec) / 1000000;
116
    y->tv_usec += 1000000 * nsec;
117
    y->tv_sec -= nsec;
118
  }
119

    
120
  // Compute the time remaining to wait. tv_usec is certainly positive.
121
  result->tv_sec = x->tv_sec - y->tv_sec;
122
  result->tv_usec = x->tv_usec - y->tv_usec;
123

    
124
  // Return 1 if result is negative.
125
  return x->tv_sec < y->tv_sec;
126
}
127

    
128

    
129
void PacketQueueInit(PacketQueue *q, short int Type)
130
{
131
#ifdef DEBUG_QUEUE
132
        fprintf(stderr,"QUEUE: INIT BEGIN: NPackets=%d Type=%s\n", q->nb_packets, (q->queueType==AUDIO) ? "AUDIO" : "VIDEO");
133
#endif
134
        memset(q,0,sizeof(PacketQueue));
135
        q->mutex = SDL_CreateMutex();
136
        QueueFillingMode=1;
137
        q->queueType=Type;
138
        q->last_frame_extracted = -1;
139
        q->first_pkt= NULL;
140
        q->minpts_pkt= NULL;
141
        //q->last_pkt = NULL;
142
        q->nb_packets = 0;
143
        q->size = 0;
144
        q->density= 0.0;
145
        FirstTime = 1;
146
        FirstTimeAudio = 1;
147
        //init up statistics
148
        
149
        q->PacketHistory.Mutex = SDL_CreateMutex();
150
        PacketQueueClearStats(q);
151
        
152
#ifdef DEBUG_QUEUE
153
        fprintf(stderr,"QUEUE: INIT END: NPackets=%d Type=%s\n", q->nb_packets, (q->queueType==AUDIO) ? "AUDIO" : "VIDEO");
154
#endif
155
}
156

    
157
void PacketQueueReset(PacketQueue *q)
158
{
159
        AVPacketList *tmp,*tmp1;
160
#ifdef DEBUG_QUEUE
161
        fprintf(stderr,"QUEUE: RESET BEGIN: NPackets=%d Type=%s LastExtr=%d\n", q->nb_packets, (q->queueType==AUDIO) ? "AUDIO" : "VIDEO", q->last_frame_extracted);
162
#endif
163
        SDL_LockMutex(q->mutex);
164

    
165
        tmp = q->first_pkt;
166
        while(tmp) {
167
                tmp1 = tmp;
168
                tmp = tmp->next;
169
                av_free_packet(&(tmp1->pkt));
170
                av_free(tmp1);
171
#ifdef DEBUG_QUEUE
172
                fprintf(stderr,"F ");
173
#endif
174
                q->PacketHistory.LostCount++;
175
        }
176
#ifdef DEBUG_QUEUE
177
        fprintf(stderr,"\n");
178
#endif
179

    
180
        QueueFillingMode=1;
181
        q->last_frame_extracted = -1;
182
        
183
        // on queue reset do not reset loss count
184
        // (loss count reset is done on queue init, ie channel switch)
185
        q->density=0.0;
186
        q->first_pkt= NULL;
187
        q->minpts_pkt= NULL;
188
        //q->last_pkt = NULL;
189
        q->nb_packets = 0;
190
        q->size = 0;
191
        FirstTime = 1;
192
        FirstTimeAudio = 1;
193
        //clean up statistics
194
        PacketQueueClearStats(q);
195
#ifdef DEBUG_QUEUE
196
        fprintf(stderr,"QUEUE: RESET END: NPackets=%d Type=%s LastExtr=%d\n", q->nb_packets, (q->queueType==AUDIO) ? "AUDIO" : "VIDEO", q->last_frame_extracted);
197
#endif
198
        SDL_UnlockMutex(q->mutex);
199
}
200

    
201
void PacketQueueClearStats(PacketQueue *q)
202
{
203
        sprintf(q->stats_message, "%s", "\n");
204
        int i;
205
        memset((void*)q->PacketHistory.History, 0, sizeof(SHistoryElement)*QUEUE_HISTORY_SIZE);
206
        for(i=0; i<QUEUE_HISTORY_SIZE; i++)
207
        {
208
                q->PacketHistory.History[i].Statistics.LastIFrameDistance = -1;
209
                q->PacketHistory.History[i].Status = -1;
210
        }
211
        q->PacketHistory.Index = q->PacketHistory.LogIndex = 0;
212
        q->PacketHistory.Index = q->PacketHistory.QoEIndex = 0;
213
        q->PacketHistory.LostCount = q->PacketHistory.PlayedCount = q->PacketHistory.SkipCount = 0;
214
}
215

    
216
int ChunkerPlayerCore_PacketQueuePut(PacketQueue *q, AVPacket *pkt)
217
{
218
        //~ fprintf(stderr,"\tSTREAM_INDEX=%d\n", pkt->stream_index);
219
        short int skip = 0;
220
        AVPacketList *pkt1, *tmp, *prevtmp;
221
        int res = 0;
222

    
223
        if(q->nb_packets > queue_filling_threshold*QUEUE_MAX_GROW_FACTOR) {
224
#ifdef DEBUG_QUEUE
225
                fprintf(stderr,"QUEUE: PUT i have TOO MANY packets %d Type=%s, RESETTING\n", q->nb_packets, (q->queueType==AUDIO) ? "AUDIO" : "VIDEO");
226
#endif
227
                PacketQueueReset(q);
228
        }
229

    
230
        //make a copy of the incoming packet
231
        if(av_dup_packet(pkt) < 0) {
232
#ifdef DEBUG_QUEUE
233
                fprintf(stderr,"QUEUE: PUT in Queue cannot duplicate in packet        : NPackets=%d Type=%s\n",q->nb_packets, (q->queueType==AUDIO) ? "AUDIO" : "VIDEO");
234
#endif
235
                return -1;
236
        }
237
        pkt1 = av_malloc(sizeof(AVPacketList));
238

    
239
        if(!pkt1) {
240
                av_free_packet(pkt);
241
                return -1;
242
        }
243
        pkt1->pkt = *pkt;
244
        pkt1->next = NULL;
245
        
246
        static time_t last_auto_switch = 0;
247

    
248
        if(
249
                (pkt->stream_index < last_video_frame_extracted)
250
                && (pkt->stream_index <= RESTART_FRAME_NUMBER_THRESHOLD)
251
                && ((time(NULL) - last_auto_switch) > 10)
252
        )
253
        {
254
                fprintf(stderr,"file streaming loop detected => re-tune channel and start grabbing statistics\n");
255
                last_auto_switch = time(NULL);
256
                SDL_LockMutex(q->mutex);
257
                ReTune(&(Channels[SelectedChannel]));
258
                SDL_UnlockMutex(q->mutex);
259
        }
260

    
261
        else
262
        {
263
                SDL_LockMutex(q->mutex);
264

    
265
                // INSERTION SORT ALGORITHM
266
                // before inserting pkt, check if pkt.stream_index is <= current_extracted_frame.
267
                if(pkt->stream_index > q->last_frame_extracted)
268
                {
269
                        // either checking starting from the first_pkt or needed other struct like AVPacketList with next and prev....
270
                        //if (!q->last_pkt)
271
                        if(!q->first_pkt) {
272
                                q->first_pkt = pkt1;
273
                                q->last_pkt = pkt1;
274
                        }
275
                        else if(pkt->stream_index < q->first_pkt->pkt.stream_index) {
276
                                //the packet that has arrived is earlier than the first we got some time ago!
277
                                //we need to put it at the head of the queue
278
                                pkt1->next = q->first_pkt;
279
                                q->first_pkt = pkt1;
280
                        }
281
                        else {
282
                                tmp = q->first_pkt;
283
                                while(tmp->pkt.stream_index < pkt->stream_index) {
284
                                        prevtmp = tmp;
285
                                        tmp = tmp->next;
286

    
287
                                        if(!tmp) {
288
                                                break;
289
                                        }
290
                                }
291
                                if(tmp && tmp->pkt.stream_index == pkt->stream_index) {
292
                                        //we already have a frame with that index
293
                                        skip = 1;
294
#ifdef DEBUG_QUEUE
295
                                        fprintf(stderr,"%s QUEUE: PUT: we already have frame with index %d, skipping\n", ((q->queueType == AUDIO) ? "AUDIO" : "VIDEO"), pkt->stream_index);
296
#endif
297
                                }
298
                                else {
299
                                        prevtmp->next = pkt1;
300
                                        pkt1->next = tmp;
301
                                        if(pkt1->next == NULL)
302
                                                q->last_pkt = pkt1;
303
                                }
304
                                //q->last_pkt->next = pkt1; // It was uncommented when not insertion sort
305
                        }
306
                        if(skip == 0) {
307
                                //q->last_pkt = pkt1;
308
                                q->nb_packets++;
309
                                q->size += pkt1->pkt.size;
310
                                if(q->nb_packets>=queue_filling_threshold && QueueFillingMode) // && q->queueType==AUDIO)
311
                                {
312
                                        QueueFillingMode=0;
313
#ifdef DEBUG_QUEUE
314
                                        fprintf(stderr,"QUEUE: PUT: FillingMode set to zero\n");
315
#endif
316
                                }
317
                                //set min
318
                                if (!q->minpts_pkt || (pkt1->pkt.pts < q->minpts_pkt->pts)) {
319
                                        q->minpts_pkt = &(pkt1->pkt);
320
                                }
321
                        }
322
                }
323
                else {
324
                        av_free_packet(&pkt1->pkt);
325
                        av_free(pkt1);
326
#ifdef DEBUG_QUEUE
327
                        fprintf(stderr,"QUEUE: PUT: NOT inserting because index %d <= last extracted %d\n", pkt->stream_index, q->last_frame_extracted);
328
#endif
329
                        res = 1;
330
                }
331
                SDL_UnlockMutex(q->mutex);
332
        }
333

    
334
        return res;
335
}
336

    
337
int OpenACodec (char *audio_codec, int sample_rate, short int audio_channels)
338
{
339
        AVCodec *aCodec;
340

    
341
        aCodecCtx = avcodec_alloc_context();
342
        //aCodecCtx->bit_rate = 64000;
343
        aCodecCtx->sample_rate = sample_rate;
344
        aCodecCtx->channels = audio_channels;
345
        aCodec = avcodec_find_decoder_by_name(audio_codec);
346
        if(!aCodec) {
347
                fprintf(stderr,"Codec not found!\n");
348
                return -1;
349
        }
350
        if(avcodec_open(aCodecCtx, aCodec)<0) {
351
                fprintf(stderr, "could not open codec\n");
352
                return -1; // Could not open codec
353
        }
354
        fprintf(stderr,"using audio Codecid: %d ",aCodecCtx->codec_id);
355
        fprintf(stderr,"samplerate: %d ",aCodecCtx->sample_rate);
356
        fprintf(stderr,"channels: %d\n",aCodecCtx->channels);
357

    
358
        return 1;
359
}
360

    
361
int OpenAudio(AVCodecContext  *aCodecCtx)
362
{
363
        SDL_AudioSpec *wanted_spec;
364
        static SDL_AudioSpec *wanted_spec_old = NULL;
365

    
366
        if (! (wanted_spec = malloc(sizeof(*wanted_spec)))) {
367
                perror("error initializing audio");
368
                return -1;
369
        }
370
        wanted_spec->freq = aCodecCtx->sample_rate;
371
        wanted_spec->format = AUDIO_S16SYS;
372
        wanted_spec->channels = aCodecCtx->channels;
373
        wanted_spec->silence = 0;
374
        wanted_spec->samples = SDL_AUDIO_BUFFER_SIZE;
375
        wanted_spec->callback = AudioCallback;
376
        wanted_spec->userdata = aCodecCtx;
377

    
378
#ifdef DEBUG_AUDIO
379
        fprintf(stderr,"wanted freq:%d\n",wanted_spec->freq);
380
        fprintf(stderr,"wanted format:%d\n",wanted_spec->format);
381
        fprintf(stderr,"wanted channels:%d\n",wanted_spec->channels);
382
        fprintf(stderr,"wanted silence:%d\n",wanted_spec->silence);
383
        fprintf(stderr,"wanted samples:%d\n",wanted_spec->samples);
384
#endif
385

    
386
        if (wanted_spec_old && 
387
           (wanted_spec->freq == wanted_spec_old->freq) &&
388
           (wanted_spec->channels == wanted_spec_old->channels)) {        //do not reinit audio if the wanted specification is the same as before
389
                return 1;
390
        }
391

    
392
        if(wanted_spec_old) {
393
                SDL_CloseAudio();
394
        }
395

    
396
        if (! (wanted_spec_old = malloc(sizeof(*wanted_spec_old)))) {
397
                perror("error initializing audio");
398
                return -1;
399
        }
400
        memcpy(wanted_spec_old, wanted_spec, sizeof(*wanted_spec));
401

    
402
        if (SDL_OpenAudio(wanted_spec,NULL)<0) {
403
                fprintf(stderr,"SDL_OpenAudio: %s\n", SDL_GetError());
404
                return -1;
405
        }
406

    
407
        CurrentAudioFreq = wanted_spec->freq;
408
        CurrentAudioSamples = wanted_spec->samples;
409
        dimAudioQ = wanted_spec->size;
410
        deltaAudioQ = (float)((float)wanted_spec->samples)*1000/wanted_spec->freq;        //in ms
411
        CurrentAudioSilence = wanted_spec->silence;
412

    
413
#ifdef DEBUG_AUDIO
414
        fprintf(stderr,"freq:%d\n",wanted_spec->freq);
415
        fprintf(stderr,"format:%d\n",wanted_spec->format);
416
        fprintf(stderr,"channels:%d\n",wanted_spec->channels);
417
        fprintf(stderr,"silence:%d\n",wanted_spec->silence);
418
        fprintf(stderr,"samples:%d\n",wanted_spec->samples);
419
        fprintf(stderr,"size:%d\n",wanted_spec->size);
420
        fprintf(stderr,"deltaAudioQ: %f\n",deltaAudioQ);
421
#endif
422

    
423
        return 1;
424
}
425

    
426
int ChunkerPlayerCore_InitAudioCodecs(char *audio_codec, int sample_rate, short int audio_channels)
427
{
428
        // some initializations
429
        QueueStopped = 0;
430
        AudioQueueOffset=0;
431
        AVPlaying = 0;
432
        GotSigInt = 0;
433
        FirstTimeAudio=1;
434
        FirstTime = 1;
435
        deltaAudioQError=0;
436

    
437

    
438
        if (OpenACodec(audio_codec, sample_rate, audio_channels) < 0) {
439
                return -1;
440
        }
441

    
442
        if (OpenAudio(aCodecCtx) < 1) {
443
                return -1;
444
        }
445

    
446
        outbuf_audio = malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
447

    
448
        //initialize the audio queue
449
        PacketQueueInit(&audioq, AUDIO);
450
        
451
        // Init audio buffers
452
        av_init_packet(&AudioPkt);
453
        //fprintf(stderr,"AVCODEC_MAX_AUDIO_FRAME_SIZE=%d\n", AVCODEC_MAX_AUDIO_FRAME_SIZE);
454
        AudioPkt.data=(uint8_t *)malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
455
        if(!AudioPkt.data) return -1;
456

    
457
        return 0;
458
}
459

    
460
int ChunkerPlayerCore_InitVideoCodecs(char *v_codec, int width, int height)
461
{
462

    
463
        memset(&VideoCallbackThreadParams, 0, sizeof(ThreadVal));
464
        
465
        VideoCallbackThreadParams.width = width;
466
        VideoCallbackThreadParams.height = height;
467
        VideoCallbackThreadParams.video_codec = strdup(v_codec);
468

    
469
        //initialize the video queue
470
        PacketQueueInit(&videoq, VIDEO);
471

    
472
        // Init video buffers
473
        av_init_packet(&VideoPkt);
474

    
475
        VideoPkt.data=(uint8_t *)malloc(width*height*3/2);
476
        if(!VideoPkt.data) return -1;
477

    
478
        return 0;
479
}
480

    
481
int ChunkerPlayerCore_InitCodecs(char *v_codec, int width, int height, char *audio_codec, int sample_rate, short int audio_channels)
482
{
483
        char audio_stats[255], video_stats[255];
484

    
485
        // Register all formats and codecs
486
        av_log_set_level(AV_LOG_WARNING);
487
        avcodec_init();
488
        av_register_all();
489

    
490
        if (ChunkerPlayerCore_InitAudioCodecs(audio_codec, sample_rate, audio_channels) < 0) {
491
                return -1;
492
        }
493

    
494
        if (ChunkerPlayerCore_InitVideoCodecs(v_codec, width, height) < 0) {
495
                return -1;
496
        }
497

    
498
        av_log_set_level(AV_LOG_FATAL);
499

    
500
        sprintf(audio_stats, "waiting for incoming audio packets...");
501
        sprintf(video_stats, "waiting for incoming video packets...");
502
        ChunkerPlayerGUI_SetStatsText(audio_stats, video_stats,qoe_led ? LED_GREEN : LED_NONE);
503
}
504

    
505
int DecodeEnqueuedAudio(AVPacket *pkt, PacketQueue *q, int* size)
506
{
507
        uint16_t *audio_bufQ = NULL;
508
        int16_t *dataQ = NULL;
509
        int data_sizeQ = AVCODEC_MAX_AUDIO_FRAME_SIZE;
510
        int lenQ;
511
        int ret = 0;
512

    
513
        //set the flag to decoded anyway        
514
        pkt->convergence_duration = -1;
515

    
516
        audio_bufQ = (uint16_t *)av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
517
        if(audio_bufQ) {
518
#ifdef DEBUG_AUDIO_BUFFER
519
                fprintf(stderr,"AUDIO_BUFFER: about to decode packet %d, size %d, data %d\n", pkt->stream_index, pkt->size, pkt->data);
520
#endif
521
                //decode the packet data
522
                lenQ = avcodec_decode_audio3(aCodecCtx, (int16_t *)audio_bufQ, &data_sizeQ, pkt);
523
                if(lenQ > 0) {
524
                        dataQ = (int16_t *)av_malloc(data_sizeQ); //this will be free later at the time of playback
525
                        if(dataQ) {
526
                                memcpy(dataQ, audio_bufQ, data_sizeQ);
527
                                if(pkt->data != NULL)
528
                                {
529
                                        //discard the old encoded bytes
530
                                        av_free(pkt->data);
531
                                }
532
                                //subtract them from queue size
533
                                q->size -= pkt->size;
534
                                *size = pkt->size;
535
                                pkt->data = (uint8_t *)dataQ;
536
                                pkt->size = data_sizeQ;
537
                                //add new size to queue size
538
                                q->size += pkt->size;
539
                                ret = 1;
540
                        }
541
                        else {
542
#ifdef DEBUG_AUDIO_BUFFER
543
                                fprintf(stderr,"AUDIO_BUFFER: cannot alloc space for decoded packet %d\n", pkt->stream_index);
544
#endif
545
                        }
546
                }
547
                else {
548
#ifdef DEBUG_AUDIO_BUFFER
549
                        fprintf(stderr,"AUDIO_BUFFER: cannot decode packet %d\n", pkt->stream_index);
550
#endif
551
                }
552
                av_free(audio_bufQ);
553
        }
554
        else {
555
#ifdef DEBUG_AUDIO_BUFFER
556
                fprintf(stderr,"AUDIO_BUFFER: cannot alloc decode buffer for packet %d\n", pkt->stream_index);
557
#endif
558
        }
559
        return ret; //problems occurred
560
}
561

    
562
/**
563
 * removes a packet from the list and returns the next
564
 * */
565
AVPacketList *RemoveFromQueue(PacketQueue *q, AVPacketList *p)
566
{
567
        AVPacketList *p1;
568

    
569
        if (q->first_pkt == p) {
570
                q->first_pkt = p->next;
571
        }
572
        if (&(p->pkt) == q->minpts_pkt) {
573
                q->minpts_pkt = NULL;
574
        }
575

    
576
        AVPacketList *retpk = p->next;
577
        q->nb_packets--;
578
        //adjust size here and not in the various cases of the dequeue
579
        q->size -= p->pkt.size;
580
        if(&p->pkt)
581
        {
582
                av_free_packet(&p->pkt);
583
        }
584
        if(p) {
585
                av_free(p);
586
        }
587

    
588
        //updating min info
589
        for (p1 = q->first_pkt; p1; p1 = p1->next) {
590
                if (!q->minpts_pkt || p1->pkt.pts < q->minpts_pkt->pts) {
591
                        q->minpts_pkt = &(p1->pkt);
592
                }
593
        }
594

    
595
        return retpk;
596
}
597

    
598
AVPacketList *SeekAndDecodePacketStartingFrom(AVPacketList *p, PacketQueue *q, int* size)
599
{
600
        while(p) {
601
                        //check if audio packet has been already decoded
602
                        if(p->pkt.convergence_duration == 0) {
603
                                //not decoded yet, try to decode it
604
                                if( !DecodeEnqueuedAudio(&(p->pkt), q, size) ) {
605
                                        //it was not possible to decode this packet, return next one
606
                                        p = RemoveFromQueue(q, p);
607
                                }
608
                                else
609
                                        return p;
610
                        }
611
                        else
612
                                return p;
613
        }
614
        return NULL;
615
}
616

    
617
int PacketQueueGet(PacketQueue *q, AVPacket *pkt, short int av, int* size)
618
{
619
        //AVPacket tmp;
620
        AVPacketList *pkt1 = NULL;
621
        int ret=-1;
622
        int SizeToCopy=0;
623
        int reqsize;
624

    
625
        SDL_LockMutex(q->mutex);
626

    
627
#ifdef DEBUG_QUEUE
628
        fprintf(stderr,"QUEUE: Get NPackets=%d Type=%s\n", q->nb_packets, (q->queueType==AUDIO) ? "AUDIO" : "VIDEO");
629
#endif
630

    
631
        if((q->queueType==AUDIO && QueueFillingMode) || QueueStopped)
632
        {
633
                SDL_UnlockMutex(q->mutex);
634
                return -1;
635
        }
636

    
637
        if(av==1) { //somebody requested an audio packet, q is the audio queue
638
                reqsize = dimAudioQ; //TODO pass this as parameter, not garanteed by SDL to be exactly dimAudioQ
639
                pkt->size = 0;
640
                pkt->dts = 0;
641
                pkt->pts = 0;
642
                //try to dequeue the first packet of the audio queue
643
                pkt1 = q->first_pkt;
644
                while (pkt->size < reqsize && pkt1 && SeekAndDecodePacketStartingFrom(pkt1, q, size)) {
645
                        AVPacketList *next = pkt1->next;        //save it here since we could delete pkt1 later
646
                        if (!pkt->dts) pkt->dts = pkt1->pkt.dts;
647
                        if (!pkt->pts) pkt->pts = pkt1->pkt.pts;
648
                        pkt->stream_index = pkt1->pkt.stream_index;
649
                        pkt->flags = 1;
650
                        pkt->pos = -1;
651
                        pkt->convergence_duration = -1;
652
                        if (pkt1->pkt.size - AudioQueueOffset <= reqsize - pkt->size) { //we need the whole packet
653
                                SizeToCopy = pkt1->pkt.size - AudioQueueOffset;        //packet might be partial
654
                                memcpy(pkt->data + pkt->size, pkt1->pkt.data + AudioQueueOffset, SizeToCopy);
655
                                pkt->size += SizeToCopy;
656
                                AudioQueueOffset = 0;
657
                                RemoveFromQueue(q, pkt1);
658
                        } else {
659
                                SizeToCopy = reqsize - pkt->size;        //partial packet remains
660
                                memcpy(pkt->data + pkt->size, pkt1->pkt.data + AudioQueueOffset, SizeToCopy);
661
                                pkt->size += SizeToCopy;
662
                                AudioQueueOffset += SizeToCopy;
663
                                pkt1->pkt.dts += SizeToCopy/(dimAudioQ/CurrentAudioSamples)/(CurrentAudioFreq/1000);
664
                                pkt1->pkt.pts += SizeToCopy/(dimAudioQ/CurrentAudioSamples)/(CurrentAudioFreq/1000);
665
                        }
666

    
667
#ifdef DEBUG_AUDIO_BUFFER
668
                        fprintf(stderr,"2: idx %d    \taqo %d    \tstc %d    \taqe %f    \tpsz %d\n", pkt1->pkt.stream_index, AudioQueueOffset, SizeToCopy, deltaAudioQError, pkt1->pkt.size);
669
#endif
670

    
671
                        //update index of last frame extracted
672
                        //ChunkerPlayerStats_UpdateAudioLossHistory(&(q->PacketHistory), pkt->stream_index, q->last_frame_extracted);
673
                        q->last_frame_extracted = pkt->stream_index;
674

    
675
                        pkt1 = next;
676
                }
677
                ret = 1; //TODO: check some conditions
678
        } else { //somebody requested a video packet, q is the video queue
679
                pkt1 = q->first_pkt;
680
                if(pkt1) {
681
#ifdef DEBUG_QUEUE_DEEP
682
                        fprintf(stderr,"  AV not 1\n");
683
#endif
684
                        pkt->size = pkt1->pkt.size;
685
                        pkt->dts = pkt1->pkt.dts;
686
                        pkt->pts = pkt1->pkt.pts;
687
                        pkt->stream_index = pkt1->pkt.stream_index;
688
                        pkt->flags = pkt1->pkt.flags;
689
                        pkt->pos = pkt1->pkt.pos;
690
                        pkt->convergence_duration = pkt1->pkt.convergence_duration;
691
                        //*pkt = pkt1->pkt;
692
                        
693
                        if((pkt->data != NULL) && (pkt1->pkt.data != NULL))
694
                                memcpy(pkt->data, pkt1->pkt.data, pkt1->pkt.size);
695
                                
696
                        //HINT SEE BEFORE q->size -= pkt1->pkt.size;
697
                        RemoveFromQueue(q, pkt1);
698

    
699
                        ret = 1;
700
                        
701
                        ChunkerPlayerStats_UpdateVideoLossHistory(&(q->PacketHistory), pkt->stream_index, q->last_frame_extracted);
702
                        
703
                        //update index of last frame extracted
704
                        q->last_frame_extracted = pkt->stream_index;
705
                        last_video_frame_extracted = q->last_frame_extracted;
706
                }
707
#ifdef DEBUG_QUEUE
708
                else {
709
                        fprintf(stderr,"  VIDEO pk1 NULL!!!!\n");
710
                }
711
#endif
712
        }
713

    
714
        if(q->nb_packets==0 && q->queueType==AUDIO) {
715
                QueueFillingMode=1;
716
#ifdef DEBUG_QUEUE
717
                fprintf(stderr,"QUEUE: Get FillingMode ON\n");
718
#endif
719
        }
720
#ifdef DEBUG_QUEUE
721
        fprintf(stderr,"QUEUE: Get Last %s Frame Extracted = %d\n", (q->queueType==AUDIO) ? "AUDIO" : "VIDEO", q->last_frame_extracted);
722
#endif
723

    
724
        SDL_UnlockMutex(q->mutex);
725
        return ret;
726
}
727

    
728
int AudioDecodeFrame(uint8_t *audio_buf, int buf_size) {
729
        //struct timeval now;
730
        int audio_pkt_size = 0;
731
        int compressed_size = 0;
732
        long long Now;
733
        short int DecodeAudio=0, SkipAudio=0;
734
        //int len1, data_size;
735

    
736
        //gettimeofday(&now,NULL);
737
        //Now = (now.tv_sec)*1000+now.tv_usec/1000;
738
        Now=(long long)SDL_GetTicks();
739

    
740
        if(QueueFillingMode || QueueStopped)
741
        {
742
                //SDL_LockMutex(timing_mutex);
743
                FirstTimeAudio=1;
744
                FirstTime = 1;
745
                //SDL_UnlockMutex(timing_mutex);
746
                return -1;
747
        }
748

    
749
        if((FirstTime==1 || FirstTimeAudio==1) && audioq.size>0) {
750
                if(audioq.first_pkt->pkt.pts>0)
751
                {
752
                        //SDL_LockMutex(timing_mutex);
753
                        DeltaTime=Now-(long long)(audioq.first_pkt->pkt.pts);
754
                        FirstTimeAudio = 0;
755
                        FirstTime = 0;
756
                        //SDL_UnlockMutex(timing_mutex);
757
#ifdef DEBUG_AUDIO 
758
                         fprintf(stderr,"AUDIO: audio_decode_frame - DeltaTimeAudio=%lld\n",DeltaTime);
759
#endif
760
                }
761
        }
762

    
763
#ifdef DEBUG_AUDIO 
764
        if(audioq.first_pkt)
765
        {
766
                fprintf(stderr,"AUDIO: audio_decode_frame - Syncro params: Delta:%lld Now:%lld pts=%lld pts+Delta=%lld ",(long long)DeltaTime,Now,(long long)audioq.first_pkt->pkt.pts,(long long)audioq.first_pkt->pkt.pts+DeltaTime);
767
                fprintf(stderr,"AUDIO: QueueLen=%d ",(int)audioq.nb_packets);
768
                fprintf(stderr,"AUDIO: QueueSize=%d\n",(int)audioq.size);
769
        }
770
        else
771
                fprintf(stderr,"AUDIO: audio_decode_frame - Empty queue\n");
772
#endif
773

    
774
        if(audioq.nb_packets>0)
775
        {
776
                if((double)audioq.first_pkt->pkt.pts+DeltaTime<Now+deltaAudioQ)        //too late ... TODO: figure out the right number
777
                {
778
                        SkipAudio = 1;
779
                        DecodeAudio = 0;
780
                }
781
                else if((double)audioq.first_pkt->pkt.pts+DeltaTime>=Now+deltaAudioQ &&        //TODO: figure out the right number
782
                        (double)audioq.first_pkt->pkt.pts+DeltaTime<=Now+deltaAudioQ+3*deltaAudioQ) {        //TODO: how much in future? On some systems, SDL asks for more buffers in a raw
783
                                SkipAudio = 0;
784
                                DecodeAudio = 1;
785
                }
786
        }
787
        
788
        while(SkipAudio==1 && audioq.size>0)
789
        {
790
                SkipAudio = 0;
791
#ifdef DEBUG_AUDIO
792
                 fprintf(stderr,"AUDIO: skipaudio: queue size=%d\n",audioq.size);
793
#endif
794
                if(PacketQueueGet(&audioq,&AudioPkt,1, &compressed_size) < 0) {
795
                        return -1;
796
                }
797
                if(audioq.first_pkt)
798
                {
799
                        ChunkerPlayerStats_UpdateAudioSkipHistory(&(audioq.PacketHistory), AudioPkt.stream_index, compressed_size);
800
                        
801
                        if((double)audioq.first_pkt->pkt.pts+DeltaTime<Now+deltaAudioQ)        //TODO: figure out the right number
802
                        {
803
                                SkipAudio = 1;
804
                                DecodeAudio = 0;
805
                        }
806
                        else if((double)audioq.first_pkt->pkt.pts+DeltaTime>=Now+deltaAudioQ &&        //TODO: figure out the right number
807
                                (double)audioq.first_pkt->pkt.pts+DeltaTime<=Now+deltaAudioQ+3*deltaAudioQ) {        //TODO: how much in future?
808
                                        SkipAudio = 0;
809
                                        DecodeAudio = 1;
810
                        }
811
                }
812
        }
813
        if(DecodeAudio==1) {
814
                if(PacketQueueGet(&audioq,&AudioPkt,1, &compressed_size) < 0) {
815
                        return -1;
816
                }
817
#ifdef DEBUG_SYNC
818
                fprintf(stderr, "AUDIO delay =%lld ms\n",(long long)AudioPkt.pts+DeltaTime-Now);
819
#endif
820
                memcpy(audio_buf,AudioPkt.data,AudioPkt.size);
821
                audio_pkt_size = AudioPkt.size;
822
#ifdef DEBUG_AUDIO
823
                 fprintf(stderr,"AUDIO: Decode audio\n");
824
#endif
825

    
826
                ChunkerPlayerStats_UpdateAudioPlayedHistory(&(audioq.PacketHistory), AudioPkt.stream_index, compressed_size);
827
        }
828

    
829
        return audio_pkt_size;
830
}
831

    
832
// Render a Frame to a YUV Overlay. Note that the Overlay is already bound to an SDL Surface
833
// Note that width, height would not be needed in new ffmpeg versions where this info is contained in AVFrame
834
// see: [FFmpeg-devel] [PATCH] lavc: add width and height fields to AVFrame
835
int RenderFrame2Overlay(AVFrame *pFrame, int frame_width, int frame_height, SDL_Overlay *YUVOverlay)
836
{
837
        AVPicture pict;
838
        static struct SwsContext *img_convert_ctx = NULL;        //if the function is used for more streams, this could be made part of some context passed as a parameter (to optimize performance)
839

    
840
                                        if(SDL_LockYUVOverlay(YUVOverlay) < 0) {
841
                                                return -1;
842
                                        }
843

    
844
                                        pict.data[0] = YUVOverlay->pixels[0];
845
                                        pict.data[1] = YUVOverlay->pixels[2];
846
                                        pict.data[2] = YUVOverlay->pixels[1];
847

    
848
                                        pict.linesize[0] = YUVOverlay->pitches[0];
849
                                        pict.linesize[1] = YUVOverlay->pitches[2];
850
                                        pict.linesize[2] = YUVOverlay->pitches[1];
851

    
852
                                        img_convert_ctx = sws_getCachedContext(img_convert_ctx, frame_width, frame_height, PIX_FMT_YUV420P, YUVOverlay->w, YUVOverlay->h, PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);
853
                                        if(img_convert_ctx == NULL) {
854
                                                fprintf(stderr, "Cannot initialize the conversion context!\n");
855
                                                exit(1);
856
                                        }
857

    
858
                                        // let's draw the data (*yuv[3]) on a SDL screen (*screen)
859
                                        sws_scale(img_convert_ctx, pFrame->data, pFrame->linesize, 0, frame_height, pict.data, pict.linesize);
860
                                        SDL_UnlockYUVOverlay(YUVOverlay);
861

    
862
        return 0;
863
}
864

    
865
// Render a YUV Overlay to the specified Rect of the Surface. Note that the Overlay is already bound to an SDL Surface.
866
int RenderOverlay2Rect(SDL_Overlay *YUVOverlay, SDL_Rect *Rect)
867
{
868

    
869
                                        // Lock SDL_yuv_overlay
870
                                        if(SDL_MUSTLOCK(MainScreen)) {
871
                                                if(SDL_LockSurface(MainScreen) < 0) {
872
                                                        return -1;
873
                                                }
874
                                        }
875

    
876
                                        // Show, baby, show!
877
                                        SDL_LockMutex(OverlayMutex);
878
                                        SDL_DisplayYUVOverlay(YUVOverlay, Rect);
879
                                        SDL_UnlockMutex(OverlayMutex);
880

    
881
                                        if(SDL_MUSTLOCK(MainScreen)) {
882
                                                SDL_UnlockSurface(MainScreen);
883
                                        }
884

    
885
        return 0;
886

    
887
}
888

    
889

    
890
int VideoCallback(void *valthread)
891
{
892
        //AVPacket pktvideo;
893
        AVCodecContext  *pCodecCtx;
894
        AVCodec         *pCodec;
895
        AVFrame         *pFrame;
896
        int frameFinished;
897
        long long Now;
898
        long long Last = 0;
899
        short int SkipVideo, DecodeVideo;
900
        uint64_t last_pts = 0;
901
        long long decode_delay = 0;
902
        int queue_size_checked = 0;
903
        
904
#ifdef SAVE_YUV
905
        static AVFrame* lastSavedFrameBuffer = NULL;
906
        
907
        if(!lastSavedFrameBuffer)
908
                lastSavedFrameBuffer = (AVFrame*) malloc(sizeof(AVFrame));
909
#endif
910

    
911
        //double frame_rate = 0.0,time_between_frames=0.0;
912
        //struct timeval now;
913

    
914
        //int wait_for_sync = 1;
915
        ThreadVal *tval;
916
        tval = (ThreadVal *)valthread;
917

    
918
        //frame_rate = tval->framerate;
919
        //time_between_frames = 1.e6 / frame_rate;
920
        //gettimeofday(&time_now,0);
921

    
922
        //frecon = fopen("recondechunk.mpg","wb");
923

    
924
        //setup video decoder
925
        pCodec = avcodec_find_decoder_by_name(tval->video_codec);
926
        if (pCodec) {
927
                fprintf(stderr, "INIT: Setting VIDEO codecID to: %d\n",pCodec->id);
928
        } else {
929
                fprintf(stderr, "INIT: Unknown VIDEO codec: %s!\n", tval->video_codec);
930
                return -1; // Codec not found
931
        }
932

    
933
        pCodecCtx=avcodec_alloc_context();
934
        pCodecCtx->codec_type = CODEC_TYPE_VIDEO;
935
        //pCodecCtx->debug = FF_DEBUG_DCT_COEFF;
936
        pCodecCtx->codec_id = pCodec->id;
937

    
938
        //pCodecCtx->bit_rate = 400000;
939
        // resolution must be a multiple of two
940
        pCodecCtx->width = tval->width;//176;//352;
941
        pCodecCtx->height = tval->height;//144;//288;
942

    
943
        // frames per second
944
        //pCodecCtx->time_base = (AVRational){1,25};
945
        //pCodecCtx->gop_size = 10; // emit one intra frame every ten frames
946
        //pCodecCtx->max_b_frames=1;
947
        pCodecCtx->pix_fmt = PIX_FMT_YUV420P;
948
        pCodec=avcodec_find_decoder(pCodecCtx->codec_id);
949

    
950
        if(pCodec==NULL) {
951
                fprintf(stderr, "Unsupported codec!\n");
952
                return -1; // Codec not found
953
        }
954
        if(avcodec_open(pCodecCtx, pCodec) < 0) {
955
                fprintf(stderr, "could not open codec\n");
956
                return -1; // Could not open codec
957
        }
958
        pFrame=avcodec_alloc_frame();
959
        if(pFrame==NULL) {
960
                fprintf(stderr,"Memory error!!!\n");
961
                return -1;
962
        }
963
        
964
#ifdef DEBUG_VIDEO
965
         fprintf(stderr,"VIDEO: video_callback entering main cycle\n");
966
#endif
967

    
968
        while(AVPlaying && !quit) {
969

    
970
                if(QueueFillingMode || QueueStopped)
971
                {
972
                        //SDL_LockMutex(timing_mutex);
973
                        FirstTime = 1;
974
                        //SDL_UnlockMutex(timing_mutex);
975
                        usleep(5000);
976
                        continue;
977
                }
978

    
979
                DecodeVideo = 0;
980
                SkipVideo = 0;
981
                Now=(long long)SDL_GetTicks();
982
                if(FirstTime==1 && videoq.size>0) {
983
                        if(videoq.first_pkt->pkt.pts>0)
984
                        {
985
                                //SDL_LockMutex(timing_mutex);
986
                                DeltaTime=Now-(long long)videoq.first_pkt->pkt.pts;
987
                                FirstTime = 0;
988
                                FirstTimeAudio = 0;
989
                                //SDL_UnlockMutex(timing_mutex);
990
                        }
991
#ifdef DEBUG_VIDEO 
992
                         fprintf(stderr,"VIDEO: VideoCallback - DeltaTimeAudio=%lld\n",DeltaTime);
993
#endif
994
                }
995

    
996
#ifdef DEBUG_VIDEO 
997
                if(videoq.first_pkt)
998
                {
999
                        fprintf(stderr,"VIDEO: VideoCallback - Syncro params: Delta:%lld Now:%lld pts=%lld pts+Delta=%lld ",(long long)DeltaTime,Now,(long long)videoq.first_pkt->pkt.pts,(long long)videoq.first_pkt->pkt.pts+DeltaTime);
1000
                        fprintf(stderr,"VIDEO: Index=%d ", (int)videoq.first_pkt->pkt.stream_index);
1001
                        fprintf(stderr,"VIDEO: QueueLen=%d ", (int)videoq.nb_packets);
1002
                        fprintf(stderr,"VIDEO: QueueSize=%d\n", (int)videoq.size);
1003
                }
1004
                else
1005
                        fprintf(stderr,"VIDEO: VideoCallback - Empty queue\n");
1006
#endif
1007

    
1008
#ifdef DEBUG_VIDEO
1009
                fprintf(stderr,"VIDEO: skipvideo:%d decodevideo:%d\n",SkipVideo,DecodeVideo);
1010
#endif
1011
//                        ChunkerPlayerStats_UpdateVideoSkipHistory(&(videoq.PacketHistory), VideoPkt.stream_index, pFrame->pict_type, VideoPkt.size, pFrame);
1012

    
1013
                if(videoq.nb_packets>0) {
1014
                        if (!queue_size_checked && videoq.last_pkt->pkt.pts - videoq.first_pkt->pkt.pts < decode_delay) {        //queue too short
1015
#ifdef DEBUG_SYNC
1016
                                fprintf(stderr, "VIDEO queue too short,diff(%lld) < decode_delay(%lld), increasing delta from \n",videoq.last_pkt->pkt.pts - videoq.first_pkt->pkt.pts, decode_delay, DeltaTime);
1017
#endif
1018
                                DeltaTime += decode_delay - (videoq.last_pkt->pkt.pts - videoq.first_pkt->pkt.pts);
1019
                                queue_size_checked = 1;        //make sure we do not increase the delay several times bacause of the same frame
1020
                        }
1021
                        if (videoq.first_pkt->pkt.pts + DeltaTime - Now < decode_delay) {        //time to decode, should be based on DTS
1022
                            if (PacketQueueGet(&videoq,&VideoPkt,0, NULL) > 0) {
1023
                                queue_size_checked = 0;
1024
                                avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished, &VideoPkt);
1025
#ifdef DEBUG_SYNC
1026
                                fprintf(stderr, "VIDEO delta =%lld ms; dt=%lld \n",(long long) pFrame->pkt_pts - last_pts, Now - Last);
1027
#endif
1028
                                last_pts = pFrame->pkt_pts;
1029
                                if (pFrame->pkt_pts) decode_delay = MAX(decode_delay, VideoPkt.pts - pFrame->pkt_pts);        //TODO: base this on dts
1030
                                decode_delay = MIN(decode_delay, 40 * 5);        //TODO, this workaround would not be needed if decode_delay would be based on DTS
1031
#ifdef DEBUG_SYNC
1032
                                fprintf(stderr, "VIDEO t=%lld ms ptsin=%lld ptsout=%lld \n",Now, (long long)VideoPkt.pts+DeltaTime, pFrame->pkt_pts+DeltaTime);
1033
                                fprintf(stderr, "VIDEO delay =%lld ms ; %lld ms \n",(long long)VideoPkt.pts+DeltaTime-Now, pFrame->pkt_pts+DeltaTime-Now);
1034
#endif
1035

    
1036
                                if(frameFinished)
1037
                                { // it must be true all the time else error
1038

    
1039
                                        long long target_pts = pFrame->pkt_pts + DeltaTime;
1040
                                        long long earlier = target_pts - Now;
1041

    
1042
#ifdef DEBUG_VIDEO
1043
                                        fprintf(stderr,"VIDEO: FrameFinished\n");
1044
#endif
1045
                                        decoded_vframes++;
1046
                                        
1047

    
1048
#ifdef VIDEO_DEINTERLACE
1049
                                        avpicture_deinterlace(
1050
                                                (AVPicture*) pFrame,
1051
                                                (const AVPicture*) pFrame,
1052
                                                pCodecCtx->pix_fmt,
1053
                                                tval->width, tval->height);
1054
#endif
1055

    
1056
#ifdef SAVE_YUV
1057
                                        if(LastSavedVFrame == -1)
1058
                                        {
1059
                                                memcpy(lastSavedFrameBuffer, pFrame, sizeof(AVFrame));
1060
                                                SaveFrame(pFrame, pCodecCtx->width, pCodecCtx->height);
1061
                                                LastSavedVFrame = VideoPkt.stream_index;
1062
                                        }
1063
                                        else if(LastSavedVFrame == (VideoPkt.stream_index-1))
1064
                                        {
1065
                                                memcpy(lastSavedFrameBuffer, pFrame, sizeof(AVFrame));
1066
                                                SaveFrame(pFrame, pCodecCtx->width, pCodecCtx->height);
1067
                                                LastSavedVFrame = VideoPkt.stream_index;
1068
                                        }
1069
                                        else if(LastSavedVFrame >= 0)
1070
                                        {
1071
                                                while(LastSavedVFrame < (VideoPkt.stream_index-1))
1072
                                                {
1073
                                                        SaveFrame(lastSavedFrameBuffer, pCodecCtx->width, pCodecCtx->height);
1074
                                                }
1075

    
1076
                                                memcpy(lastSavedFrameBuffer, pFrame, sizeof(AVFrame));
1077
                                                SaveFrame(pFrame, pCodecCtx->width, pCodecCtx->height);
1078
                                                LastSavedVFrame = VideoPkt.stream_index;
1079
                                        }
1080
#endif
1081
                                        ChunkerPlayerStats_UpdateVideoPlayedHistory(&(videoq.PacketHistory), VideoPkt.stream_index, pFrame->pict_type, VideoPkt.size, pFrame);
1082

    
1083
                                        if(SilentMode)
1084
                                                continue;
1085

    
1086
                                        SDL_LockMutex(OverlayMutex);
1087
                                        if (RenderFrame2Overlay(pFrame, pCodecCtx->width, pCodecCtx->height, YUVOverlay) < 0){
1088
                                                SDL_UnlockMutex(OverlayMutex);
1089
                                                continue;
1090
                                        }
1091

    
1092
                                        //wait for the playback time
1093
#ifdef DEBUG_SYNC
1094
                                        fprintf(stderr, "VIDEO earlier =%lld ms\n",earlier);
1095
#endif
1096
                                        if (earlier > 0) {
1097
                                                usleep(MIN(earlier,1000) * 1000);
1098
//                                        } else if (earlier < 0) {
1099
//                                                fprintf(stderr, "should increase delay2 : pFrame->pkt_pts=%lld, DeltaTime=%lld, Now=%lld, earlier=%lld\n", pFrame->pkt_pts, DeltaTime, Now, earlier);
1100
//                                                DeltaTime -= earlier;
1101
                                        }
1102

    
1103
                                        Last = Now;
1104

    
1105
                                        if (RenderOverlay2Rect(YUVOverlay, ChunkerPlayerGUI_GetMainOverlayRect()) < 0) {
1106
                                                SDL_UnlockMutex(OverlayMutex);
1107
                                                continue;
1108
                                        }
1109
                                        SDL_UnlockMutex(OverlayMutex);
1110

    
1111
                                        //redisplay logo
1112
                                        /**SDL_BlitSurface(image, NULL, MainScreen, &dest);*/
1113
                                        /* Update the screen area just changed */
1114
                                        /**SDL_UpdateRects(MainScreen, 1, &dest);*/
1115
                                } //if FrameFinished
1116
                                else
1117
                                {
1118
                                        ChunkerPlayerStats_UpdateVideoLossHistory(&(videoq.PacketHistory), VideoPkt.stream_index+1, videoq.last_frame_extracted-1);
1119
                                }
1120
                            }
1121
                        }
1122
                        usleep(5000);
1123
                }
1124
                usleep(5000);
1125
        }
1126
        avcodec_close(pCodecCtx);
1127
        av_free(pCodecCtx);
1128
        av_free(pFrame);
1129
        //fclose(frecon);
1130
#ifdef DEBUG_VIDEO
1131
         fprintf(stderr,"VIDEO: video callback end\n");
1132
#endif
1133

    
1134
#ifdef SAVE_YUV
1135
        if(!lastSavedFrameBuffer)
1136
                free(lastSavedFrameBuffer);
1137
        
1138
        lastSavedFrameBuffer = NULL;
1139
#endif
1140

    
1141
        return 0;
1142
}
1143

    
1144
void AudioCallback(void *userdata, Uint8 *stream, int len)
1145
{
1146
        //AVCodecContext *aCodecCtx = (AVCodecContext *)userdata;
1147
        int audio_size;
1148

    
1149
        static uint8_t audio_buf[AVCODEC_MAX_AUDIO_FRAME_SIZE];
1150

    
1151
        memset(audio_buf, CurrentAudioSilence, sizeof(audio_buf));
1152
        audio_size = AudioDecodeFrame(audio_buf, sizeof(audio_buf));
1153
        
1154
        if(SilentMode < 2) {
1155
                if(audio_size != len) {
1156
                        memset(stream, CurrentAudioSilence, len);
1157
                } else {
1158
                        memcpy(stream, (uint8_t *)audio_buf, len);
1159
                }
1160
        }
1161
}
1162

    
1163
void SaveFrame(AVFrame *pFrame, int width, int height)
1164
{
1165
        FILE *pFile;
1166
        int  y;
1167
  
1168
         // Open file
1169
        pFile=fopen(YUVFileName, "ab");
1170
        if(pFile==NULL)
1171
                return;
1172
  
1173
        // Write header
1174
        //fprintf(pFile, "P5\n%d %d\n255\n", width, height);
1175
  
1176
        // Write Y data
1177
        for(y=0; y<height; y++)
1178
                  fwrite(pFrame->data[0]+y*pFrame->linesize[0], 1, width, pFile);
1179
        // Write U data
1180
        for(y=0; y<height/2; y++)
1181
                  fwrite(pFrame->data[1]+y*pFrame->linesize[1], 1, width/2, pFile);
1182
        // Write V data
1183
        for(y=0; y<height/2; y++)
1184
                  fwrite(pFrame->data[2]+y*pFrame->linesize[2], 1, width/2, pFile);
1185
  
1186
        // Close file
1187
        fclose(pFile);
1188
}
1189

    
1190
int ChunkerPlayerCore_IsRunning()
1191
{
1192
        return AVPlaying;
1193
}
1194

    
1195
void ChunkerPlayerCore_Play()
1196
{
1197
        if(AVPlaying) return;
1198
        AVPlaying = 1;
1199
        
1200
        SDL_PauseAudio(0);
1201
        video_thread = SDL_CreateThread(VideoCallback, &VideoCallbackThreadParams);
1202
        ChunkerPlayerStats_Init(&VideoCallbackThreadParams);
1203
        stats_thread = SDL_CreateThread(CollectStatisticsThread, NULL);
1204
        
1205
        decoded_vframes = 0;
1206
        LastSavedVFrame = -1;
1207
}
1208

    
1209
void ChunkerPlayerCore_Stop()
1210
{
1211
        if(!AVPlaying) return;
1212
        
1213
        AVPlaying = 0;
1214
        
1215
        // Stop audio&video playback
1216
        SDL_WaitThread(video_thread, NULL);
1217
        SDL_WaitThread(stats_thread, NULL);
1218
        SDL_PauseAudio(1);        
1219
        
1220
        if(YUVOverlay != NULL)
1221
        {
1222
                SDL_FreeYUVOverlay(YUVOverlay);
1223
                YUVOverlay = NULL;
1224
        }
1225
        
1226
        PacketQueueReset(&audioq);
1227
        PacketQueueReset(&videoq);
1228
        
1229
        avcodec_close(aCodecCtx);
1230
        av_free(aCodecCtx);
1231
        free(AudioPkt.data);
1232
        free(VideoPkt.data);
1233
        free(outbuf_audio);
1234
        
1235
        /*
1236
        * Sleep two buffers' worth of audio before closing, in order
1237
        *  to allow the playback to finish. This isn't always enough;
1238
        *   perhaps SDL needs a way to explicitly wait for device drain?
1239
        * Doesn't seem to be necessary -> disabled
1240
        */
1241
        //int delay = 2 * 1000 * CurrentAudioSamples / CurrentAudioFreq;
1242
        // fprintf(stderr,"SDL_Delay(%d)\n", delay*10);
1243
        //SDL_Delay(delay*10);
1244
}
1245

    
1246
void ChunkerPlayerCore_Finalize()
1247
{
1248
        if(YUVOverlay != NULL)
1249
        {
1250
                SDL_FreeYUVOverlay(YUVOverlay);
1251
                YUVOverlay = NULL;
1252
        }
1253

    
1254
        SDL_CloseAudio();
1255
}
1256

    
1257
void ChunkerPlayerCore_Pause()
1258
{
1259
        if(!AVPlaying) return;
1260
        
1261
        AVPlaying = 0;
1262
        
1263
        // Stop audio&video playback
1264
        SDL_WaitThread(video_thread, NULL);
1265
        SDL_PauseAudio(1);
1266
        
1267
        PacketQueueReset(&audioq);
1268
        PacketQueueReset(&videoq);
1269
}
1270

    
1271
int ChunkerPlayerCore_AudioEnded()
1272
{
1273
        return (audioq.nb_packets==0 && audioq.last_frame_extracted>0);
1274
}
1275

    
1276
void ChunkerPlayerCore_ResetAVQueues()
1277
{
1278
#ifdef DEBUG_QUEUE
1279
        fprintf(stderr,"QUEUE: MAIN SHOULD RESET\n");
1280
#endif
1281
        PacketQueueReset(&audioq);
1282
        PacketQueueReset(&videoq);
1283
}
1284

    
1285
int ChunkerPlayerCore_EnqueueBlocks(const uint8_t *block, const int block_size)
1286
{
1287
#ifdef EMULATE_CHUNK_LOSS
1288
        static time_t loss_cycle_start_time = 0, now = 0;
1289
        static int early_losses = 0;
1290
        static int clp_frames = 0;
1291
        
1292
        if(ScheduledChunkLosses)
1293
        {
1294
                static unsigned int random_threshold;
1295
                now=time(NULL);
1296
                if(!loss_cycle_start_time)
1297
                        loss_cycle_start_time = now;
1298
                        
1299
                if(((now-loss_cycle_start_time) >= ScheduledChunkLosses[((CurrChunkLossIndex+1)%NScheduledChunkLosses)].Time) && (NScheduledChunkLosses>1 || CurrChunkLossIndex==-1))
1300
                {
1301
                        CurrChunkLossIndex = ((CurrChunkLossIndex+1)%NScheduledChunkLosses);
1302
                        if(CurrChunkLossIndex == (NScheduledChunkLosses-1))
1303
                                loss_cycle_start_time = now;
1304
                        
1305
                        if(ScheduledChunkLosses[CurrChunkLossIndex].Value == -1)
1306
                                random_threshold = ScheduledChunkLosses[CurrChunkLossIndex].MinValue + (rand() % (ScheduledChunkLosses[CurrChunkLossIndex].MaxValue-ScheduledChunkLosses[CurrChunkLossIndex].MinValue));
1307
                        else
1308
                                random_threshold = ScheduledChunkLosses[CurrChunkLossIndex].Value;
1309
                        
1310
                        fprintf(stderr,"new ScheduledChunkLoss, time: %d, value: %d\n", (int)ScheduledChunkLosses[CurrChunkLossIndex].Time, random_threshold);
1311
                }
1312
        
1313
                if(clp_frames > 0)
1314
                {
1315
                        clp_frames--;
1316
                        return PLAYER_FAIL_RETURN;
1317
                }
1318
                if((rand() % 100) < random_threshold)
1319
                {
1320
                        if(early_losses > 0)
1321
                early_losses--;
1322
            else
1323
            {
1324
                clp_frames=early_losses=(ScheduledChunkLosses[CurrChunkLossIndex].Burstiness-1);
1325
                return PLAYER_FAIL_RETURN;
1326
            }
1327
                }
1328
        }
1329
#endif
1330

    
1331
        Chunk *gchunk = NULL;
1332
        int decoded_size = -1;
1333
        uint8_t *tempdata, *buffer;
1334
        int j;
1335
        Frame *frame = NULL;
1336
        AVPacket packet, packetaudio;
1337

    
1338
        uint16_t *audio_bufQ = NULL;
1339

    
1340
        //the frame.h gets encoded into 5 slots of 32bits (3 ints plus 2 more for the timeval struct
1341
        static int sizeFrameHeader = 5*sizeof(int32_t);
1342
        //the following we dont need anymore
1343
        //static int ExternalChunk_header_size = 5*CHUNK_TRANSCODING_INT_SIZE + 2*CHUNK_TRANSCODING_INT_SIZE + 2*CHUNK_TRANSCODING_INT_SIZE + 1*CHUNK_TRANSCODING_INT_SIZE*2;
1344

    
1345
        static int chunks_out_of_order = 0;
1346
        static int last_chunk_id = -1;
1347

    
1348
        audio_bufQ = (uint16_t *)av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
1349
        if(!audio_bufQ) {
1350
                fprintf(stderr,"Memory error in audio_bufQ!\n");
1351
                return PLAYER_FAIL_RETURN;
1352
        }
1353

    
1354
        gchunk = (Chunk *)malloc(sizeof(Chunk));
1355
        if(!gchunk) {
1356
                fprintf(stderr,"Memory error in gchunk!\n");
1357
                av_free(audio_bufQ);
1358
                return PLAYER_FAIL_RETURN;
1359
        }
1360

    
1361
        decoded_size = decodeChunk(gchunk, block, block_size);
1362

    
1363
        if(last_chunk_id == -1)
1364
                last_chunk_id = gchunk->id;
1365

    
1366
        if(gchunk->id > (last_chunk_id+1)) {
1367
                chunks_out_of_order += gchunk->id - last_chunk_id - 1;
1368
        }
1369
        last_chunk_id = gchunk->id;
1370

    
1371
#ifdef DEBUG_CHUNKER
1372
        fprintf(stderr,"CHUNKER: enqueueBlock: id %d decoded_size %d target size %d - out_of_order %d\n", gchunk->id, decoded_size, GRAPES_ENCODED_CHUNK_HEADER_SIZE + gchunk->size, chunks_out_of_order);
1373
#endif
1374
  if(decoded_size < 0) {
1375
                //HINT here i should differentiate between various return values of the decode
1376
                //in order to free what has been allocated there
1377
                fprintf(stderr,"chunk probably corrupted!\n");
1378
                av_free(audio_bufQ);
1379
                free(gchunk);
1380
                return PLAYER_FAIL_RETURN;
1381
        }
1382

    
1383
        frame = (Frame *)malloc(sizeof(Frame));
1384
        if(!frame) {
1385
                fprintf(stderr,"Memory error in Frame!\n");
1386
                if(gchunk) {
1387
                        if(gchunk->attributes) {
1388
                                free(gchunk->attributes);
1389
                        }
1390
                        free(gchunk);
1391
                }
1392
                av_free(audio_bufQ);
1393
                return PLAYER_FAIL_RETURN;
1394
        }
1395

    
1396
        tempdata = gchunk->data; //let it point to first frame of payload
1397
        j=gchunk->size;
1398
        while(j>0 && !quit) {
1399
                frame->number = bit32_encoded_pull(tempdata);
1400
                tempdata += CHUNK_TRANSCODING_INT_SIZE;
1401
                frame->timestamp.tv_sec = bit32_encoded_pull(tempdata);
1402
                tempdata += CHUNK_TRANSCODING_INT_SIZE;
1403
                frame->timestamp.tv_usec = bit32_encoded_pull(tempdata);
1404
                tempdata += CHUNK_TRANSCODING_INT_SIZE;
1405
                frame->size = bit32_encoded_pull(tempdata);
1406
                tempdata += CHUNK_TRANSCODING_INT_SIZE;
1407
                frame->type = bit32_encoded_pull(tempdata);
1408
                tempdata += CHUNK_TRANSCODING_INT_SIZE;
1409

    
1410
                buffer = tempdata; // here coded frame information
1411
                tempdata += frame->size; //let it point to the next frame
1412

    
1413
                if(frame->type < 5) { // video frame
1414
                        av_init_packet(&packet);
1415
                        packet.data = buffer;//video_bufQ;
1416
                        packet.size = frame->size;
1417
                        packet.pts = frame->timestamp.tv_sec*(unsigned long long)1000+frame->timestamp.tv_usec;
1418
                        packet.dts = frame->timestamp.tv_sec*(unsigned long long)1000+frame->timestamp.tv_usec;
1419
                        packet.stream_index = frame->number; // use of stream_index for number frame
1420
                        //packet.duration = frame->timestamp.tv_sec;
1421
                        if(packet.size > 0) {
1422
                                int ret = ChunkerPlayerCore_PacketQueuePut(&videoq, &packet); //the _put makes a copy of the packet
1423
                                if (ret == 1) {        //TODO: check and correct return values
1424
                                        fprintf(stderr, "late chunk received, increasing delay to %lld\n", DeltaTime);
1425
                                        DeltaTime += 5;        //TODO: handle audio skip; verify this value
1426
                                }
1427
                        }
1428

    
1429
#ifdef DEBUG_SOURCE
1430
                        fprintf(stderr,"SOURCE: Insert video in queue pts=%lld %d %d sindex:%d\n",packet.pts,(int)frame->timestamp.tv_sec,(int)frame->timestamp.tv_usec,packet.stream_index);
1431
#endif
1432
                }
1433
                else if(frame->type == 5) { // audio frame
1434
                        av_init_packet(&packetaudio);
1435
                        packetaudio.data = buffer;
1436
                        packetaudio.size = frame->size;
1437
                        packetaudio.pts = frame->timestamp.tv_sec*(unsigned long long)1000+frame->timestamp.tv_usec;
1438
                        packetaudio.dts = frame->timestamp.tv_sec*(unsigned long long)1000+frame->timestamp.tv_usec;
1439
                        //packetaudio.duration = frame->timestamp.tv_sec;
1440
                        packetaudio.stream_index = frame->number; // use of stream_index for number frame
1441
                        packetaudio.flags = 1;
1442
                        packetaudio.pos = -1;
1443

    
1444
                        //instead of -1, in order to signal it is not decoded yet
1445
                        packetaudio.convergence_duration = 0;
1446

    
1447
                        // insert the audio frame into the queue
1448
                        if(packetaudio.size > 0) {
1449
                                int ret = ChunkerPlayerCore_PacketQueuePut(&audioq, &packetaudio);//makes a copy of the packet so i can free here
1450
                                if (ret == 1) {        //TODO: check and correct return values
1451
                                        fprintf(stderr, "late chunk received, increasing delay to %lld\n", DeltaTime);
1452
                                        DeltaTime += 5;        //TODO: handle audio skip; verify this value
1453
                                }
1454
                        }
1455

    
1456
#ifdef DEBUG_SOURCE
1457
                        fprintf(stderr,"SOURCE: Insert audio in queue pts=%lld sindex:%d\n", packetaudio.pts, packetaudio.stream_index);
1458
#endif
1459
                }
1460
                else {
1461
                        fprintf(stderr,"SOURCE: Unknown frame type %d. Size %d\n", frame->type, frame->size);
1462
                }
1463
                if(frame->size > 0)
1464
                        j = j - sizeFrameHeader - frame->size;
1465
                else {
1466
                        fprintf(stderr,"SOURCE: Corrupt frames (size %d) in chunk. Skipping it...\n", frame->size);
1467
                        j = -1;
1468
                }
1469
        }
1470
        //chunk ingestion terminated!
1471
        if(gchunk) {
1472
                if(gchunk->attributes) {
1473
                        free(gchunk->attributes);
1474
                }
1475
                if(gchunk->data)
1476
                        free(gchunk->data);
1477
                free(gchunk);
1478
        }
1479
        if(frame)
1480
                free(frame);
1481
        if(audio_bufQ)
1482
                av_free(audio_bufQ);
1483
                
1484
        return PLAYER_OK_RETURN;
1485
}
1486

    
1487
void ChunkerPlayerCore_SetupOverlay(int width, int height)
1488
{
1489
        // if(!MainScreen && !SilentMode)
1490
        // {
1491
                // fprintf(stderr,"Cannot find main screen, exiting...\n");
1492
                // exit(1);
1493
        // }
1494
        
1495
        if(SilentMode)
1496
                return;
1497

    
1498
        //TODO: return with error if size is too small
1499
        width = MAX(width, 8);
1500
        height = MAX(height, 8);
1501

    
1502
        SDL_LockMutex(OverlayMutex);
1503
        if(YUVOverlay != NULL)
1504
        {
1505
                SDL_FreeYUVOverlay(YUVOverlay);
1506
                YUVOverlay = NULL;
1507
        }
1508
        
1509
        // create video overlay for display of video frames
1510
        // fprintf(stderr,"SDL_CreateYUVOverlay(%d, %d, SDL_YV12_OVERLAY, MainScreen)\n", width, height);
1511
        YUVOverlay = SDL_CreateYUVOverlay(width, height, SDL_YV12_OVERLAY, MainScreen);
1512
        if ( YUVOverlay == NULL )
1513
        {
1514
                fprintf(stderr,"SDL: Couldn't create SDL_yuv_overlay: %s", SDL_GetError());
1515
                exit(1);
1516
        }
1517

    
1518
        if ( YUVOverlay->hw_overlay )
1519
                fprintf(stderr,"SDL: Using hardware overlay.\n");
1520
        
1521
        SDL_DisplayYUVOverlay(YUVOverlay, ChunkerPlayerGUI_GetMainOverlayRect());
1522
        
1523
        SDL_UnlockMutex(OverlayMutex);
1524
}
1525

    
1526
int CollectStatisticsThread(void *params)
1527
{
1528
        struct timeval last_stats_evaluation, now, last_trace, last_qoe_evaluation;
1529
        gettimeofday(&last_stats_evaluation, NULL);
1530
        last_trace = last_stats_evaluation;
1531
        last_qoe_evaluation = last_stats_evaluation;
1532
        
1533
        double video_qdensity;
1534
        double audio_qdensity;
1535
        char audio_stats_text[255];
1536
        char video_stats_text[255];
1537
        SStats audio_statistics, video_statistics;
1538
        double qoe = 0;
1539
        int sleep_time = STATS_THREAD_GRANULARITY*1000;
1540
        int audio_avg_bitrate = 0;
1541
        int video_avg_bitrate = 0;
1542
        
1543
        while(AVPlaying && !quit)
1544
        {
1545
                usleep(sleep_time);
1546
                
1547
                gettimeofday(&now, NULL);
1548
                
1549
                if((((now.tv_sec*1000)+(now.tv_usec/1000)) - ((last_stats_evaluation.tv_sec*1000)+(last_stats_evaluation.tv_usec/1000))) > GUI_PRINTSTATS_INTERVAL)
1550
                {
1551
                        // estimate audio queue stats
1552
                        int audio_stats_changed = ChunkerPlayerStats_GetStats(&(audioq.PacketHistory), &audio_statistics);
1553
                        
1554
                        // estimate video queue stats
1555
                        int video_stats_changed = ChunkerPlayerStats_GetStats(&(videoq.PacketHistory), &video_statistics);
1556

    
1557
                        // compute avg bitrate up to now
1558
                        audioq.cumulative_bitrate += audio_statistics.Bitrate;
1559
                        audioq.cumulative_samples++;
1560
                        audio_avg_bitrate = (int)( ((double)audioq.cumulative_bitrate) / ((double)audioq.cumulative_samples) );
1561
                        videoq.cumulative_bitrate += video_statistics.Bitrate;
1562
                        videoq.cumulative_samples++;
1563
                        video_avg_bitrate = (int)( ((double)videoq.cumulative_bitrate) / ((double)videoq.cumulative_samples) );
1564

    
1565
#ifdef DEBUG_STATS
1566
                        fprintf(stderr,"VIDEO: %d Kbit/sec; ", video_statistics.Bitrate);
1567
                        fprintf(stderr,"AUDIO: %d Kbit/sec\n", audio_statistics.Bitrate);
1568
#endif
1569

    
1570
                        // QUEUE DENSITY EVALUATION
1571
                        if((audioq.last_pkt != NULL) && (audioq.first_pkt != NULL))
1572
                                if(audioq.last_pkt->pkt.stream_index >= audioq.first_pkt->pkt.stream_index)
1573
                                {
1574
                                        //plus 1 because if they are adjacent (difference 1) there really should be 2 packets in the queue
1575
                                        audio_qdensity = (double)audioq.nb_packets / (double)(audioq.last_pkt->pkt.stream_index - audioq.first_pkt->pkt.stream_index + 1) * 100.0;
1576
                                }
1577
                        
1578
                        if((videoq.last_pkt != NULL) && (videoq.first_pkt != NULL))
1579
                                if(videoq.last_pkt->pkt.stream_index >= videoq.first_pkt->pkt.stream_index)
1580
                                {
1581
                                        // plus 1 because if they are adjacent (difference 1) there really should be 2 packets in the queue
1582
                                        video_qdensity = (double)videoq.nb_packets / (double)(videoq.last_pkt->pkt.stream_index - videoq.first_pkt->pkt.stream_index + 1) * 100.0;
1583
                                }
1584
                        
1585
                        if(LogTraces)
1586
                        {
1587
                                ChunkerPlayerStats_PrintHistoryTrace(&(audioq.PacketHistory), AudioTraceFilename);
1588
                                ChunkerPlayerStats_PrintHistoryTrace(&(videoq.PacketHistory), VideoTraceFilename);
1589
                                
1590
                                //if(SilentMode != 1 && SilentMode != 2)
1591
                                        ChunkerPlayerStats_PrintContextFile();
1592
                        }
1593

    
1594
                        // PRINT STATISTICS ON GUI
1595
                        if(!Audio_ON)
1596
                                sprintf(audio_stats_text, "AUDIO MUTED");
1597
                        else if(audio_stats_changed)
1598
//                                sprintf(audio_stats_text, "[AUDIO] qsize: %d qdensity: %d\%% - losses: %d/sec (%ld tot) - skips: %d/sec (%ld tot)", (int)audioq.nb_packets, (int)audio_qdensity, (int)audio_statistics.Lossrate, audioq.PacketHistory.LostCount, audio_statistics.Skiprate, audioq.PacketHistory.SkipCount);
1599
                                sprintf(audio_stats_text, "[AUDIO] qsize: %d qdensity: %d\%% - losses: %d/sec (%ld tot) - rate: %d kbits/sec (avg: %d)", (int)audioq.nb_packets, (int)audio_qdensity, (int)audio_statistics.Lossrate, audioq.PacketHistory.LostCount, audio_statistics.Bitrate, audio_avg_bitrate);
1600
                        else
1601
                                sprintf(audio_stats_text, "waiting for incoming audio packets...");
1602

    
1603
                        if(video_stats_changed)
1604
                        {
1605
                                char est_psnr_string[255];
1606
                                sprintf(est_psnr_string, ".");
1607
                                if(qoe)
1608
                                {
1609
                                        sprintf(est_psnr_string, " - Est. Mean PSNR: %.1f db", (float)qoe);
1610
#ifdef PSNR_PUBLICATION
1611
                                        // Publish measure into repository
1612
                                        if(RepoAddress[0]!='\0')
1613
                                        {
1614
                                            MeasurementRecord r;
1615
                            r.originator = NetworkID;
1616
                            r.targetA = NetworkID;
1617
                            r.targetB = NULL;
1618
                            r.published_name = "PSNR_MEAN";
1619
                            r.value = qoe;
1620
                            r.string_value = NULL;
1621
                            r.channel = Channels[SelectedChannel].Title;
1622
                            gettimeofday(&(r.timestamp), NULL);
1623
                            // One update every REPO_UPDATE_INTERVALL seconds
1624
                            struct timeval ElapsedTime;
1625
                            timeval_subtract(&(r.timestamp),&LastTimeRepoPublish,&ElapsedTime);
1626
                        if(ElapsedTime.tv_sec>=PSNR_REPO_UPDATE_INTERVALL)
1627
                        {
1628
                            LastTimeRepoPublish=r.timestamp;
1629
                            if(repPublish(repoclient,NULL,NULL,&r)!=NULL) {
1630
#ifdef DEBUG_PSNR
1631
                               fprintf(stderr,"PSNR publish: %s  %e  %s\n",r.originator,qoe,r.channel);
1632
#endif
1633
                                                                                                                }
1634
                        }
1635
                   }
1636
#endif
1637
                                }
1638

    
1639
//                                sprintf(video_stats_text, "[VIDEO] qsize: %d qdensity: %d\%% - losses: %d/sec (%ld tot) - skips: %d/sec (%ld tot)%s", (int)videoq.nb_packets, (int)video_qdensity, video_statistics.Lossrate, videoq.PacketHistory.LostCount, video_statistics.Skiprate, videoq.PacketHistory.SkipCount, est_psnr_string);
1640
                                sprintf(video_stats_text, "[VIDEO] qsize: %d qdensity: %d\%% - losses: %d/sec (%ld tot) - rate: %d kbits/sec (avg: %d) %s", (int)videoq.nb_packets, (int)video_qdensity, video_statistics.Lossrate, videoq.PacketHistory.LostCount, video_statistics.Bitrate, video_avg_bitrate, est_psnr_string);
1641
                        }
1642
                        else
1643
                                sprintf(video_stats_text, "waiting for incoming video packets...");
1644
                        
1645
                        if(qoe && qoe_led) {
1646
                            ChunkerPlayerGUI_SetStatsText(audio_stats_text, video_stats_text,(qoe>LED_THRS_YELLOW?LED_GREEN:((qoe<=LED_THRS_YELLOW && qoe>LED_THRS_RED)?LED_YELLOW:LED_RED)));
1647
                        } else {
1648
                            ChunkerPlayerGUI_SetStatsText(audio_stats_text, video_stats_text,LED_NONE);
1649
                        }
1650

    
1651
                        last_stats_evaluation = now;
1652
                }
1653
                
1654
                if((((now.tv_sec*1000)+(now.tv_usec/1000)) - ((last_qoe_evaluation.tv_sec*1000)+(last_qoe_evaluation.tv_usec/1000))) > EVAL_QOE_INTERVAL)
1655
                {
1656
                        // ESTIMATE QoE
1657
                        //ChunkerPlayerStats_GetMeanVideoQuality(&(videoq.PacketHistory), &qoe);
1658
                        // ESTIMATE QoE using real-time computed cumulative average bitrate
1659
                        // (plus a diminshing contribution of the instantaneous bitrate, until the cumulative avg stabilizes)
1660
                        int input_bitrate = 0;
1661
                        // stabilize after circa 30 seconds
1662
                        if(videoq.cumulative_samples < 30*(1000/GUI_PRINTSTATS_INTERVAL))
1663
                                input_bitrate = video_statistics.Bitrate;
1664
                        else
1665
                                input_bitrate = video_avg_bitrate;
1666
                        //double a = 1 / ((double)videoq.cumulative_samples);
1667
                        //double b = 1-a;
1668
                        //double input_bitrate = a*((double)video_statistics.Bitrate) + b*((double)video_avg_bitrate);
1669
                        ChunkerPlayerStats_GetMeanVideoQuality(&(videoq.PacketHistory), input_bitrate, &qoe);
1670
#ifdef DEBUG_STATS
1671
                        fprintf(stderr,"rate %d avg %d wghtd %d cum_samp %d PSNR %f\n", video_statistics.Bitrate, video_avg_bitrate, (int)input_bitrate, videoq.cumulative_samples, (float)qoe);
1672
#endif
1673
                        last_qoe_evaluation = now;
1674
                }
1675
        }
1676
        return 0;
1677
}
1678

    
1679
void ChunkerPlayerCore_ChangeDelay(int ms)
1680
{
1681
        DeltaTime += ms;
1682
}