Statistics
| Branch: | Revision:

chunker-player / chunker_player / player_core.c @ 37fc5455

History | View | Annotate | Download (49.7 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
int tcrop = 0;
96
int bcrop = 0;
97

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

    
104
//int lastCheckedVideoFrame = -1;
105
long int last_video_frame_extracted = -1;
106

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

    
123
  // Compute the time remaining to wait. tv_usec is certainly positive.
124
  result->tv_sec = x->tv_sec - y->tv_sec;
125
  result->tv_usec = x->tv_usec - y->tv_usec;
126

    
127
  // Return 1 if result is negative.
128
  return x->tv_sec < y->tv_sec;
129
}
130

    
131

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

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

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

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

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

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

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

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

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

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

    
264
        else
265
        {
266
                SDL_LockMutex(q->mutex);
267

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

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

    
337
        return res;
338
}
339

    
340
int OpenACodec (char *audio_codec, int sample_rate, short int audio_channels)
341
{
342
        AVCodec *aCodec;
343

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

    
361
        return 1;
362
}
363

    
364
int OpenAudio(AVCodecContext  *aCodecCtx)
365
{
366
        SDL_AudioSpec *wanted_spec;
367
        static SDL_AudioSpec *wanted_spec_old = NULL;
368

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

    
381
#ifdef DEBUG_AUDIO
382
        printf("wanted freq:%d\n",wanted_spec->freq);
383
        printf("wanted format:%d\n",wanted_spec->format);
384
        printf("wanted channels:%d\n",wanted_spec->channels);
385
        printf("wanted silence:%d\n",wanted_spec->silence);
386
        printf("wanted samples:%d\n",wanted_spec->samples);
387
#endif
388

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

    
395
        if(wanted_spec_old) {
396
                SDL_CloseAudio();
397
        }
398

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

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

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

    
416
#ifdef DEBUG_AUDIO
417
        printf("freq:%d\n",wanted_spec->freq);
418
        printf("format:%d\n",wanted_spec->format);
419
        printf("channels:%d\n",wanted_spec->channels);
420
        printf("silence:%d\n",wanted_spec->silence);
421
        printf("samples:%d\n",wanted_spec->samples);
422
        printf("size:%d\n",wanted_spec->size);
423
        printf("deltaAudioQ: %f\n",deltaAudioQ);
424
#endif
425

    
426
        return 1;
427
}
428

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

    
440

    
441
        if (OpenACodec(audio_codec, sample_rate, audio_channels) < 0) {
442
                return -1;
443
        }
444

    
445
        if (OpenAudio(aCodecCtx) < 1) {
446
                return -1;
447
        }
448

    
449
        outbuf_audio = malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
450

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

    
460
        return 0;
461
}
462

    
463
int ChunkerPlayerCore_InitVideoCodecs(char *v_codec, int width, int height)
464
{
465

    
466
        memset(&VideoCallbackThreadParams, 0, sizeof(ThreadVal));
467
        
468
        VideoCallbackThreadParams.width = width;
469
        VideoCallbackThreadParams.height = height;
470
        VideoCallbackThreadParams.video_codec = strdup(v_codec);
471

    
472
        //initialize the video queue
473
        PacketQueueInit(&videoq, VIDEO);
474

    
475
        // Init video buffers
476
        av_init_packet(&VideoPkt);
477

    
478
        VideoPkt.data=(uint8_t *)malloc(width*height*3/2);
479
        if(!VideoPkt.data) return -1;
480

    
481
        return 0;
482
}
483

    
484
int ChunkerPlayerCore_InitCodecs(char *v_codec, int width, int height, char *audio_codec, int sample_rate, short int audio_channels)
485
{
486
        char audio_stats[255], video_stats[255];
487

    
488
        // Register all formats and codecs
489
        av_log_set_level(AV_LOG_WARNING);
490
        avcodec_init();
491
        av_register_all();
492

    
493
        if (ChunkerPlayerCore_InitAudioCodecs(audio_codec, sample_rate, audio_channels) < 0) {
494
                return -1;
495
        }
496

    
497
        if (ChunkerPlayerCore_InitVideoCodecs(v_codec, width, height) < 0) {
498
                return -1;
499
        }
500

    
501
        av_log_set_level(AV_LOG_ERROR);
502

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

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

    
516
        //set the flag to decoded anyway        
517
        pkt->convergence_duration = -1;
518

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

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

    
572
        if (q->first_pkt == p) {
573
                q->first_pkt = p->next;
574
        }
575
        if (&(p->pkt) == q->minpts_pkt) {
576
                q->minpts_pkt = NULL;
577
        }
578

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

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

    
598
        return retpk;
599
}
600

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

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

    
628
        SDL_LockMutex(q->mutex);
629

    
630
#ifdef DEBUG_QUEUE
631
        printf("QUEUE: Get NPackets=%d Type=%s\n", q->nb_packets, (q->queueType==AUDIO) ? "AUDIO" : "VIDEO");
632
#endif
633

    
634
        if((q->queueType==AUDIO && QueueFillingMode) || QueueStopped)
635
        {
636
                SDL_UnlockMutex(q->mutex);
637
                return -1;
638
        }
639

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

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

    
674
                        //update index of last frame extracted
675
                        //ChunkerPlayerStats_UpdateAudioLossHistory(&(q->PacketHistory), pkt->stream_index, q->last_frame_extracted);
676
                        q->last_frame_extracted = pkt->stream_index;
677

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

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

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

    
727
        SDL_UnlockMutex(q->mutex);
728
        return ret;
729
}
730

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

    
739
        //gettimeofday(&now,NULL);
740
        //Now = (now.tv_sec)*1000+now.tv_usec/1000;
741
        Now=(long long)SDL_GetTicks();
742

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

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

    
766
#ifdef DEBUG_AUDIO 
767
        if(audioq.first_pkt)
768
        {
769
                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);
770
                printf("AUDIO: QueueLen=%d ",(int)audioq.nb_packets);
771
                printf("AUDIO: QueueSize=%d\n",(int)audioq.size);
772
        }
773
        else
774
                printf("AUDIO: audio_decode_frame - Empty queue\n");
775
#endif
776

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

    
829
                ChunkerPlayerStats_UpdateAudioPlayedHistory(&(audioq.PacketHistory), AudioPkt.stream_index, compressed_size);
830
        }
831

    
832
        return audio_pkt_size;
833
}
834

    
835

    
836
void ChunkerPlayerCore_SetYCrop(int t, int b){
837
        tcrop = t;
838
        bcrop = b;
839
}
840

    
841
// Render a Frame to a YUV Overlay. Note that the Overlay is already bound to an SDL Surface
842
// Note that width, height would not be needed in new ffmpeg versions where this info is contained in AVFrame
843
// see: [FFmpeg-devel] [PATCH] lavc: add width and height fields to AVFrame
844
int RenderFrame2Overlay(AVFrame *pFrame, int frame_width, int frame_height, int tcrop, int bcrop,  SDL_Overlay *YUVOverlay)
845
{
846
        AVPicture pict;
847
        unsigned int ycrop = 50;
848
        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)
849

    
850
                                        if(SDL_LockYUVOverlay(YUVOverlay) < 0) {
851
                                                return -1;
852
                                        }
853

    
854
                                        pict.data[0] = YUVOverlay->pixels[0];
855
                                        pict.data[1] = YUVOverlay->pixels[2];
856
                                        pict.data[2] = YUVOverlay->pixels[1];
857

    
858
                                        pict.linesize[0] = YUVOverlay->pitches[0];
859
                                        pict.linesize[1] = YUVOverlay->pitches[2];
860
                                        pict.linesize[2] = YUVOverlay->pitches[1];
861

    
862
                                        img_convert_ctx = sws_getCachedContext(img_convert_ctx, frame_width, frame_height - tcrop - bcrop, PIX_FMT_YUV420P, YUVOverlay->w, YUVOverlay->h, PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);
863
                                        if(img_convert_ctx == NULL) {
864
                                                fprintf(stderr, "Cannot initialize the conversion context!\n");
865
                                                exit(1);
866
                                        }
867

    
868
                                        // let's draw the data (*yuv[3]) on a SDL screen (*screen)
869
                                        sws_scale(img_convert_ctx, pFrame->data, pFrame->linesize, -tcrop, frame_height - bcrop, pict.data, pict.linesize);
870
                                        SDL_UnlockYUVOverlay(YUVOverlay);
871

    
872
        return 0;
873
}
874

    
875
// Render a YUV Overlay to the specified Rect of the Surface. Note that the Overlay is already bound to an SDL Surface.
876
int RenderOverlay2Rect(SDL_Overlay *YUVOverlay, SDL_Rect *Rect)
877
{
878

    
879
                                        // Lock SDL_yuv_overlay
880
                                        if(SDL_MUSTLOCK(MainScreen)) {
881
                                                if(SDL_LockSurface(MainScreen) < 0) {
882
                                                        return -1;
883
                                                }
884
                                        }
885

    
886
                                        // Show, baby, show!
887
                                        SDL_LockMutex(OverlayMutex);
888
                                        SDL_DisplayYUVOverlay(YUVOverlay, Rect);
889
                                        SDL_UnlockMutex(OverlayMutex);
890

    
891
                                        if(SDL_MUSTLOCK(MainScreen)) {
892
                                                SDL_UnlockSurface(MainScreen);
893
                                        }
894

    
895
        return 0;
896

    
897
}
898

    
899

    
900
int VideoCallback(void *valthread)
901
{
902
        //AVPacket pktvideo;
903
        AVCodecContext  *pCodecCtx;
904
        AVCodec         *pCodec;
905
        AVFrame         *pFrame;
906
        int frameFinished;
907
        long long Now;
908
        long long Last = 0;
909
        short int SkipVideo, DecodeVideo;
910
        uint64_t last_pts = 0;
911
        long long decode_delay = 0;
912
        int queue_size_checked = 0;
913
        
914
#ifdef SAVE_YUV
915
        static AVFrame* lastSavedFrameBuffer = NULL;
916
        
917
        if(!lastSavedFrameBuffer)
918
                lastSavedFrameBuffer = (AVFrame*) malloc(sizeof(AVFrame));
919
#endif
920

    
921
        //double frame_rate = 0.0,time_between_frames=0.0;
922
        //struct timeval now;
923

    
924
        //int wait_for_sync = 1;
925
        ThreadVal *tval;
926
        tval = (ThreadVal *)valthread;
927

    
928
        //frame_rate = tval->framerate;
929
        //time_between_frames = 1.e6 / frame_rate;
930
        //gettimeofday(&time_now,0);
931

    
932
        //frecon = fopen("recondechunk.mpg","wb");
933

    
934
        //setup video decoder
935
        pCodec = avcodec_find_decoder_by_name(tval->video_codec);
936
        if (pCodec) {
937
                fprintf(stderr, "INIT: Setting VIDEO codecID to: %d\n",pCodec->id);
938
        } else {
939
                fprintf(stderr, "INIT: Unknown VIDEO codec: %s!\n", tval->video_codec);
940
                return -1; // Codec not found
941
        }
942

    
943
        pCodecCtx=avcodec_alloc_context();
944
        pCodecCtx->codec_type = CODEC_TYPE_VIDEO;
945
        //pCodecCtx->debug = FF_DEBUG_DCT_COEFF;
946
        pCodecCtx->codec_id = pCodec->id;
947

    
948
        //pCodecCtx->bit_rate = 400000;
949
        // resolution must be a multiple of two
950
        pCodecCtx->width = tval->width;//176;//352;
951
        pCodecCtx->height = tval->height;//144;//288;
952

    
953
        // frames per second
954
        //pCodecCtx->time_base = (AVRational){1,25};
955
        //pCodecCtx->gop_size = 10; // emit one intra frame every ten frames
956
        //pCodecCtx->max_b_frames=1;
957
        pCodecCtx->pix_fmt = PIX_FMT_YUV420P;
958
        pCodec=avcodec_find_decoder(pCodecCtx->codec_id);
959

    
960
        if(pCodec==NULL) {
961
                fprintf(stderr, "Unsupported codec!\n");
962
                return -1; // Codec not found
963
        }
964
        if(avcodec_open(pCodecCtx, pCodec) < 0) {
965
                fprintf(stderr, "could not open codec\n");
966
                return -1; // Could not open codec
967
        }
968
        pFrame=avcodec_alloc_frame();
969
        if(pFrame==NULL) {
970
                printf("Memory error!!!\n");
971
                return -1;
972
        }
973
        
974
#ifdef DEBUG_VIDEO
975
         printf("VIDEO: video_callback entering main cycle\n");
976
#endif
977

    
978
        while(AVPlaying && !quit) {
979

    
980
                if(QueueFillingMode || QueueStopped)
981
                {
982
                        //SDL_LockMutex(timing_mutex);
983
                        FirstTime = 1;
984
                        //SDL_UnlockMutex(timing_mutex);
985
                        usleep(5000);
986
                        continue;
987
                }
988

    
989
                DecodeVideo = 0;
990
                SkipVideo = 0;
991
                Now=(long long)SDL_GetTicks();
992
                if(FirstTime==1 && videoq.size>0) {
993
                        if(videoq.first_pkt->pkt.pts>0)
994
                        {
995
                                //SDL_LockMutex(timing_mutex);
996
                                DeltaTime=Now-(long long)videoq.first_pkt->pkt.pts;
997
                                FirstTime = 0;
998
                                FirstTimeAudio = 0;
999
                                //SDL_UnlockMutex(timing_mutex);
1000
                        }
1001
#ifdef DEBUG_VIDEO 
1002
                         printf("VIDEO: VideoCallback - DeltaTimeAudio=%lld\n",DeltaTime);
1003
#endif
1004
                }
1005

    
1006
#ifdef DEBUG_VIDEO 
1007
                if(videoq.first_pkt)
1008
                {
1009
                        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);
1010
                        printf("VIDEO: Index=%d ", (int)videoq.first_pkt->pkt.stream_index);
1011
                        printf("VIDEO: QueueLen=%d ", (int)videoq.nb_packets);
1012
                        printf("VIDEO: QueueSize=%d\n", (int)videoq.size);
1013
                }
1014
                else
1015
                        printf("VIDEO: VideoCallback - Empty queue\n");
1016
#endif
1017

    
1018
#ifdef DEBUG_VIDEO
1019
                printf("VIDEO: skipvideo:%d decodevideo:%d\n",SkipVideo,DecodeVideo);
1020
#endif
1021
//                        ChunkerPlayerStats_UpdateVideoSkipHistory(&(videoq.PacketHistory), VideoPkt.stream_index, pFrame->pict_type, VideoPkt.size, pFrame);
1022

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

    
1046
                                if(frameFinished)
1047
                                { // it must be true all the time else error
1048

    
1049
                                        long long target_pts = pFrame->pkt_pts + DeltaTime;
1050
                                        long long earlier = target_pts - Now;
1051

    
1052
#ifdef DEBUG_VIDEO
1053
                                        printf("VIDEO: FrameFinished\n");
1054
#endif
1055
                                        decoded_vframes++;
1056
                                        
1057

    
1058
#ifdef VIDEO_DEINTERLACE
1059
                                        avpicture_deinterlace(
1060
                                                (AVPicture*) pFrame,
1061
                                                (const AVPicture*) pFrame,
1062
                                                pCodecCtx->pix_fmt,
1063
                                                tval->width, tval->height);
1064
#endif
1065

    
1066
#ifdef SAVE_YUV
1067
                                        if(LastSavedVFrame == -1)
1068
                                        {
1069
                                                memcpy(lastSavedFrameBuffer, pFrame, sizeof(AVFrame));
1070
                                                SaveFrame(pFrame, pCodecCtx->width, pCodecCtx->height);
1071
                                                LastSavedVFrame = VideoPkt.stream_index;
1072
                                        }
1073
                                        else if(LastSavedVFrame == (VideoPkt.stream_index-1))
1074
                                        {
1075
                                                memcpy(lastSavedFrameBuffer, pFrame, sizeof(AVFrame));
1076
                                                SaveFrame(pFrame, pCodecCtx->width, pCodecCtx->height);
1077
                                                LastSavedVFrame = VideoPkt.stream_index;
1078
                                        }
1079
                                        else if(LastSavedVFrame >= 0)
1080
                                        {
1081
                                                while(LastSavedVFrame < (VideoPkt.stream_index-1))
1082
                                                {
1083
                                                        SaveFrame(lastSavedFrameBuffer, pCodecCtx->width, pCodecCtx->height);
1084
                                                }
1085

    
1086
                                                memcpy(lastSavedFrameBuffer, pFrame, sizeof(AVFrame));
1087
                                                SaveFrame(pFrame, pCodecCtx->width, pCodecCtx->height);
1088
                                                LastSavedVFrame = VideoPkt.stream_index;
1089
                                        }
1090
#endif
1091
                                        ChunkerPlayerStats_UpdateVideoPlayedHistory(&(videoq.PacketHistory), VideoPkt.stream_index, pFrame->pict_type, VideoPkt.size, pFrame);
1092

    
1093
                                        if(SilentMode)
1094
                                                continue;
1095

    
1096
                                        SDL_LockMutex(OverlayMutex);
1097
                                        if (RenderFrame2Overlay(pFrame, pCodecCtx->width, pCodecCtx->height, tcrop, bcrop, YUVOverlay) < 0){
1098
                                                SDL_UnlockMutex(OverlayMutex);
1099
                                                continue;
1100
                                        }
1101

    
1102
                                        //wait for the playback time
1103
#ifdef DEBUG_SYNC
1104
                                        fprintf(stderr, "VIDEO earlier =%lld ms\n",earlier);
1105
#endif
1106
                                        if (earlier > 0) {
1107
                                                usleep(MIN(earlier,1000) * 1000);
1108
//                                        } else if (earlier < 0) {
1109
//                                                fprintf(stderr, "should increase delay2 : pFrame->pkt_pts=%lld, DeltaTime=%lld, Now=%lld, earlier=%lld\n", pFrame->pkt_pts, DeltaTime, Now, earlier);
1110
//                                                DeltaTime -= earlier;
1111
                                        }
1112

    
1113
                                        Last = Now;
1114

    
1115
                                        if (RenderOverlay2Rect(YUVOverlay, ChunkerPlayerGUI_GetMainOverlayRect()) < 0) {
1116
                                                SDL_UnlockMutex(OverlayMutex);
1117
                                                continue;
1118
                                        }
1119
                                        SDL_UnlockMutex(OverlayMutex);
1120

    
1121
                                        //redisplay logo
1122
                                        /**SDL_BlitSurface(image, NULL, MainScreen, &dest);*/
1123
                                        /* Update the screen area just changed */
1124
                                        /**SDL_UpdateRects(MainScreen, 1, &dest);*/
1125
                                } //if FrameFinished
1126
                                else
1127
                                {
1128
                                        ChunkerPlayerStats_UpdateVideoLossHistory(&(videoq.PacketHistory), VideoPkt.stream_index+1, videoq.last_frame_extracted-1);
1129
                                }
1130
                            }
1131
                        }
1132
                        usleep(5000);
1133
                }
1134
                usleep(5000);
1135
        }
1136
        avcodec_close(pCodecCtx);
1137
        av_free(pCodecCtx);
1138
        av_free(pFrame);
1139
        //fclose(frecon);
1140
#ifdef DEBUG_VIDEO
1141
         printf("VIDEO: video callback end\n");
1142
#endif
1143

    
1144
#ifdef SAVE_YUV
1145
        if(!lastSavedFrameBuffer)
1146
                free(lastSavedFrameBuffer);
1147
        
1148
        lastSavedFrameBuffer = NULL;
1149
#endif
1150

    
1151
        return 0;
1152
}
1153

    
1154
void AudioCallback(void *userdata, Uint8 *stream, int len)
1155
{
1156
        //AVCodecContext *aCodecCtx = (AVCodecContext *)userdata;
1157
        int audio_size;
1158

    
1159
        static uint8_t audio_buf[AVCODEC_MAX_AUDIO_FRAME_SIZE];
1160

    
1161
        memset(audio_buf, CurrentAudioSilence, sizeof(audio_buf));
1162
        audio_size = AudioDecodeFrame(audio_buf, sizeof(audio_buf));
1163
        
1164
        if(SilentMode < 2) {
1165
                if(audio_size != len) {
1166
                        memset(stream, CurrentAudioSilence, len);
1167
                } else {
1168
                        memcpy(stream, (uint8_t *)audio_buf, len);
1169
                }
1170
        }
1171
}
1172

    
1173
void SaveFrame(AVFrame *pFrame, int width, int height)
1174
{
1175
        FILE *pFile;
1176
        int  y;
1177
  
1178
         // Open file
1179
        pFile=fopen(YUVFileName, "ab");
1180
        if(pFile==NULL)
1181
                return;
1182
  
1183
        // Write header
1184
        //fprintf(pFile, "P5\n%d %d\n255\n", width, height);
1185
  
1186
        // Write Y data
1187
        for(y=0; y<height; y++)
1188
                  fwrite(pFrame->data[0]+y*pFrame->linesize[0], 1, width, pFile);
1189
        // Write U data
1190
        for(y=0; y<height/2; y++)
1191
                  fwrite(pFrame->data[1]+y*pFrame->linesize[1], 1, width/2, pFile);
1192
        // Write V data
1193
        for(y=0; y<height/2; y++)
1194
                  fwrite(pFrame->data[2]+y*pFrame->linesize[2], 1, width/2, pFile);
1195
  
1196
        // Close file
1197
        fclose(pFile);
1198
}
1199

    
1200
int ChunkerPlayerCore_IsRunning()
1201
{
1202
        return AVPlaying;
1203
}
1204

    
1205
void ChunkerPlayerCore_Play()
1206
{
1207
        if(AVPlaying) return;
1208
        AVPlaying = 1;
1209
        
1210
        SDL_PauseAudio(0);
1211
        video_thread = SDL_CreateThread(VideoCallback, &VideoCallbackThreadParams);
1212
        ChunkerPlayerStats_Init(&VideoCallbackThreadParams);
1213
        stats_thread = SDL_CreateThread(CollectStatisticsThread, NULL);
1214
        
1215
        decoded_vframes = 0;
1216
        LastSavedVFrame = -1;
1217
}
1218

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

    
1256
void ChunkerPlayerCore_Finalize()
1257
{
1258
        if(YUVOverlay != NULL)
1259
        {
1260
                SDL_FreeYUVOverlay(YUVOverlay);
1261
                YUVOverlay = NULL;
1262
        }
1263

    
1264
        SDL_CloseAudio();
1265
}
1266

    
1267
void ChunkerPlayerCore_Pause()
1268
{
1269
        if(!AVPlaying) return;
1270
        
1271
        AVPlaying = 0;
1272
        
1273
        // Stop audio&video playback
1274
        SDL_WaitThread(video_thread, NULL);
1275
        SDL_PauseAudio(1);
1276
        
1277
        PacketQueueReset(&audioq);
1278
        PacketQueueReset(&videoq);
1279
}
1280

    
1281
int ChunkerPlayerCore_AudioEnded()
1282
{
1283
        return (audioq.nb_packets==0 && audioq.last_frame_extracted>0);
1284
}
1285

    
1286
void ChunkerPlayerCore_ResetAVQueues()
1287
{
1288
#ifdef DEBUG_QUEUE
1289
        printf("QUEUE: MAIN SHOULD RESET\n");
1290
#endif
1291
        PacketQueueReset(&audioq);
1292
        PacketQueueReset(&videoq);
1293
}
1294

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

    
1341
        Chunk *gchunk = NULL;
1342
        int decoded_size = -1;
1343
        uint8_t *tempdata, *buffer;
1344
        int j;
1345
        Frame *frame = NULL;
1346
        AVPacket packet, packetaudio;
1347

    
1348
        uint16_t *audio_bufQ = NULL;
1349

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

    
1355
        static int chunks_out_of_order = 0;
1356
        static int last_chunk_id = -1;
1357

    
1358
        audio_bufQ = (uint16_t *)av_malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
1359
        if(!audio_bufQ) {
1360
                printf("Memory error in audio_bufQ!\n");
1361
                return PLAYER_FAIL_RETURN;
1362
        }
1363

    
1364
        gchunk = (Chunk *)malloc(sizeof(Chunk));
1365
        if(!gchunk) {
1366
                printf("Memory error in gchunk!\n");
1367
                av_free(audio_bufQ);
1368
                return PLAYER_FAIL_RETURN;
1369
        }
1370

    
1371
        decoded_size = decodeChunk(gchunk, block, block_size);
1372

    
1373
        if(last_chunk_id == -1)
1374
                last_chunk_id = gchunk->id;
1375

    
1376
        if(gchunk->id > (last_chunk_id+1)) {
1377
                chunks_out_of_order += gchunk->id - last_chunk_id - 1;
1378
        }
1379
        last_chunk_id = gchunk->id;
1380

    
1381
#ifdef DEBUG_CHUNKER
1382
        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);
1383
#endif
1384
  if(decoded_size < 0) {
1385
                //HINT here i should differentiate between various return values of the decode
1386
                //in order to free what has been allocated there
1387
                printf("chunk probably corrupted!\n");
1388
                av_free(audio_bufQ);
1389
                free(gchunk);
1390
                return PLAYER_FAIL_RETURN;
1391
        }
1392

    
1393
        frame = (Frame *)malloc(sizeof(Frame));
1394
        if(!frame) {
1395
                printf("Memory error in Frame!\n");
1396
                if(gchunk) {
1397
                        if(gchunk->attributes) {
1398
                                free(gchunk->attributes);
1399
                        }
1400
                        free(gchunk);
1401
                }
1402
                av_free(audio_bufQ);
1403
                return PLAYER_FAIL_RETURN;
1404
        }
1405

    
1406
        tempdata = gchunk->data; //let it point to first frame of payload
1407
        j=gchunk->size;
1408
        while(j>0 && !quit) {
1409
                frame->number = bit32_encoded_pull(tempdata);
1410
                tempdata += CHUNK_TRANSCODING_INT_SIZE;
1411
                frame->timestamp.tv_sec = bit32_encoded_pull(tempdata);
1412
                tempdata += CHUNK_TRANSCODING_INT_SIZE;
1413
                frame->timestamp.tv_usec = bit32_encoded_pull(tempdata);
1414
                tempdata += CHUNK_TRANSCODING_INT_SIZE;
1415
                frame->size = bit32_encoded_pull(tempdata);
1416
                tempdata += CHUNK_TRANSCODING_INT_SIZE;
1417
                frame->type = bit32_encoded_pull(tempdata);
1418
                tempdata += CHUNK_TRANSCODING_INT_SIZE;
1419

    
1420
                buffer = tempdata; // here coded frame information
1421
                tempdata += frame->size; //let it point to the next frame
1422

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

    
1439
#ifdef DEBUG_SOURCE
1440
                        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);
1441
#endif
1442
                }
1443
                else if(frame->type == 5) { // audio frame
1444
                        av_init_packet(&packetaudio);
1445
                        packetaudio.data = buffer;
1446
                        packetaudio.size = frame->size;
1447
                        packetaudio.pts = frame->timestamp.tv_sec*(unsigned long long)1000+frame->timestamp.tv_usec;
1448
                        packetaudio.dts = frame->timestamp.tv_sec*(unsigned long long)1000+frame->timestamp.tv_usec;
1449
                        //packetaudio.duration = frame->timestamp.tv_sec;
1450
                        packetaudio.stream_index = frame->number; // use of stream_index for number frame
1451
                        packetaudio.flags = 1;
1452
                        packetaudio.pos = -1;
1453

    
1454
                        //instead of -1, in order to signal it is not decoded yet
1455
                        packetaudio.convergence_duration = 0;
1456

    
1457
                        // insert the audio frame into the queue
1458
                        if(packetaudio.size > 0) {
1459
                                int ret = ChunkerPlayerCore_PacketQueuePut(&audioq, &packetaudio);//makes a copy of the packet so i can free here
1460
                                if (ret == 1) {        //TODO: check and correct return values
1461
                                        fprintf(stderr, "late chunk received, increasing delay to %lld\n", DeltaTime);
1462
                                        DeltaTime += 5;        //TODO: handle audio skip; verify this value
1463
                                }
1464
                        }
1465

    
1466
#ifdef DEBUG_SOURCE
1467
                        printf("SOURCE: Insert audio in queue pts=%lld sindex:%d\n", packetaudio.pts, packetaudio.stream_index);
1468
#endif
1469
                }
1470
                else {
1471
                        printf("SOURCE: Unknown frame type %d. Size %d\n", frame->type, frame->size);
1472
                }
1473
                if(frame->size > 0)
1474
                        j = j - sizeFrameHeader - frame->size;
1475
                else {
1476
                        printf("SOURCE: Corrupt frames (size %d) in chunk. Skipping it...\n", frame->size);
1477
                        j = -1;
1478
                }
1479
        }
1480
        //chunk ingestion terminated!
1481
        if(gchunk) {
1482
                if(gchunk->attributes) {
1483
                        free(gchunk->attributes);
1484
                }
1485
                if(gchunk->data)
1486
                        free(gchunk->data);
1487
                free(gchunk);
1488
        }
1489
        if(frame)
1490
                free(frame);
1491
        if(audio_bufQ)
1492
                av_free(audio_bufQ);
1493
                
1494
        return PLAYER_OK_RETURN;
1495
}
1496

    
1497
void ChunkerPlayerCore_SetupOverlay(int width, int height)
1498
{
1499
        // if(!MainScreen && !SilentMode)
1500
        // {
1501
                // printf("Cannot find main screen, exiting...\n");
1502
                // exit(1);
1503
        // }
1504
        
1505
        if(SilentMode)
1506
                return;
1507

    
1508
        //TODO: return with error if size is too small
1509
        width = MAX(width, 8);
1510
        height = MAX(height, 8);
1511

    
1512
        SDL_LockMutex(OverlayMutex);
1513
        if(YUVOverlay != NULL)
1514
        {
1515
                SDL_FreeYUVOverlay(YUVOverlay);
1516
                YUVOverlay = NULL;
1517
        }
1518
        
1519
        // create video overlay for display of video frames
1520
        // printf("SDL_CreateYUVOverlay(%d, %d, SDL_YV12_OVERLAY, MainScreen)\n", width, height);
1521
        YUVOverlay = SDL_CreateYUVOverlay(width, height, SDL_YV12_OVERLAY, MainScreen);
1522
        if ( YUVOverlay == NULL )
1523
        {
1524
                fprintf(stderr,"SDL: Couldn't create SDL_yuv_overlay: %s", SDL_GetError());
1525
                exit(1);
1526
        }
1527

    
1528
        if ( YUVOverlay->hw_overlay )
1529
                fprintf(stderr,"SDL: Using hardware overlay.\n");
1530
        
1531
        SDL_DisplayYUVOverlay(YUVOverlay, ChunkerPlayerGUI_GetMainOverlayRect());
1532
        
1533
        SDL_UnlockMutex(OverlayMutex);
1534
}
1535

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

    
1567
                        // compute avg bitrate up to now
1568
                        audioq.cumulative_bitrate += audio_statistics.Bitrate;
1569
                        audioq.cumulative_samples++;
1570
                        audio_avg_bitrate = (int)( ((double)audioq.cumulative_bitrate) / ((double)audioq.cumulative_samples) );
1571
                        videoq.cumulative_bitrate += video_statistics.Bitrate;
1572
                        videoq.cumulative_samples++;
1573
                        video_avg_bitrate = (int)( ((double)videoq.cumulative_bitrate) / ((double)videoq.cumulative_samples) );
1574

    
1575
#ifdef DEBUG_STATS
1576
                        printf("VIDEO: %d Kbit/sec; ", video_statistics.Bitrate);
1577
                        printf("AUDIO: %d Kbit/sec\n", audio_statistics.Bitrate);
1578
#endif
1579

    
1580
                        // QUEUE DENSITY EVALUATION
1581
                        if((audioq.last_pkt != NULL) && (audioq.first_pkt != NULL))
1582
                                if(audioq.last_pkt->pkt.stream_index >= audioq.first_pkt->pkt.stream_index)
1583
                                {
1584
                                        //plus 1 because if they are adjacent (difference 1) there really should be 2 packets in the queue
1585
                                        audio_qdensity = (double)audioq.nb_packets / (double)(audioq.last_pkt->pkt.stream_index - audioq.first_pkt->pkt.stream_index + 1) * 100.0;
1586
                                }
1587
                        
1588
                        if((videoq.last_pkt != NULL) && (videoq.first_pkt != NULL))
1589
                                if(videoq.last_pkt->pkt.stream_index >= videoq.first_pkt->pkt.stream_index)
1590
                                {
1591
                                        // plus 1 because if they are adjacent (difference 1) there really should be 2 packets in the queue
1592
                                        video_qdensity = (double)videoq.nb_packets / (double)(videoq.last_pkt->pkt.stream_index - videoq.first_pkt->pkt.stream_index + 1) * 100.0;
1593
                                }
1594
                        
1595
                        if(LogTraces)
1596
                        {
1597
                                ChunkerPlayerStats_PrintHistoryTrace(&(audioq.PacketHistory), AudioTraceFilename);
1598
                                ChunkerPlayerStats_PrintHistoryTrace(&(videoq.PacketHistory), VideoTraceFilename);
1599
                                
1600
                                //if(SilentMode != 1 && SilentMode != 2)
1601
                                        ChunkerPlayerStats_PrintContextFile();
1602
                        }
1603

    
1604
                        // PRINT STATISTICS ON GUI
1605
                        if(!Audio_ON)
1606
                                sprintf(audio_stats_text, "AUDIO MUTED");
1607
                        else if(audio_stats_changed)
1608
//                                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);
1609
                                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);
1610
                        else
1611
                                sprintf(audio_stats_text, "waiting for incoming audio packets...");
1612

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

    
1649
//                                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);
1650
                                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);
1651
                        }
1652
                        else
1653
                                sprintf(video_stats_text, "waiting for incoming video packets...");
1654
                        
1655
                        if(qoe && qoe_led) {
1656
                            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)));
1657
                        } else {
1658
                            ChunkerPlayerGUI_SetStatsText(audio_stats_text, video_stats_text,LED_NONE);
1659
                        }
1660

    
1661
                        last_stats_evaluation = now;
1662
                }
1663
                
1664
                if((((now.tv_sec*1000)+(now.tv_usec/1000)) - ((last_qoe_evaluation.tv_sec*1000)+(last_qoe_evaluation.tv_usec/1000))) > EVAL_QOE_INTERVAL)
1665
                {
1666
                        // ESTIMATE QoE
1667
                        //ChunkerPlayerStats_GetMeanVideoQuality(&(videoq.PacketHistory), &qoe);
1668
                        // ESTIMATE QoE using real-time computed cumulative average bitrate
1669
                        // (plus a diminshing contribution of the instantaneous bitrate, until the cumulative avg stabilizes)
1670
                        int input_bitrate = 0;
1671
                        // stabilize after circa 30 seconds
1672
                        if(videoq.cumulative_samples < 30*(1000/GUI_PRINTSTATS_INTERVAL))
1673
                                input_bitrate = video_statistics.Bitrate;
1674
                        else
1675
                                input_bitrate = video_avg_bitrate;
1676
                        //double a = 1 / ((double)videoq.cumulative_samples);
1677
                        //double b = 1-a;
1678
                        //double input_bitrate = a*((double)video_statistics.Bitrate) + b*((double)video_avg_bitrate);
1679
                        ChunkerPlayerStats_GetMeanVideoQuality(&(videoq.PacketHistory), input_bitrate, &qoe);
1680
#ifdef DEBUG_STATS
1681
                        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);
1682
#endif
1683
                        last_qoe_evaluation = now;
1684
                }
1685
        }
1686
        return 0;
1687
}
1688

    
1689
void ChunkerPlayerCore_ChangeDelay(int ms)
1690
{
1691
        DeltaTime += ms;
1692
}