Statistics
| Branch: | Revision:

chunker-player / chunker_player / player_core.c @ 3262ed44

History | View | Annotate | Download (49.4 KB)

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

    
9
#include <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
        printf("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
        printf("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
        printf("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
                printf("F ");
173
#endif
174
                q->PacketHistory.LostCount++;
175
        }
176
#ifdef DEBUG_QUEUE
177
        printf("\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
        printf("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
        //~ printf("\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
                printf("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
                printf("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
                printf("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
                                        printf("%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
                                        printf("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
                        printf("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
                printf("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
        printf("using audio Codecid: %d ",aCodecCtx->codec_id);
355
        printf("samplerate: %d ",aCodecCtx->sample_rate);
356
        printf("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
        printf("wanted freq:%d\n",wanted_spec->freq);
380
        printf("wanted format:%d\n",wanted_spec->format);
381
        printf("wanted channels:%d\n",wanted_spec->channels);
382
        printf("wanted silence:%d\n",wanted_spec->silence);
383
        printf("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
        printf("freq:%d\n",wanted_spec->freq);
415
        printf("format:%d\n",wanted_spec->format);
416
        printf("channels:%d\n",wanted_spec->channels);
417
        printf("silence:%d\n",wanted_spec->silence);
418
        printf("samples:%d\n",wanted_spec->samples);
419
        printf("size:%d\n",wanted_spec->size);
420
        printf("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
        //printf("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
        avcodec_init();
487
        av_register_all();
488

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

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

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

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

    
510
        //set the flag to decoded anyway        
511
        pkt->convergence_duration = -1;
512

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

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

    
566
        if (q->first_pkt == p) {
567
                q->first_pkt = p->next;
568
        }
569
        if (&(p->pkt) == q->minpts_pkt) {
570
                q->minpts_pkt = NULL;
571
        }
572

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

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

    
592
        return retpk;
593
}
594

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

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

    
622
        SDL_LockMutex(q->mutex);
623

    
624
#ifdef DEBUG_QUEUE
625
        printf("QUEUE: Get NPackets=%d Type=%s\n", q->nb_packets, (q->queueType==AUDIO) ? "AUDIO" : "VIDEO");
626
#endif
627

    
628
        if((q->queueType==AUDIO && QueueFillingMode) || QueueStopped)
629
        {
630
                SDL_UnlockMutex(q->mutex);
631
                return -1;
632
        }
633

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

    
664
#ifdef DEBUG_AUDIO_BUFFER
665
                        printf("2: idx %d    \taqo %d    \tstc %d    \taqe %f    \tpsz %d\n", pkt1->pkt.stream_index, AudioQueueOffset, SizeToCopy, deltaAudioQError, pkt1->pkt.size);
666
#endif
667

    
668
                        //update index of last frame extracted
669
                        //ChunkerPlayerStats_UpdateAudioLossHistory(&(q->PacketHistory), pkt->stream_index, q->last_frame_extracted);
670
                        q->last_frame_extracted = pkt->stream_index;
671

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

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

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

    
721
        SDL_UnlockMutex(q->mutex);
722
        return ret;
723
}
724

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

    
733
        //gettimeofday(&now,NULL);
734
        //Now = (now.tv_sec)*1000+now.tv_usec/1000;
735
        Now=(long long)SDL_GetTicks();
736

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

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

    
760
#ifdef DEBUG_AUDIO 
761
        if(audioq.first_pkt)
762
        {
763
                printf("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);
764
                printf("AUDIO: QueueLen=%d ",(int)audioq.nb_packets);
765
                printf("AUDIO: QueueSize=%d\n",(int)audioq.size);
766
        }
767
        else
768
                printf("AUDIO: audio_decode_frame - Empty queue\n");
769
#endif
770

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

    
823
                ChunkerPlayerStats_UpdateAudioPlayedHistory(&(audioq.PacketHistory), AudioPkt.stream_index, compressed_size);
824
        }
825

    
826
        return audio_pkt_size;
827
}
828

    
829
// Render a Frame to a YUV Overlay. Note that the Overlay is already bound to an SDL Surface
830
// Note that width, height would not be needed in new ffmpeg versions where this info is contained in AVFrame
831
// see: [FFmpeg-devel] [PATCH] lavc: add width and height fields to AVFrame
832
int RenderFrame2Overlay(AVFrame *pFrame, int frame_width, int frame_height, SDL_Overlay *YUVOverlay)
833
{
834
        AVPicture pict;
835
        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)
836

    
837
                                        if(SDL_LockYUVOverlay(YUVOverlay) < 0) {
838
                                                return -1;
839
                                        }
840

    
841
                                        pict.data[0] = YUVOverlay->pixels[0];
842
                                        pict.data[1] = YUVOverlay->pixels[2];
843
                                        pict.data[2] = YUVOverlay->pixels[1];
844

    
845
                                        pict.linesize[0] = YUVOverlay->pitches[0];
846
                                        pict.linesize[1] = YUVOverlay->pitches[2];
847
                                        pict.linesize[2] = YUVOverlay->pitches[1];
848

    
849
                                        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);
850
                                        if(img_convert_ctx == NULL) {
851
                                                fprintf(stderr, "Cannot initialize the conversion context!\n");
852
                                                exit(1);
853
                                        }
854

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

    
859
        return 0;
860
}
861

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

    
866
                                        // Lock SDL_yuv_overlay
867
                                        if(SDL_MUSTLOCK(MainScreen)) {
868
                                                if(SDL_LockSurface(MainScreen) < 0) {
869
                                                        return -1;
870
                                                }
871
                                        }
872

    
873
                                        // Show, baby, show!
874
                                        SDL_LockMutex(OverlayMutex);
875
                                        SDL_DisplayYUVOverlay(YUVOverlay, Rect);
876
                                        SDL_UnlockMutex(OverlayMutex);
877

    
878
                                        if(SDL_MUSTLOCK(MainScreen)) {
879
                                                SDL_UnlockSurface(MainScreen);
880
                                        }
881

    
882
        return 0;
883

    
884
}
885

    
886

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

    
908
        //double frame_rate = 0.0,time_between_frames=0.0;
909
        //struct timeval now;
910

    
911
        //int wait_for_sync = 1;
912
        ThreadVal *tval;
913
        tval = (ThreadVal *)valthread;
914

    
915
        //frame_rate = tval->framerate;
916
        //time_between_frames = 1.e6 / frame_rate;
917
        //gettimeofday(&time_now,0);
918

    
919
        //frecon = fopen("recondechunk.mpg","wb");
920

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

    
930
        pCodecCtx=avcodec_alloc_context();
931
        pCodecCtx->codec_type = CODEC_TYPE_VIDEO;
932
        //pCodecCtx->debug = FF_DEBUG_DCT_COEFF;
933
        pCodecCtx->codec_id = pCodec->id;
934

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

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

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

    
965
        while(AVPlaying && !quit) {
966

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

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

    
993
#ifdef DEBUG_VIDEO 
994
                if(videoq.first_pkt)
995
                {
996
                        printf("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);
997
                        printf("VIDEO: Index=%d ", (int)videoq.first_pkt->pkt.stream_index);
998
                        printf("VIDEO: QueueLen=%d ", (int)videoq.nb_packets);
999
                        printf("VIDEO: QueueSize=%d\n", (int)videoq.size);
1000
                }
1001
                else
1002
                        printf("VIDEO: VideoCallback - Empty queue\n");
1003
#endif
1004

    
1005
#ifdef DEBUG_VIDEO
1006
                printf("VIDEO: skipvideo:%d decodevideo:%d\n",SkipVideo,DecodeVideo);
1007
#endif
1008
//                        ChunkerPlayerStats_UpdateVideoSkipHistory(&(videoq.PacketHistory), VideoPkt.stream_index, pFrame->pict_type, VideoPkt.size, pFrame);
1009

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

    
1033
                                if(frameFinished)
1034
                                { // it must be true all the time else error
1035

    
1036
                                        long long target_pts = pFrame->pkt_pts + DeltaTime;
1037
                                        long long earlier = target_pts - Now;
1038

    
1039
#ifdef DEBUG_VIDEO
1040
                                        printf("VIDEO: FrameFinished\n");
1041
#endif
1042
                                        decoded_vframes++;
1043
                                        
1044

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

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

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

    
1080
                                        if(SilentMode)
1081
                                                continue;
1082

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

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

    
1100
                                        Last = Now;
1101

    
1102
                                        if (RenderOverlay2Rect(YUVOverlay, ChunkerPlayerGUI_GetMainOverlayRect()) < 0) {
1103
                                                SDL_UnlockMutex(OverlayMutex);
1104
                                                continue;
1105
                                        }
1106
                                        SDL_UnlockMutex(OverlayMutex);
1107

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

    
1131
#ifdef SAVE_YUV
1132
        if(!lastSavedFrameBuffer)
1133
                free(lastSavedFrameBuffer);
1134
        
1135
        lastSavedFrameBuffer = NULL;
1136
#endif
1137

    
1138
        return 0;
1139
}
1140

    
1141
void AudioCallback(void *userdata, Uint8 *stream, int len)
1142
{
1143
        //AVCodecContext *aCodecCtx = (AVCodecContext *)userdata;
1144
        int audio_size;
1145

    
1146
        static uint8_t audio_buf[AVCODEC_MAX_AUDIO_FRAME_SIZE];
1147

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

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

    
1187
int ChunkerPlayerCore_IsRunning()
1188
{
1189
        return AVPlaying;
1190
}
1191

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

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

    
1243
void ChunkerPlayerCore_Finalize()
1244
{
1245
        if(YUVOverlay != NULL)
1246
        {
1247
                SDL_FreeYUVOverlay(YUVOverlay);
1248
                YUVOverlay = NULL;
1249
        }
1250

    
1251
        SDL_CloseAudio();
1252
}
1253

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

    
1268
int ChunkerPlayerCore_AudioEnded()
1269
{
1270
        return (audioq.nb_packets==0 && audioq.last_frame_extracted>0);
1271
}
1272

    
1273
void ChunkerPlayerCore_ResetAVQueues()
1274
{
1275
#ifdef DEBUG_QUEUE
1276
        printf("QUEUE: MAIN SHOULD RESET\n");
1277
#endif
1278
        PacketQueueReset(&audioq);
1279
        PacketQueueReset(&videoq);
1280
}
1281

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

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

    
1335
        uint16_t *audio_bufQ = NULL;
1336

    
1337
        //the frame.h gets encoded into 5 slots of 32bits (3 ints plus 2 more for the timeval struct
1338
        static int sizeFrameHeader = 5*sizeof(int32_t);
1339
        //the following we dont need anymore
1340
        //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;
1341

    
1342
        static int chunks_out_of_order = 0;
1343
        static int last_chunk_id = -1;
1344

    
1345
        audio_bufQ = (uint16_t *)av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
1346
        if(!audio_bufQ) {
1347
                printf("Memory error in audio_bufQ!\n");
1348
                return PLAYER_FAIL_RETURN;
1349
        }
1350

    
1351
        gchunk = (Chunk *)malloc(sizeof(Chunk));
1352
        if(!gchunk) {
1353
                printf("Memory error in gchunk!\n");
1354
                av_free(audio_bufQ);
1355
                return PLAYER_FAIL_RETURN;
1356
        }
1357

    
1358
        decoded_size = decodeChunk(gchunk, block, block_size);
1359

    
1360
        if(last_chunk_id == -1)
1361
                last_chunk_id = gchunk->id;
1362

    
1363
        if(gchunk->id > (last_chunk_id+1)) {
1364
                chunks_out_of_order += gchunk->id - last_chunk_id - 1;
1365
        }
1366
        last_chunk_id = gchunk->id;
1367

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

    
1380
        frame = (Frame *)malloc(sizeof(Frame));
1381
        if(!frame) {
1382
                printf("Memory error in Frame!\n");
1383
                if(gchunk) {
1384
                        if(gchunk->attributes) {
1385
                                free(gchunk->attributes);
1386
                        }
1387
                        free(gchunk);
1388
                }
1389
                av_free(audio_bufQ);
1390
                return PLAYER_FAIL_RETURN;
1391
        }
1392

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

    
1407
                buffer = tempdata; // here coded frame information
1408
                tempdata += frame->size; //let it point to the next frame
1409

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

    
1426
#ifdef DEBUG_SOURCE
1427
                        printf("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);
1428
#endif
1429
                }
1430
                else if(frame->type == 5) { // audio frame
1431
                        av_init_packet(&packetaudio);
1432
                        packetaudio.data = buffer;
1433
                        packetaudio.size = frame->size;
1434
                        packetaudio.pts = frame->timestamp.tv_sec*(unsigned long long)1000+frame->timestamp.tv_usec;
1435
                        packetaudio.dts = frame->timestamp.tv_sec*(unsigned long long)1000+frame->timestamp.tv_usec;
1436
                        //packetaudio.duration = frame->timestamp.tv_sec;
1437
                        packetaudio.stream_index = frame->number; // use of stream_index for number frame
1438
                        packetaudio.flags = 1;
1439
                        packetaudio.pos = -1;
1440

    
1441
                        //instead of -1, in order to signal it is not decoded yet
1442
                        packetaudio.convergence_duration = 0;
1443

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

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

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

    
1495
        //TODO: return with error if size is too small
1496
        width = MAX(width, 8);
1497
        height = MAX(height, 8);
1498

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

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

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

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

    
1562
#ifdef DEBUG_STATS
1563
                        printf("VIDEO: %d Kbit/sec; ", video_statistics.Bitrate);
1564
                        printf("AUDIO: %d Kbit/sec\n", audio_statistics.Bitrate);
1565
#endif
1566

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

    
1591
                        // PRINT STATISTICS ON GUI
1592
                        if(!Audio_ON)
1593
                                sprintf(audio_stats_text, "AUDIO MUTED");
1594
                        else if(audio_stats_changed)
1595
//                                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);
1596
                                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);
1597
                        else
1598
                                sprintf(audio_stats_text, "waiting for incoming audio packets...");
1599

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

    
1636
//                                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);
1637
                                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);
1638
                        }
1639
                        else
1640
                                sprintf(video_stats_text, "waiting for incoming video packets...");
1641
                        
1642
                        if(qoe && qoe_led) {
1643
                            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)));
1644
                        } else {
1645
                            ChunkerPlayerGUI_SetStatsText(audio_stats_text, video_stats_text,LED_NONE);
1646
                        }
1647

    
1648
                        last_stats_evaluation = now;
1649
                }
1650
                
1651
                if((((now.tv_sec*1000)+(now.tv_usec/1000)) - ((last_qoe_evaluation.tv_sec*1000)+(last_qoe_evaluation.tv_usec/1000))) > EVAL_QOE_INTERVAL)
1652
                {
1653
                        // ESTIMATE QoE
1654
                        //ChunkerPlayerStats_GetMeanVideoQuality(&(videoq.PacketHistory), &qoe);
1655
                        // ESTIMATE QoE using real-time computed cumulative average bitrate
1656
                        // (plus a diminshing contribution of the instantaneous bitrate, until the cumulative avg stabilizes)
1657
                        int input_bitrate = 0;
1658
                        // stabilize after circa 30 seconds
1659
                        if(videoq.cumulative_samples < 30*(1000/GUI_PRINTSTATS_INTERVAL))
1660
                                input_bitrate = video_statistics.Bitrate;
1661
                        else
1662
                                input_bitrate = video_avg_bitrate;
1663
                        //double a = 1 / ((double)videoq.cumulative_samples);
1664
                        //double b = 1-a;
1665
                        //double input_bitrate = a*((double)video_statistics.Bitrate) + b*((double)video_avg_bitrate);
1666
                        ChunkerPlayerStats_GetMeanVideoQuality(&(videoq.PacketHistory), input_bitrate, &qoe);
1667
#ifdef DEBUG_STATS
1668
                        printf("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);
1669
#endif
1670
                        last_qoe_evaluation = now;
1671
                }
1672
        }
1673
        return 0;
1674
}
1675

    
1676
void ChunkerPlayerCore_ChangeDelay(int ms)
1677
{
1678
        DeltaTime += ms;
1679
}