Switch to unified view

a b/src/mediaserver/cdplugins/abuffer.h
1
#ifndef _ABUFFER_H_INCLUDED_
2
#define _ABUFFER_H_INCLUDED_
3
4
#include <stdlib.h>
5
#include <string.h>
6
7
/// Data buffer used on the queue.
8
///
9
/// The implementation details are public because this may be used
10
/// externally when inserting an intermediary queue to process the
11
/// data.
12
///
13
/// This is a very raw structure and it is never shared. Either
14
/// the data producer or consumer has exclusive use until the
15
/// buffer is passed on.
16
///
17
/// The producer possibly allocates a buffer (or retrieves a
18
/// recycled one from somewhere), copies data to it, setting the
19
/// 'bytes' value, then passes it on.
20
///
21
/// The consumer gets the buffer from a queue, then does what it
22
/// needs with the data, possibly in several chunks, using the
23
/// curoffs field to keep track. curoffs is private to the
24
/// consumer (nornally set to zero when getting the buffer).
25
struct ABuffer {
26
    ABuffer(size_t bufsize)
27
        : buf((char*)malloc(bufsize)), allocbytes(bufsize),
28
          bytes(0), curoffs(0) { }
29
30
    // @param buf is is a malloced buffer, and we take ownership. The
31
    //   caller MUST NOT free it.
32
    // @param bufsize buffer allocated size in bytes.
33
    // @param bytes data contents size. 
34
    ABuffer(char *buf, size_t bufsize, size_t bytes)
35
        : buf(buf), allocbytes(bufsize), bytes(bytes), curoffs(0) { }
36
37
    ~ABuffer() {
38
        if (buf)
39
            free(buf);
40
    }
41
42
    bool setminalloc(size_t minbytes) {
43
        if (allocbytes >= minbytes) {
44
            return true;
45
        }
46
        if ((buf = (char *)realloc(buf, minbytes)) == nullptr) {
47
            return false;
48
        }
49
        allocbytes = minbytes;
50
        return true;
51
    }
52
53
    // Append data. This should not be used casually as we don't take
54
    // much care to make the reallocation efficient. Typically, this
55
    // is only used to buffer a bit of data at the beginning of the
56
    // stream for header forensics.
57
    bool append(const char *data, int cnt) {
58
        if (!setminalloc(2*(cnt+bytes))) {
59
            return false;
60
        }
61
        memcpy(buf + bytes, data, cnt);
62
        bytes += cnt;
63
        return true;
64
    }
65
    
66
    ABuffer *dup() {
67
        ABuffer *n = new ABuffer(bytes);
68
        if (nullptr == n || nullptr == n->buf) {
69
            return nullptr;
70
        }
71
        memcpy(n->buf, buf, bytes);
72
        n->bytes = bytes;
73
        return n;
74
    }
75
    
76
    char *buf;
77
    unsigned int allocbytes; // buffer size
78
    unsigned int bytes; // Useful bytes, set by producer.
79
    unsigned int curoffs; // Current offset in data, used by the consumer
80
};
81
82
#endif /* _ABUFFER_H_INCLUDED_ */