summaryrefslogtreecommitdiffstats
path: root/core/Fifo.c
blob: a8f6034c041e6c97d5bc6b024e2cfa642593b142 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/* $Id: Fifo.c,v 1.2 2003/11/05 19:14:37 titer Exp $

   This file is part of the HandBrake source code.
   Homepage: <http://handbrake.m0k.org/>.
   It may be used under the terms of the GNU General Public License. */

#include "Fifo.h"

HBBuffer * HBBufferInit( int size )
{
    HBBuffer * b;
    if( !( b = malloc( sizeof( HBBuffer ) ) ) )
    {
        HBLog( "HBBufferInit: malloc() failed, gonna crash" );
        return NULL;
    }

    b->alloc = size;
    b->size  = size;

    if( !( b->data = malloc( size ) ) )
    {
        HBLog( "HBBufferInit: malloc() failed, gonna crash" );
        free( b );
        return NULL;
    }

    b->position = 0.0;
    b->streamId = 0;
    b->keyFrame = 0;
    b->pts      = 0;
    b->pass     = 0;
    b->last     = 0;

    return b;
}

void HBBufferReAlloc( HBBuffer * b, int size )
{
    b->alloc = size;
    b->data  = realloc( b->data, size );

    if( !b->data )
    {
        HBLog( "HBBufferReAlloc: realloc() failed, gonna crash soon" );
    }
}

void HBBufferClose( HBBuffer ** b )
{
    free( (*b)->data );
    (*b) = NULL;
}

HBFifo * HBFifoInit( int capacity )
{
    HBFifo * f;
    if( !( f = malloc( sizeof( HBFifo ) ) ) )
    {
        HBLog( "HBFifoInit: malloc() failed, gonna crash" );
        return NULL;
    }

    f->capacity    = capacity;
    f->whereToPush = 0;
    f->whereToPop  = 0;

    if( !( f->buffers = malloc( ( capacity + 1 ) * sizeof( void* ) ) ) )
    {
        HBLog( "HBFifoInit: malloc() failed, gonna crash" );
        free( f );
        return NULL;
    }
    
    f->lock = HBLockInit();

    return f;
}

int HBFifoSize( HBFifo * f )
{
    return ( f->capacity + 1 + f->whereToPush - f->whereToPop ) %
                 ( f->capacity + 1 );
}

void HBFifoClose( HBFifo ** _f )
{
    HBFifo * f = (*_f);
    
    HBLog( "HBFifoClose: trashing %d buffer%s",
           HBFifoSize( f ), ( HBFifoSize( f ) > 1 ) ? "s" : "" );

    while( f->whereToPush != f->whereToPop )
    {
        HBBufferClose( &(f->buffers[f->whereToPop]) );
        f->whereToPop++;
        f->whereToPop %= ( f->capacity + 1 );
    }

    HBLockClose( &f->lock );
    free( f->buffers );
    free( f );
    (*_f) = NULL;
}