5 #include "protocol-native-spec.h"
8 struct pa_pdispatch *pdispatch;
9 struct reply_info *next, *previous;
10 int (*callback)(struct pa_pdispatch *pd, uint32_t command, uint32_t tag, struct pa_tagstruct *t, void *userdata);
13 void *mainloop_timeout;
17 struct pa_mainloop_api *mainloop;
18 const struct pa_pdispatch_command *command_table;
20 struct reply_info *replies;
23 static void reply_info_free(struct reply_info *r) {
24 assert(r && r->pdispatch && r->pdispatch->mainloop);
27 r->pdispatch->mainloop->cancel_time(r->pdispatch->mainloop, r->mainloop_timeout);
30 r->previous->next = r->next;
32 r->pdispatch->replies = r->next;
35 r->next->previous = r->previous;
40 struct pa_pdispatch* pa_pdispatch_new(struct pa_mainloop_api *mainloop, const struct pa_pdispatch_command*table, unsigned entries) {
41 struct pa_pdispatch *pd;
44 assert((entries && table) || (!entries && !table));
46 pd = malloc(sizeof(struct pa_pdispatch));
48 pd->mainloop = mainloop;
49 pd->command_table = table;
50 pd->n_commands = entries;
55 void pa_pdispatch_free(struct pa_pdispatch *pd) {
58 reply_info_free(pd->replies);
62 int pa_pdispatch_run(struct pa_pdispatch *pd, struct pa_packet*packet, void *userdata) {
63 uint32_t tag, command;
65 struct pa_tagstruct *ts = NULL;
66 assert(pd && packet && packet->data);
68 if (packet->length <= 8)
71 ts = pa_tagstruct_new(packet->data, packet->length);
74 if (pa_tagstruct_getu32(ts, &command) < 0 ||
75 pa_tagstruct_getu32(ts, &tag) < 0)
78 if (command == PA_COMMAND_ERROR || command == PA_COMMAND_REPLY) {
82 for (r = pd->replies; r; r = r->next) {
84 int ret = r->callback(r->pdispatch, command, tag, ts, r->userdata);
98 } else if (pd->command_table && command < pd->n_commands) {
99 const struct pa_pdispatch_command *c = pd->command_table+command;
104 if (c->proc(pd, command, tag, ts, userdata) < 0)
109 pa_tagstruct_free(ts);
115 pa_tagstruct_free(ts);
120 static void timeout_callback(struct pa_mainloop_api*m, void *id, const struct timeval *tv, void *userdata) {
121 struct reply_info*r = userdata;
122 assert (r && r->mainloop_timeout == id && r->pdispatch && r->pdispatch->mainloop == m && r->callback);
124 r->callback(r->pdispatch, PA_COMMAND_TIMEOUT, r->tag, NULL, r->userdata);
128 void pa_pdispatch_register_reply(struct pa_pdispatch *pd, uint32_t tag, int timeout, int (*cb)(struct pa_pdispatch *pd, uint32_t command, uint32_t tag, struct pa_tagstruct *t, void *userdata), void *userdata) {
129 struct reply_info *r;
133 r = malloc(sizeof(struct reply_info));
137 r->userdata = userdata;
140 gettimeofday(&tv, NULL);
141 tv.tv_sec += timeout;
143 r->mainloop_timeout = pd->mainloop->source_time(pd->mainloop, &tv, timeout_callback, r);
144 assert(r->mainloop_timeout);
147 r->next = pd->replies;
149 r->next->previous = r;