summaryrefslogtreecommitdiff
path: root/toxav/toxav.c
blob: 5683795ea0bab40e057a9ee94c4a41ed732bb7a6 (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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
/**  toxav.c
 * 
 *   Copyright (C) 2013 Tox project All Rights Reserved.
 *
 *   This file is part of Tox.
 *
 *   Tox is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   Tox is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with Tox. If not, see <http://www.gnu.org/licenses/>.
 *
 * 
 *   Report bugs/suggestions at either #tox-dev @ freenode.net:6667 or
 *   my email: eniz_vukovic@hotmail.com
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif /* HAVE_CONFIG_H */

#include "media.h"
#include "rtp.h"
#include "msi.h"

#include <stdlib.h>
#include <string.h>
#include <assert.h>

#include "toxav.h"

#define inline__ inline __attribute__((always_inline))

static const uint8_t audio_index = 0, video_index = 1;


typedef enum {
    ts_closing,
    ts_running,
    ts_closed
    
} ThreadState;

typedef struct _ToxAv
{
    Messenger* messenger;
    
    MSISession* msi_session; /** Main msi session */
    
    RTPSession* rtp_sessions[2]; /* Audio is first and video is second */
    
    /* TODO: Add media session */
    struct jitter_buffer* j_buf;
    CodecState* cs;
    /* TODO: Add media session threads */
    
    
    void* agent_handler;    
} ToxAv;





/********************************************************************************************************************  
 ********************************************************************************************************************
 ********************************************************************************************************************
 ********************************************************************************************************************
 ********************************************************************************************************************
 * 
 * 
 * 
 * PUBLIC API FUNCTIONS IMPLEMENTATIONS
 * 
 * 
 * 
 ********************************************************************************************************************
 ********************************************************************************************************************
 ********************************************************************************************************************
 ********************************************************************************************************************
 ********************************************************************************************************************/



ToxAv* toxav_new( Tox* messenger, void* useragent, const char* ua_name , uint16_t video_width, uint16_t video_height) 
{
    ToxAv* av = calloc ( sizeof(ToxAv), 1);
    if (av == NULL)
        return NULL;

    av->messenger = (Messenger *)messenger;

    av->msi_session = msi_init_session(av->messenger, (const unsigned char*) ua_name );
    av->msi_session->agent_handler = av;
    
    av->rtp_sessions[0] = av->rtp_sessions [1] = NULL;

    /* NOTE: This should be user defined or? */
    av->j_buf = create_queue(20);
    
    av->cs = codec_init_session(AUDIO_BITRATE, AUDIO_FRAME_DURATION, AUDIO_SAMPLE_RATE, AUDIO_CHANNELS, video_width, video_height, VIDEO_BITRATE);
    
    av->agent_handler = useragent;
    
    return av;
}

void toxav_kill ( ToxAv* av ) 
{    
    msi_terminate_session(av->msi_session);
    
    if ( av->rtp_sessions[audio_index] ) {
        rtp_terminate_session(av->rtp_sessions[audio_index], av->msi_session->messenger_handle);
    }
    
    if ( av->rtp_sessions[video_index] ) {
        rtp_terminate_session(av->rtp_sessions[video_index], av->msi_session->messenger_handle);
    }
    
    codec_terminate_session(av->cs);
    
    free(av);
}

void toxav_register_callstate_callback ( ToxAVCallback callback, ToxAvCallbackID id ) 
{
    msi_register_callback((MSICallback)callback, (MSICallbackID) id);
}



int toxav_call (ToxAv* av, int user, ToxAvCallType call_type, int ringing_seconds ) 
{
    if ( av->msi_session->call ) {
        return ErrorAlreadyInCall;
    }
    
    return msi_invite(av->msi_session, call_type, ringing_seconds * 1000, user);
}

int toxav_hangup ( ToxAv* av ) 
{
    if ( !av->msi_session->call ) {
        return ErrorNoCall;
    }
    
    if ( av->msi_session->call->state != call_active ) {
        return ErrorInvalidState;
    }
    
    return msi_hangup(av->msi_session);
}

int toxav_answer ( ToxAv* av, ToxAvCallType call_type ) 
{
    if ( !av->msi_session->call ) {
        return ErrorNoCall;
    }
    
    if ( av->msi_session->call->state != call_starting ) {
        return ErrorInvalidState;
    }
    
    return msi_answer(av->msi_session, call_type);
}

int toxav_reject ( ToxAv* av, const char* reason ) 
{
    if ( !av->msi_session->call ) {
        return ErrorNoCall;
    }

    if ( av->msi_session->call->state != call_starting ) {
        return ErrorInvalidState;
    }

    return msi_reject(av->msi_session, (const uint8_t*) reason);
}

int toxav_cancel ( ToxAv* av, const char* reason )
{
    if ( !av->msi_session->call ) {
        return ErrorNoCall;
    }
    
    return msi_cancel(av->msi_session, 0, (const uint8_t*)reason);
}

/* You can stop the call at any state */
int toxav_stop_call ( ToxAv* av ) 
{
    if ( !av->msi_session->call ) {
        return ErrorNoCall;
    }
    
    return msi_stopcall(av->msi_session);
}


int toxav_prepare_transmission ( ToxAv* av ) 
{
    assert(av->msi_session);
    if ( !av->msi_session || !av->msi_session->call ) {
        return ErrorNoCall;
    }
    
    av->rtp_sessions[audio_index] = rtp_init_session(
                                    type_audio,
                                    av->messenger, 
                                    av->msi_session->call->peers[0],
                                    av->msi_session->call->key_peer,
                                    av->msi_session->call->key_local,
                                    av->msi_session->call->nonce_peer,
                                    av->msi_session->call->nonce_local
                                    );
    
    
    if ( !av->rtp_sessions[audio_index] ) {
        fprintf(stderr, "Error while starting audio RTP session!\n");
        return ErrorStartingAudioRtp;
    }
    
    av->rtp_sessions[video_index] = rtp_init_session ( 
                                    type_video,
                                    av->messenger, 
                                    av->msi_session->call->peers[0],
                                    av->msi_session->call->key_peer,
                                    av->msi_session->call->key_local,
                                    av->msi_session->call->nonce_peer,
                                    av->msi_session->call->nonce_local
                                    );
    
    
    if ( !av->rtp_sessions[video_index] ) {
        fprintf(stderr, "Error while starting video RTP session!\n");
        return ErrorStartingVideoRtp;
    }
    
    return ErrorNone;
}


int toxav_kill_transmission ( ToxAv* av ) 
{
    /* Both sessions should be active at any time */
    if ( !av->rtp_sessions[0] || !av->rtp_sessions[0] )
        return ErrorNoTransmission;
    
    
    if ( -1 == rtp_terminate_session(av->rtp_sessions[audio_index], av->messenger) ) {
        fprintf(stderr, "Error while terminating audio RTP session!\n");
        return ErrorTerminatingAudioRtp;
    }
    
    if ( -1 == rtp_terminate_session(av->rtp_sessions[video_index], av->messenger) ) {
        fprintf(stderr, "Error while terminating video RTP session!\n");
        return ErrorTerminatingVideoRtp;
    }
    
    return ErrorNone;
}


inline__ int toxav_send_rtp_payload ( ToxAv* av, ToxAvCallType type, const uint8_t* payload, uint16_t length ) 
{
    if ( av->rtp_sessions[type - TypeAudio] )
        return rtp_send_msg ( av->rtp_sessions[type - TypeAudio], av->msi_session->messenger_handle, payload, length );
    else return -1;
}

inline__ int toxav_recv_rtp_payload ( ToxAv* av, ToxAvCallType type, uint8_t* dest ) 
{
    if ( !dest ) return ErrorInternal;
    
    if ( !av->rtp_sessions[type - TypeAudio] ) return ErrorNoRtpSession;
    
    RTPMessage* message;
    
    if ( type == TypeAudio ) {
        
        do {
            message = rtp_recv_msg(av->rtp_sessions[audio_index]);
            
            if (message) {
                /* push the packet into the queue */
                queue(av->j_buf, message);
            }
        } while(message);
        
        int success = 0;
        message = dequeue(av->j_buf, &success);

        if ( success == 2) return ErrorAudioPacketLost;
    }
    else {
        message = rtp_recv_msg(av->rtp_sessions[video_index]);
    }
        
    if ( message ) {    
        memcpy(dest, message->data, message->length);
        
        int length = message->length;
        
        rtp_free_msg(NULL, message);
                
        return length;
    }
    
    return 0;
}

inline__ int toxav_recv_video ( ToxAv* av, vpx_image_t **output) 
{
    if ( !output ) return ErrorInternal;
    uint8_t packet [RTP_PAYLOAD_SIZE];
    int recved_size = 0;
    do {
        recved_size = toxav_recv_rtp_payload(av, TypeVideo, packet);
        if (recved_size > 0) {
            printf("decode: %s\n", vpx_codec_err_to_string(vpx_codec_decode(&av->cs->v_decoder, packet, recved_size, NULL, 0)));
        }
    }while (recved_size > 0);
    vpx_codec_iter_t iter = NULL;
    vpx_image_t *img;
    img = vpx_codec_get_frame(&av->cs->v_decoder, &iter);
    if (img == NULL)
        return ErrorInternal;
    
    *output = img;
    return 0;
}

inline__ int toxav_send_video ( ToxAv* av, vpx_image_t *input)
{
    if (vpx_codec_encode(&av->cs->v_encoder, input, av->cs->frame_counter, 1, 0, MAX_ENCODE_TIME_US) != VPX_CODEC_OK) {
        printf("could not encode video frame\n");
        return ErrorInternal;
    }
    ++av->cs->frame_counter;
    
    vpx_codec_iter_t iter = NULL;
    const vpx_codec_cx_pkt_t *pkt;
    int sent = 0;
    while( (pkt = vpx_codec_get_cx_data(&av->cs->v_encoder, &iter)) ) {
        if (pkt->kind == VPX_CODEC_CX_FRAME_PKT) {
            if (toxav_send_rtp_payload(av, TypeVideo, pkt->data.frame.buf, pkt->data.frame.sz) != -1)
                ++sent;
        }
    }
    if (sent > 0)
        return 0;
    
    return ErrorInternal;
}

inline__ int toxav_recv_audio ( ToxAv* av, int frame_size, int16_t* dest ) 
{
    if ( !dest ) return ErrorInternal;
    uint8_t packet [RTP_PAYLOAD_SIZE];

    int recved_size = toxav_recv_rtp_payload(av, TypeAudio, packet);

    if ( recved_size == ErrorAudioPacketLost ) {
        printf("Lost packet\n");
        return opus_decode(av->cs->audio_decoder, NULL, 0, dest, frame_size, 1);
    } else if ( recved_size ){
        return opus_decode(av->cs->audio_decoder, packet, recved_size, dest, frame_size, 0);
    } else {
        return ErrorInternal;
    }
}

inline__ int toxav_send_audio ( ToxAv* av, const int16_t* frame, int frame_size)
{
    uint8_t temp_data[RTP_PAYLOAD_SIZE];
    int32_t ret = opus_encode(av->cs->audio_encoder, frame, frame_size, temp_data, sizeof(temp_data));
    if (ret <= 0)
        return ErrorInternal;

    return toxav_send_rtp_payload(av, TypeAudio, temp_data, ret);
}

int toxav_get_peer_transmission_type ( ToxAv* av, int peer ) 
{
    assert(av->msi_session);
    if ( peer < 0 || !av->msi_session->call || av->msi_session->call->peer_count <= peer )
        return ErrorInternal;
    
    return av->msi_session->call->type_peer[peer];
}

void* toxav_get_agent_handler ( ToxAv* av ) 
{
    return av->agent_handler;
}