1+ //
2+ // Created by frank on 2018/2/3.
3+ //
4+ #include "AVpacket_queue.h"
5+ #include <stdlib.h>
6+ #include <libavcodec/avcodec.h>
7+
8+
9+ AVPacketQueue * queue_init (int size ){
10+ AVPacketQueue * queue = malloc (sizeof (AVPacketQueue ));
11+ queue -> size = size ;
12+ queue -> next_to_read = 0 ;
13+ queue -> next_to_write = 0 ;
14+ int i ;
15+ queue -> packets = malloc (sizeof (* queue -> packets ) * size );
16+ for (i = 0 ; i < size ; i ++ ){
17+ queue -> packets [i ] = malloc (sizeof (AVPacket ));
18+ }
19+ return queue ;
20+ }
21+
22+ void queue_free (AVPacketQueue * queue ){
23+ int i ;
24+ for (i = 0 ; i < queue -> size ; i ++ ){
25+ free (queue -> packets [i ]);
26+ }
27+ free (queue -> packets );
28+ free (queue );
29+ }
30+
31+ int queue_next (AVPacketQueue * queue , int current ){
32+ return (current + 1 ) % queue -> size ;
33+ }
34+
35+ void * queue_push (AVPacketQueue * queue , pthread_mutex_t * mutex , pthread_cond_t * cond ){
36+ int current = queue -> next_to_write ;
37+ int next_to_write ;
38+ for (;;){
39+ next_to_write = queue_next (queue , current );
40+ //写的不等于读的,跳出循环
41+ if (next_to_write != queue -> next_to_read ){
42+ break ;
43+ }
44+ pthread_cond_wait (cond , mutex );
45+ }
46+ queue -> next_to_write = next_to_write ;
47+ pthread_cond_broadcast (cond );
48+ return queue -> packets [current ];
49+ }
50+
51+ void * queue_pop (AVPacketQueue * queue , pthread_mutex_t * mutex , pthread_cond_t * cond ){
52+ int current = queue -> next_to_read ;
53+ for (;;){
54+ //写的不等于读的,跳出循环
55+ if (queue -> next_to_write != queue -> next_to_read ){
56+ break ;
57+ }
58+ pthread_cond_wait (cond , mutex );
59+ }
60+ queue -> next_to_read = queue_next (queue , current );
61+ pthread_cond_broadcast (cond );
62+ return queue -> packets [current ];
63+ }
0 commit comments